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 |
|---|---|---|---|---|---|---|---|---|
548df07ea2fbc85e00264819fa91e3c3a1a6cae8 | Throw on null json. | PenguinF/sandra-three | Sandra.UI.WF/Storage/JsonSyntax.cs | Sandra.UI.WF/Storage/JsonSyntax.cs | #region License
/*********************************************************************************
* JsonSyntax.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
#endregion
using System;
namespace Sandra.UI.WF.Storage
{
public class JsonTerminalSymbol
{
public JsonTerminalSymbol(string json, int start, int length)
{
if (json == null) throw new ArgumentNullException(nameof(json));
}
}
}
| #region License
/*********************************************************************************
* JsonSyntax.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
#endregion
namespace Sandra.UI.WF.Storage
{
public class JsonTerminalSymbol
{
public JsonTerminalSymbol(string json, int start, int length)
{
}
}
}
| apache-2.0 | C# |
7ee53373c61eec5f3376ea64317c1f98f338d0b2 | Remove tests as AppVeyor can’t handle them at the moment | adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress | build.cake | build.cake | var target = Argument("target", "Default");
var tag = Argument("tag", "cake");
Task("Restore")
.Does(() =>
{
DotNetCoreRestore(".");
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
if (IsRunningOnWindows())
{
MSBuild("./sharpcompress.sln", c =>
{
c.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.UseToolVersion(MSBuildToolVersion.VS2017);
});
}
else
{
var settings = new DotNetCoreBuildSettings
{
Framework = "netstandard1.0",
Configuration = "Release",
NoRestore = true
};
DotNetCoreBuild("./src/SharpCompress/SharpCompress.csproj", settings);
settings.Framework = "netstandard1.3";
DotNetCoreBuild("./src/SharpCompress/SharpCompress.csproj", settings);
settings.Framework = "netstandard2.0";
DotNetCoreBuild("./src/SharpCompress/SharpCompress.csproj", settings);
}
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var files = GetFiles("tests/**/*.csproj");
foreach(var file in files)
{
var settings = new DotNetCoreTestSettings
{
Configuration = "Release",
Framework = "netcoreapp2.1"
};
DotNetCoreTest(file.ToString(), settings);
}
});
Task("Pack")
.IsDependentOn("Build")
.Does(() =>
{
if (IsRunningOnWindows())
{
MSBuild("src/SharpCompress/SharpCompress.csproj", c => c
.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.UseToolVersion(MSBuildToolVersion.VS2017)
.WithProperty("NoBuild", "true")
.WithTarget("Pack"));
}
else
{
Information("Skipping Pack as this is not Windows");
}
});
Task("Default")
.IsDependentOn("Restore")
.IsDependentOn("Build")
//.IsDependentOn("Test")
.IsDependentOn("Pack");
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("Test");
RunTarget(target); | var target = Argument("target", "Default");
var tag = Argument("tag", "cake");
Task("Restore")
.Does(() =>
{
DotNetCoreRestore(".");
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
if (IsRunningOnWindows())
{
MSBuild("./sharpcompress.sln", c =>
{
c.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.UseToolVersion(MSBuildToolVersion.VS2017);
});
}
else
{
var settings = new DotNetCoreBuildSettings
{
Framework = "netstandard1.0",
Configuration = "Release",
NoRestore = true
};
DotNetCoreBuild("./src/SharpCompress/SharpCompress.csproj", settings);
settings.Framework = "netstandard1.3";
DotNetCoreBuild("./src/SharpCompress/SharpCompress.csproj", settings);
settings.Framework = "netstandard2.0";
DotNetCoreBuild("./src/SharpCompress/SharpCompress.csproj", settings);
}
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var files = GetFiles("tests/**/*.csproj");
foreach(var file in files)
{
var settings = new DotNetCoreTestSettings
{
Configuration = "Release",
Framework = "netcoreapp2.1"
};
DotNetCoreTest(file.ToString(), settings);
}
});
Task("Pack")
.IsDependentOn("Build")
.Does(() =>
{
if (IsRunningOnWindows())
{
MSBuild("src/SharpCompress/SharpCompress.csproj", c => c
.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.UseToolVersion(MSBuildToolVersion.VS2017)
.WithProperty("NoBuild", "true")
.WithTarget("Pack"));
}
else
{
Information("Skipping Pack as this is not Windows");
}
});
Task("Default")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("Test")
.IsDependentOn("Pack");
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("Test");
RunTarget(target); | mit | C# |
7722a7d543c164f799ceb15797bcf07d77477628 | Make sure all packages are built. | spectresystems/spectre.system | build.cake | build.cake | #load "./scripts/version.cake"
#load "./scripts/msbuild.cake"
#tool "nuget:https://www.nuget.org/api/v2?package=GitVersion.CommandLine&version=3.6.2"
var configuration = Argument("configuration", "Release");
var target = Argument("target", "Default");
var version = BuildVersion.Calculate(Context);
var settings = MSBuildHelper.CreateSettings(version);
Task("Clean")
.Does(() =>
{
CleanDirectory("./.artifacts");
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
DotNetCoreRestore("./src/Spectre.System.sln");
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
DotNetCoreBuild("./src/Spectre.System.sln", new DotNetCoreBuildSettings {
Configuration = "Release",
MSBuildSettings = settings
});
});
Task("Run-Tests")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./src/Spectre.System.Tests/Spectre.System.Tests.csproj", new DotNetCoreTestSettings {
Configuration = "Release"
});
});
Task("Package")
.IsDependentOn("Run-Tests")
.Does(() =>
{
DotNetCorePack("./src/Spectre.System/Spectre.System.csproj", new DotNetCorePackSettings {
Configuration = "Release",
OutputDirectory = "./.artifacts",
MSBuildSettings = settings
});
DotNetCorePack("./src/Spectre.System.sln", new DotNetCorePackSettings {
Configuration = "Release",
OutputDirectory = "./.artifacts",
MSBuildSettings = settings
});
});
Task("Default")
.IsDependentOn("Package");
Task("AppVeyor")
.IsDependentOn("Default");
RunTarget(target); | #load "./scripts/version.cake"
#load "./scripts/msbuild.cake"
#tool "nuget:https://www.nuget.org/api/v2?package=GitVersion.CommandLine&version=3.6.2"
var configuration = Argument("configuration", "Release");
var target = Argument("target", "Default");
var version = BuildVersion.Calculate(Context);
var settings = MSBuildHelper.CreateSettings(version);
Task("Clean")
.Does(() =>
{
CleanDirectory("./.artifacts");
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
DotNetCoreRestore("./src/Spectre.System.sln");
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
DotNetCoreBuild("./src/Spectre.System.sln", new DotNetCoreBuildSettings {
Configuration = "Release",
MSBuildSettings = settings
});
});
Task("Run-Tests")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./src/Spectre.System.Tests/Spectre.System.Tests.csproj", new DotNetCoreTestSettings {
Configuration = "Release"
});
});
Task("Package")
.IsDependentOn("Run-Tests")
.Does(() =>
{
DotNetCorePack("./src/Spectre.System/Spectre.System.csproj", new DotNetCorePackSettings {
Configuration = "Release",
OutputDirectory = "./.artifacts",
MSBuildSettings = settings
});
});
Task("Default")
.IsDependentOn("Package");
Task("AppVeyor")
.IsDependentOn("Default");
RunTarget(target); | mit | C# |
58be4c95adb1e1984387ba50b8f20aee933fe096 | support fancy tls k thnx bai | ericdc1/DTMF,ericdc1/DTMF,ericdc1/DTMF | Source/DTMF.Website/Global.asax.cs | Source/DTMF.Website/Global.asax.cs | using System.Net;
using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace DTMF
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Role;
}
}
}
| using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace DTMF
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Role;
}
}
}
| mit | C# |
4cd5634060818e713c77d54c0db98b5d5ac3e226 | Fix DataCenter enum in tests project | NFig/NFig | NFig.Tests/Common/Enums.cs | NFig.Tests/Common/Enums.cs | namespace NFig.Tests.Common
{
public enum Tier
{
Any = 0,
Local = 1,
Dev = 2,
Prod = 3,
}
public enum DataCenter
{
Any = 0,
Local = 1,
East = 2,
West = 3,
}
} | namespace NFig.Tests.Common
{
public enum Tier
{
Any = 0,
Local = 1,
Dev = 2,
Prod = 3,
}
public enum DataCenter
{
Any = 0,
Local = 1,
Dev = 2,
Prod = 3,
}
} | mit | C# |
08b2b0960d0da0930091170450af0b8dca065501 | Update AlreadyCaptured message | cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,UdiBen/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,RossLieberman/NEST,elastic/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,azubanov/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net | src/Elasticsearch.Net/Responses/ElasticsearchResponse.cs | src/Elasticsearch.Net/Responses/ElasticsearchResponse.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Elasticsearch.Net
{
internal static class ResponseStatics
{
public static readonly string PrintFormat = "StatusCode: {1}, {0}\tMethod: {2}, {0}\tUrl: {3}, {0}\tRequest: {4}, {0}\tResponse: {5}";
public static readonly string ErrorFormat = "{0}\tExceptionMessage: {1}{0}\t StackTrace: {2}";
public static readonly string AlreadyCaptured = "<Response stream not captured or already read to completion by serializer. Set DisableDirectStreaming() on ConnectionSettings to force it to be set on the response.>";
}
public class ElasticsearchResponse<T> : IApiCallDetails
{
public bool Success { get; }
public HttpMethod HttpMethod { get; internal set; }
public Uri Uri { get; internal set; }
/// <summary>The raw byte request message body, only set when DisableDirectStreaming() is set on Connection configuration</summary>
public byte[] RequestBodyInBytes { get; internal set; }
/// <summary>The raw byte response message body, only set when DisableDirectStreaming() is set on Connection configuration</summary>
public byte[] ResponseBodyInBytes { get; internal set; }
public T Body { get; protected internal set; }
public int? HttpStatusCode { get; }
public List<Audit> AuditTrail { get; internal set; }
/// <summary>
/// The response is succesful or has a response code between 400-599 the call should not be retried.
/// Only on 502 and 503 will this return false;
/// </summary>
public bool SuccessOrKnownError =>
this.Success || (HttpStatusCode >= 400 && HttpStatusCode < 599
&& HttpStatusCode != 503 //service unavailable needs to be retried
&& HttpStatusCode != 502 //bad gateway needs to be retried
);
public Exception OriginalException { get; protected internal set; }
public ServerError ServerError { get; internal set; }
public ElasticsearchResponse(Exception e)
{
this.Success = false;
this.OriginalException = e;
}
public ElasticsearchResponse(int statusCode, IEnumerable<int> allowedStatusCodes)
{
this.Success = statusCode >= 200 && statusCode < 300 || allowedStatusCodes.Contains(statusCode);
this.HttpStatusCode = statusCode;
}
public override string ToString()
{
var r = this;
var e = r.OriginalException;
var response = this.ResponseBodyInBytes?.Utf8String() ?? ResponseStatics.AlreadyCaptured;
var requestJson = r.RequestBodyInBytes?.Utf8String();
var print = string.Format(ResponseStatics.PrintFormat,
Environment.NewLine,
r.HttpStatusCode.HasValue ? r.HttpStatusCode.Value.ToString(CultureInfo.InvariantCulture) : "-1",
r.HttpMethod,
r.Uri,
requestJson,
response
);
if (!this.Success && e != null)
print += string.Format(ResponseStatics.ErrorFormat,Environment.NewLine, e.Message, e.StackTrace);
return print;
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Elasticsearch.Net
{
internal static class ResponseStatics
{
public static readonly string PrintFormat = "StatusCode: {1}, {0}\tMethod: {2}, {0}\tUrl: {3}, {0}\tRequest: {4}, {0}\tResponse: {5}";
public static readonly string ErrorFormat = "{0}\tExceptionMessage: {1}{0}\t StackTrace: {2}";
public static readonly string AlreadyCaptured = "<Response stream not captured or already read to completion by serializer, set ExposeRawResponse() on connectionsettings to force it to be set on>";
}
public class ElasticsearchResponse<T> : IApiCallDetails
{
public bool Success { get; }
public HttpMethod HttpMethod { get; internal set; }
public Uri Uri { get; internal set; }
/// <summary>The raw byte request message body, only set when DisableDirectStreaming() is set on Connection configuration</summary>
public byte[] RequestBodyInBytes { get; internal set; }
/// <summary>The raw byte response message body, only set when DisableDirectStreaming() is set on Connection configuration</summary>
public byte[] ResponseBodyInBytes { get; internal set; }
public T Body { get; protected internal set; }
public int? HttpStatusCode { get; }
public List<Audit> AuditTrail { get; internal set; }
/// <summary>
/// The response is succesful or has a response code between 400-599 the call should not be retried.
/// Only on 502 and 503 will this return false;
/// </summary>
public bool SuccessOrKnownError =>
this.Success || (HttpStatusCode >= 400 && HttpStatusCode < 599
&& HttpStatusCode != 503 //service unavailable needs to be retried
&& HttpStatusCode != 502 //bad gateway needs to be retried
);
public Exception OriginalException { get; protected internal set; }
public ServerError ServerError { get; internal set; }
public ElasticsearchResponse(Exception e)
{
this.Success = false;
this.OriginalException = e;
}
public ElasticsearchResponse(int statusCode, IEnumerable<int> allowedStatusCodes)
{
this.Success = statusCode >= 200 && statusCode < 300 || allowedStatusCodes.Contains(statusCode);
this.HttpStatusCode = statusCode;
}
public override string ToString()
{
var r = this;
var e = r.OriginalException;
var response = this.ResponseBodyInBytes?.Utf8String() ?? ResponseStatics.AlreadyCaptured;
var requestJson = r.RequestBodyInBytes?.Utf8String();
var print = string.Format(ResponseStatics.PrintFormat,
Environment.NewLine,
r.HttpStatusCode.HasValue ? r.HttpStatusCode.Value.ToString(CultureInfo.InvariantCulture) : "-1",
r.HttpMethod,
r.Uri,
requestJson,
response
);
if (!this.Success && e != null)
print += string.Format(ResponseStatics.ErrorFormat,Environment.NewLine, e.Message, e.StackTrace);
return print;
}
}
}
| apache-2.0 | C# |
56b5074c7b2735d2b624c500903d330f2e9359cf | Remove unneeded using | aloisdg/CountPages,saidmarouf/Doccou,aloisdg/Doccou | Counter/ADocument.cs | Counter/ADocument.cs | namespace Counter
{
internal abstract class ADocument : IDocument
{
public abstract DocumentType Type { get; }
public abstract uint Count { get; protected set; }
}
} | using System.IO;
namespace Counter
{
internal abstract class ADocument : IDocument
{
public abstract DocumentType Type { get; }
public abstract uint Count { get; protected set; }
}
} | mit | C# |
364be852c58728026deacc492035e7a8ddf06599 | remove code | bitsummation/pickaxe,bitsummation/pickaxe | Pickaxe/ConsoleAppender.cs | Pickaxe/ConsoleAppender.cs | using log4net.Appender;
using Pickaxe.PlatConsole;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pickaxe
{
public class ConsoleAppender : AppenderSkeleton
{
public static object ConsoleWriteLock = new object();
internal static IConsole PlatConsole;
static ConsoleAppender()
{
PlatConsole = CreateConsole();
}
private static IConsole CreateConsole()
{
if (IsWindows)
return new WindowsConsole();
return new UnixConsole();
}
protected override void Append(log4net.Core.LoggingEvent loggingEvent)
{
lock (ConsoleWriteLock)
{
PlatConsole.MoveCursor(PlatConsole.StartLine);
PlatConsole.ClearLine(PlatConsole.StartLine);
PlatConsole.Print(RenderLoggingEvent(loggingEvent));
}
}
public static bool IsWindows
{
get
{
return !(Environment.OSVersion.Platform == PlatformID.MacOSX
|| Environment.OSVersion.Platform == PlatformID.Unix);
}
}
}
}
| using log4net.Appender;
using Pickaxe.PlatConsole;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pickaxe
{
public class ConsoleAppender : AppenderSkeleton
{
public static object ConsoleWriteLock = new object();
internal static IConsole PlatConsole;
static ConsoleAppender()
{
PlatConsole = CreateConsole();
}
private static IConsole CreateConsole()
{
if (IsWindows)
return new WindowsConsole();
return new UnixConsole();
}
protected override void Append(log4net.Core.LoggingEvent loggingEvent)
{
lock (ConsoleWriteLock)
{
PlatConsole.MoveCursor(PlatConsole.StartLine);
PlatConsole.ClearLine(PlatConsole.StartLine);
PlatConsole.Print(RenderLoggingEvent(loggingEvent));
}
}
//public static int StartCursorTop { get; set; }
//public static int CurrentLine { get; set; }
public static bool IsWindows
{
get
{
return !(Environment.OSVersion.Platform == PlatformID.MacOSX
|| Environment.OSVersion.Platform == PlatformID.Unix);
}
}
/*public static void SetCursor(int position)
{
if (IsWindows)
Console.SetCursorPosition(0, position);
else
{
Console.Write("\u001b[2J");
Console.Write("\u001b[{0};{1}H", 1, 0); //set line
Console.WriteLine("Print this line");
Console.Write("\u001b[{0};{1}H", 1, 0); //set line
Console.Write("\u001b[K"); //erase line
Console.WriteLine("Erase");
Console.WriteLine("Another");
Console.Write("\u001b[K"); //erase line
Console.Write("\u001b[{0};{1}H", 5, 0); //set line
Console.WriteLine("Down");
Console.WriteLine("Down again");
}
}*/
/*public static void ClearConsoleLine(int line)
{
Console.SetCursorPosition(0, line);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, line);
}*/
}
}
| apache-2.0 | C# |
cb252ddb9ecd9abb861cc432e400b2f07806c73e | Update AssemblyInfo.cs | BlarghLabs/MoarUtils | Properties/AssemblyInfo.cs | 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("MoarUtils")]
[assembly: AssemblyDescription("Useful utilities to more efficient .NET development #OnTheShouldersOfGiants")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("BlarghLabs")]
[assembly: AssemblyProduct(" MoarUtils")]
[assembly: AssemblyCopyright("Copyright © 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("8d9b5637-f1bd-4936-a007-3b2b539f2c58")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MoarUtils")]
[assembly: AssemblyDescription("Useful utilities to more efficient .NET development #OnTheShouldersOfGiants")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("BlarghLabs")]
[assembly: AssemblyProduct(" MoarUtils")]
[assembly: AssemblyCopyright("Copyright © 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("8d9b5637-f1bd-4936-a007-3b2b539f2c58")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyVersion("1.0.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
4dd5ab4c50d455c2fcdbd589bf02854d25580ca1 | Update version to 1.2.15 | anonymousthing/ListenMoeClient | Properties/AssemblyInfo.cs | 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("Listen.moe Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Listen.moe Client")]
[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("88b02799-425e-4622-a849-202adb19601b")]
// 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.2.15.0")]
[assembly: AssemblyFileVersion("1.2.15.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Listen.moe Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Listen.moe Client")]
[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("88b02799-425e-4622-a849-202adb19601b")]
// 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.2.14.0")]
[assembly: AssemblyFileVersion("1.2.14.0")]
| mit | C# |
d9ed63529f842f173683e5b1b95871ddf1966f71 | Bump version number. | lukesampson/HastyAPI,lukesampson/HastyAPI | Properties/AssemblyInfo.cs | 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("HastyAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HastyAPI")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("9090dc7c-d62c-41d3-9296-7ef2e1610a2f")]
// 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.16")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HastyAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HastyAPI")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("9090dc7c-d62c-41d3-9296-7ef2e1610a2f")]
// 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.15")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
d0fedb8fcde7aa47013dece723627c2274726590 | Update assembly to v1.1 | nagilum/dcm | Properties/AssemblyInfo.cs | 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("Digital Color Meter")]
[assembly: AssemblyDescription("Released under the MIT License")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Digital Color Meter")]
[assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")]
[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("ca199dd4-2017-4ee7-808c-3747101e04b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| 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("Digital Color Meter")]
[assembly: AssemblyDescription("Released under the MIT License")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Digital Color Meter")]
[assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")]
[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("ca199dd4-2017-4ee7-808c-3747101e04b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
2714d0e8829322d5e0c07aa1b2800349e6c008bd | Fix "Too many open files" in MMF perf test | dhoehna/corefx,mmitche/corefx,zhenlan/corefx,rjxby/corefx,cydhaselton/corefx,mmitche/corefx,dhoehna/corefx,tijoytom/corefx,shimingsg/corefx,parjong/corefx,axelheer/corefx,elijah6/corefx,shimingsg/corefx,zhenlan/corefx,ViktorHofer/corefx,nchikanov/corefx,billwert/corefx,seanshpark/corefx,dotnet-bot/corefx,jlin177/corefx,ericstj/corefx,dotnet-bot/corefx,DnlHarvey/corefx,stone-li/corefx,zhenlan/corefx,parjong/corefx,rjxby/corefx,krk/corefx,stephenmichaelf/corefx,alexperovich/corefx,Jiayili1/corefx,stephenmichaelf/corefx,shimingsg/corefx,gkhanna79/corefx,YoupHulsebos/corefx,elijah6/corefx,ViktorHofer/corefx,dhoehna/corefx,yizhang82/corefx,richlander/corefx,yizhang82/corefx,MaggieTsang/corefx,nchikanov/corefx,ravimeda/corefx,elijah6/corefx,BrennanConroy/corefx,JosephTremoulet/corefx,stone-li/corefx,the-dwyer/corefx,weltkante/corefx,JosephTremoulet/corefx,yizhang82/corefx,gkhanna79/corefx,stone-li/corefx,Ermiar/corefx,YoupHulsebos/corefx,alexperovich/corefx,Ermiar/corefx,ericstj/corefx,weltkante/corefx,Jiayili1/corefx,ericstj/corefx,twsouthwick/corefx,the-dwyer/corefx,rubo/corefx,parjong/corefx,MaggieTsang/corefx,alexperovich/corefx,Jiayili1/corefx,nbarbettini/corefx,axelheer/corefx,krytarowski/corefx,weltkante/corefx,krytarowski/corefx,elijah6/corefx,the-dwyer/corefx,richlander/corefx,rjxby/corefx,jlin177/corefx,krytarowski/corefx,cydhaselton/corefx,DnlHarvey/corefx,DnlHarvey/corefx,ericstj/corefx,ptoonen/corefx,zhenlan/corefx,DnlHarvey/corefx,rjxby/corefx,billwert/corefx,tijoytom/corefx,fgreinacher/corefx,parjong/corefx,shimingsg/corefx,wtgodbe/corefx,tijoytom/corefx,nbarbettini/corefx,YoupHulsebos/corefx,axelheer/corefx,MaggieTsang/corefx,nchikanov/corefx,rubo/corefx,zhenlan/corefx,fgreinacher/corefx,zhenlan/corefx,stone-li/corefx,krytarowski/corefx,MaggieTsang/corefx,gkhanna79/corefx,DnlHarvey/corefx,BrennanConroy/corefx,fgreinacher/corefx,yizhang82/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,krytarowski/corefx,seanshpark/corefx,mazong1123/corefx,rjxby/corefx,tijoytom/corefx,rubo/corefx,mazong1123/corefx,dhoehna/corefx,rjxby/corefx,nbarbettini/corefx,nbarbettini/corefx,ptoonen/corefx,billwert/corefx,YoupHulsebos/corefx,twsouthwick/corefx,dotnet-bot/corefx,ravimeda/corefx,stone-li/corefx,billwert/corefx,twsouthwick/corefx,gkhanna79/corefx,stephenmichaelf/corefx,alexperovich/corefx,gkhanna79/corefx,jlin177/corefx,axelheer/corefx,cydhaselton/corefx,billwert/corefx,yizhang82/corefx,wtgodbe/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,alexperovich/corefx,weltkante/corefx,gkhanna79/corefx,MaggieTsang/corefx,rubo/corefx,Ermiar/corefx,JosephTremoulet/corefx,stephenmichaelf/corefx,shimingsg/corefx,rjxby/corefx,mazong1123/corefx,cydhaselton/corefx,wtgodbe/corefx,the-dwyer/corefx,nchikanov/corefx,ravimeda/corefx,krk/corefx,ravimeda/corefx,dotnet-bot/corefx,ravimeda/corefx,Jiayili1/corefx,dhoehna/corefx,dotnet-bot/corefx,dhoehna/corefx,wtgodbe/corefx,Ermiar/corefx,parjong/corefx,krytarowski/corefx,twsouthwick/corefx,ptoonen/corefx,richlander/corefx,DnlHarvey/corefx,mmitche/corefx,richlander/corefx,mazong1123/corefx,parjong/corefx,dhoehna/corefx,stephenmichaelf/corefx,stone-li/corefx,twsouthwick/corefx,ViktorHofer/corefx,DnlHarvey/corefx,elijah6/corefx,Jiayili1/corefx,mmitche/corefx,mazong1123/corefx,shimingsg/corefx,weltkante/corefx,tijoytom/corefx,stephenmichaelf/corefx,stone-li/corefx,alexperovich/corefx,seanshpark/corefx,MaggieTsang/corefx,tijoytom/corefx,shimingsg/corefx,elijah6/corefx,krytarowski/corefx,dotnet-bot/corefx,wtgodbe/corefx,cydhaselton/corefx,seanshpark/corefx,mazong1123/corefx,Ermiar/corefx,axelheer/corefx,ptoonen/corefx,ericstj/corefx,cydhaselton/corefx,ViktorHofer/corefx,the-dwyer/corefx,billwert/corefx,nbarbettini/corefx,YoupHulsebos/corefx,wtgodbe/corefx,krk/corefx,rubo/corefx,parjong/corefx,billwert/corefx,jlin177/corefx,seanshpark/corefx,ptoonen/corefx,cydhaselton/corefx,BrennanConroy/corefx,nchikanov/corefx,fgreinacher/corefx,alexperovich/corefx,ptoonen/corefx,krk/corefx,seanshpark/corefx,ViktorHofer/corefx,krk/corefx,ravimeda/corefx,seanshpark/corefx,twsouthwick/corefx,richlander/corefx,jlin177/corefx,dotnet-bot/corefx,krk/corefx,YoupHulsebos/corefx,wtgodbe/corefx,elijah6/corefx,ericstj/corefx,JosephTremoulet/corefx,yizhang82/corefx,mazong1123/corefx,weltkante/corefx,mmitche/corefx,YoupHulsebos/corefx,Jiayili1/corefx,jlin177/corefx,stephenmichaelf/corefx,Ermiar/corefx,Ermiar/corefx,mmitche/corefx,Jiayili1/corefx,nchikanov/corefx,axelheer/corefx,MaggieTsang/corefx,yizhang82/corefx,zhenlan/corefx,weltkante/corefx,nchikanov/corefx,nbarbettini/corefx,jlin177/corefx,nbarbettini/corefx,richlander/corefx,JosephTremoulet/corefx,the-dwyer/corefx,the-dwyer/corefx,ravimeda/corefx,ericstj/corefx,twsouthwick/corefx,mmitche/corefx,gkhanna79/corefx,krk/corefx,tijoytom/corefx,richlander/corefx | src/System.IO.MemoryMappedFiles/tests/Performance/Perf.MemoryMappedFile.cs | src/System.IO.MemoryMappedFiles/tests/Performance/Perf.MemoryMappedFile.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 Microsoft.Xunit.Performance;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Performance tests for the construction and disposal of MemoryMappedFiles of varying sizes
/// </summary>
public class Perf_MemoryMappedFile : MemoryMappedFilesTestBase
{
[Benchmark]
[InlineData(10000)]
[InlineData(100000)]
[InlineData(1000000)]
[InlineData(10000000)]
public void CreateNew(int capacity)
{
const int InnerIterations = 1000;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
for (int i = 0; i < InnerIterations; i++)
MemoryMappedFile.CreateNew(null, capacity).Dispose();
}
}
[Benchmark]
[InlineData(10000)]
[InlineData(100000)]
[InlineData(1000000)]
[InlineData(10000000)]
public void CreateFromFile(int capacity)
{
// Note that the test results will include the disposal overhead of both the MemoryMappedFile
// as well as the Accessor for it
foreach (var iteration in Benchmark.Iterations)
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (iteration.StartMeasurement())
using (MemoryMappedFile mmfile = MemoryMappedFile.CreateFromFile(file.Path))
using (mmfile.CreateViewAccessor(capacity / 4, capacity / 2))
{ }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Microsoft.Xunit.Performance;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Performance tests for the construction and disposal of MemoryMappedFiles of varying sizes
/// </summary>
public class Perf_MemoryMappedFile : MemoryMappedFilesTestBase
{
[Benchmark]
[InlineData(10000)]
[InlineData(100000)]
[InlineData(1000000)]
[InlineData(10000000)]
[ActiveIssue(18463, TestPlatforms.OSX)] // Hits the max-open-file limit often on OSX.
public void CreateNew(int capacity)
{
const int innerIterations = 1000;
MemoryMappedFile[] files = new MemoryMappedFile[innerIterations];
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
for (int i = 0; i < innerIterations; i++)
files[i] = MemoryMappedFile.CreateNew(null, capacity);
for (int i = 0; i < innerIterations; i++)
files[i].Dispose();
}
}
[Benchmark]
[InlineData(10000)]
[InlineData(100000)]
[InlineData(1000000)]
[InlineData(10000000)]
public void CreateFromFile(int capacity)
{
// Note that the test results will include the disposal overhead of both the MemoryMappedFile
// as well as the Accessor for it
foreach (var iteration in Benchmark.Iterations)
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (iteration.StartMeasurement())
using (MemoryMappedFile mmfile = MemoryMappedFile.CreateFromFile(file.Path))
using (mmfile.CreateViewAccessor(capacity / 4, capacity / 2))
{ }
}
[Benchmark]
[InlineData(10000)]
[InlineData(100000)]
[InlineData(1000000)]
public void Dispose(int capacity)
{
const int innerIterations = 1000;
MemoryMappedFile[] files = new MemoryMappedFile[innerIterations];
foreach (var iteration in Benchmark.Iterations)
{
for (int i = 0; i < innerIterations; i++)
files[i] = MemoryMappedFile.CreateNew(null, capacity);
using (iteration.StartMeasurement())
for (int i = 0; i < innerIterations; i++)
files[i].Dispose();
}
}
}
}
| mit | C# |
71e8b88514288e63162300faa6a01d4e281ad775 | Improve upon Property Summaries in CommandServiceConfig (#839) | RogueException/Discord.Net,AntiTcb/Discord.Net | src/Discord.Net.Commands/CommandServiceConfig.cs | src/Discord.Net.Commands/CommandServiceConfig.cs | namespace Discord.Commands
{
public class CommandServiceConfig
{
/// <summary> Gets or sets the default RunMode commands should have, if one is not specified on the Command attribute or builder. </summary>
public RunMode DefaultRunMode { get; set; } = RunMode.Sync;
public char SeparatorChar { get; set; } = ' ';
/// <summary> Determines whether commands should be case-sensitive. </summary>
public bool CaseSensitiveCommands { get; set; } = false;
/// <summary> Gets or sets the minimum log level severity that will be sent to the Log event. </summary>
public LogSeverity LogLevel { get; set; } = LogSeverity.Info;
/// <summary> Determines whether RunMode.Sync commands should push exceptions up to the caller. </summary>
public bool ThrowOnError { get; set; } = true;
}
}
| namespace Discord.Commands
{
public class CommandServiceConfig
{
/// <summary> The default RunMode commands should have, if one is not specified on the Command attribute or builder. </summary>
public RunMode DefaultRunMode { get; set; } = RunMode.Sync;
public char SeparatorChar { get; set; } = ' ';
/// <summary> Should commands be case-sensitive? </summary>
public bool CaseSensitiveCommands { get; set; } = false;
/// <summary> Gets or sets the minimum log level severity that will be sent to the Log event. </summary>
public LogSeverity LogLevel { get; set; } = LogSeverity.Info;
/// <summary> Gets or sets whether RunMode.Sync commands should push exceptions up to the caller. </summary>
public bool ThrowOnError { get; set; } = true;
}
} | mit | C# |
bcc1723de824ffb1cc89d51e562ff257a3b9a8e2 | Add badge for unknown key request count. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | MitternachtWeb/Areas/Analysis/Views/Shared/_AnalysisLayout.cshtml | MitternachtWeb/Areas/Analysis/Views/Shared/_AnalysisLayout.cshtml | @using System.Linq
@inject MitternachtWeb.Areas.Analysis.Services.UnknownKeyRequestsService UnknownKeyRequestsService
@{
Layout = "_Layout";
ViewData["Title"] = "Analysen";
}
<div class="row">
<nav class="col-md-3 col-xl-2">
<ul class="nav">
<li class="nav-item">
<a class="nav-link text-dark d-flex justify-content-between align-items-center" asp-area="Analysis" asp-controller="UnknownKeyRequests" asp-action="Index">
Unbekannte Translationkeys
<span class="badge badge-danger badge-pill">@UnknownKeyRequestsService.UnknownKeyRequests.Values.Aggregate(0ul, (r, i) => r+i)</span>
</a>
</li>
</ul>
</nav>
<div class="col-md-9 col-xl-10 py-md-3 pl-md-5">
@RenderBody()
</div>
</div>
| @{
Layout = "_Layout";
ViewData["Title"] = "Analysen";
}
<div class="row">
<nav class="col-md-3 col-xl-2">
<ul class="nav">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Analysis" asp-controller="UnknownKeyRequests" asp-action="Index">Unbekannte Translationkeys</a>
</li>
</ul>
</nav>
<div class="col-md-9 col-xl-10 py-md-3 pl-md-5">
@RenderBody()
</div>
</div>
| mit | C# |
4fdd041c532c559903b39cc79724d0a2e87605ec | Fix injection in MongoMigrationStartupFilter | SRoddis/Mongo.Migration | Mongo.Migration/Startup/DotNetCore/MongoMigrationStartupFilter.cs | Mongo.Migration/Startup/DotNetCore/MongoMigrationStartupFilter.cs | using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Mongo.Migration.Startup.DotNetCore
{
public class MongoMigrationStartupFilter : IStartupFilter
{
private readonly IMongoMigration _migration;
private readonly ILogger<MongoMigrationStartupFilter> _logger;
public MongoMigrationStartupFilter(IServiceScopeFactory serviceScopeFactory)
: this(serviceScopeFactory, NullLoggerFactory.Instance)
{
}
public MongoMigrationStartupFilter(IServiceScopeFactory serviceScopeFactory, ILoggerFactory loggerFactory)
{
_migration = serviceScopeFactory.CreateScope().ServiceProvider.GetService<IMongoMigration>();
_logger = loggerFactory.CreateLogger<MongoMigrationStartupFilter>();
}
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
try
{
_migration.Run();
}
catch (Exception ex)
{
_logger.LogError(ex, ex.GetType().ToString());
}
return next;
}
}
} | using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Mongo.Migration.Startup.DotNetCore
{
public class MongoMigrationStartupFilter : IStartupFilter
{
private readonly IMongoMigration _migration;
private readonly ILogger<MongoMigrationStartupFilter> _logger;
public MongoMigrationStartupFilter(IMongoMigration migration)
: this(migration, NullLoggerFactory.Instance)
{
}
public MongoMigrationStartupFilter(IMongoMigration migration, ILoggerFactory loggerFactory)
{
_migration = migration;
_logger = loggerFactory.CreateLogger<MongoMigrationStartupFilter>();
}
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
try
{
_migration.Run();
}
catch (Exception ex)
{
_logger.LogError(ex, ex.GetType().ToString());
}
return next;
}
}
} | mit | C# |
b4b50eda90d4ae273a1839d337e0602c955386fd | fix ignore | Fody/ModuleInit | Tests/ModuleWeaverTests.cs | Tests/ModuleWeaverTests.cs | using System.Reflection;
using Fody;
using Xunit;
#pragma warning disable 618
// ReSharper disable PrivateFieldCanBeConvertedToLocalVariable
public class ModuleWeaverTests
{
[Fact]
public void WithFields()
{
var weavingTask = new ModuleWeaver();
var testResult = weavingTask.ExecuteTestRun("AssemblyToProcess.dll",ignoreCodes:new []{"0x8013129d"});
var type = testResult.Assembly.GetType("ModuleInitializer");
var info = type.GetField("InitializeCalled", BindingFlags.Static | BindingFlags.Public);
Assert.True((bool)info.GetValue(null));
}
} | using System.Reflection;
using Fody;
using Xunit;
#pragma warning disable 618
// ReSharper disable PrivateFieldCanBeConvertedToLocalVariable
public class ModuleWeaverTests
{
[Fact]
public void WithFields()
{
var weavingTask = new ModuleWeaver();
var testResult = weavingTask.ExecuteTestRun("AssemblyToProcess.dll", false);
var type = testResult.Assembly.GetType("ModuleInitializer");
var info = type.GetField("InitializeCalled", BindingFlags.Static | BindingFlags.Public);
Assert.True((bool)info.GetValue(null));
}
} | mit | C# |
ac56c88c5bc66aeb668b6ab18ebc0837cb16f32b | clean up using statements an fix private/public | heupel/hyperjs,quameleon/hyperjs | HyperJS/JSBoolean.cs | HyperJS/JSBoolean.cs | using System;
namespace TonyHeupel.HyperJS
{
public static class JSBoolean
{
/// <summary>
/// The Boolean(value) function on the global object.
/// It returns a Boolean converted from the value passed in.
/// 0, NaN, null, "", undefined, false and "false" are false.
/// Everything else will return true.
/// </summary>
public static bool Boolean(this JS js, object value)
{
return NewBoolean(js, value).valueOf();
}
/// <summary>
/// The Boolean(value) constructor function.
/// It returns a Boolean object converted from the value passed in.
/// </summary>
public static dynamic NewBoolean(this JS js, dynamic value)
{
//return new ClassStyle.JSBoolean(value);
return BooleanConstructor(js, value);
}
private static dynamic BooleanConstructor(this JS js, dynamic value)
{
dynamic b = new JSObject();
b.JSTypeName = "Boolean";
// Set up prototype
dynamic p = new JSObject();
b.Prototype = b.GetPrototype(p);
// Calculate the primitive value
bool _primitiveValue = true; //default to true and only set to false when needed
dynamic v = (value is JSObject && !(value is JSUndefined || value is JSNaN)) ? value.valueOf() : value;
if (v == null ||
(v is String && (v == "" || v == "false")) ||
(v is Boolean && v == false) ||
((v is Int32 || v is Int64 || v is Int16) && v == 0) ||
v is JSNaN ||
v is JSUndefined)
{
_primitiveValue = false;
}
// Set up instance items
b.valueOf = new Func<bool>(() => _primitiveValue);
b.toString = new Func<string>(() => _primitiveValue ? "true" : "false"); //Consider using String() here
return b;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TonyHeupel.HyperJS
{
public static class JSBoolean
{
/// <summary>
/// The Boolean(value) function on the global object.
/// It returns a Boolean converted from the value passed in.
/// 0, NaN, null, "", undefined, false and "false" are false.
/// Everything else will return true.
/// </summary>
public static bool Boolean(this JS js, object value)
{
return NewBoolean(js, value).valueOf();
}
public static dynamic NewBoolean(this JS js, dynamic value)
{
//return new ClassStyle.JSBoolean(value);
return BooleanConstructor(js, value);
}
public static dynamic BooleanConstructor(this JS js, dynamic value)
{
dynamic b = new JSObject();
b.JSTypeName = "Boolean";
// Set up prototype
dynamic p = new JSObject();
b.Prototype = b.GetPrototype(p);
// Calculate the primitive value
bool _primitiveValue = true; //default to true and only set to false when needed
dynamic v = (value is JSObject && !(value is JSUndefined || value is JSNaN)) ? value.valueOf() : value;
if (v == null ||
(v is String && (v == "" || v == "false")) ||
(v is Boolean && v == false) ||
((v is Int32 || v is Int64 || v is Int16) && v == 0) ||
v is JSNaN ||
v is JSUndefined)
{
_primitiveValue = false;
}
// Set up instance items
b.valueOf = new Func<bool>(() => _primitiveValue);
b.toString = new Func<string>(() => _primitiveValue ? "true" : "false"); //Consider using String() here
return b;
}
}
}
| mit | C# |
bba15f5dd8aa84a5fc1db14985fb726ab0dfe6b7 | Update copyright. | GetTabster/Tabster | Tabster/Properties/AssemblyInfo.cs | Tabster/Properties/AssemblyInfo.cs | #region
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tabster")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nate Shoffner")]
[assembly: AssemblyProduct("Tabster")]
[assembly: AssemblyCopyright("Copyright © 2010-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("05e93702-6d2b-4e7e-888a-cf5d891f9fb8")]
// 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.6.1.0")]
[assembly: AssemblyFileVersion("1.6.1.0")] | #region
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tabster")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nate Shoffner")]
[assembly: AssemblyProduct("Tabster")]
[assembly: AssemblyCopyright("Copyright © 2010-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("05e93702-6d2b-4e7e-888a-cf5d891f9fb8")]
// 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.6.1.0")]
[assembly: AssemblyFileVersion("1.6.1.0")] | apache-2.0 | C# |
71995b21ee639e81139e3f4f376e793f4e0f1c80 | add check type to payment methods | bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core | src/Core/Enums/PaymentMethodType.cs | src/Core/Enums/PaymentMethodType.cs | using System.ComponentModel.DataAnnotations;
namespace Bit.Core.Enums
{
public enum PaymentMethodType : byte
{
[Display(Name = "Card")]
Card = 0,
[Display(Name = "Bank Account")]
BankAccount = 1,
[Display(Name = "PayPal")]
PayPal = 2,
[Display(Name = "BitPay")]
BitPay = 3,
[Display(Name = "Credit")]
Credit = 4,
[Display(Name = "Wire Transfer")]
WireTransfer = 5,
[Display(Name = "Apple In-App Purchase")]
AppleInApp = 6,
[Display(Name = "Google In-App Purchase")]
GoogleInApp = 7,
[Display(Name = "Check")]
Check = 8,
}
}
| using System.ComponentModel.DataAnnotations;
namespace Bit.Core.Enums
{
public enum PaymentMethodType : byte
{
[Display(Name = "Card")]
Card = 0,
[Display(Name = "Bank Account")]
BankAccount = 1,
[Display(Name = "PayPal")]
PayPal = 2,
[Display(Name = "BitPay")]
BitPay = 3,
[Display(Name = "Credit")]
Credit = 4,
[Display(Name = "Wire Transfer")]
WireTransfer = 5,
[Display(Name = "Apple In-App Purchase")]
AppleInApp = 6,
[Display(Name = "Google In-App Purchase")]
GoogleInApp = 7,
}
}
| agpl-3.0 | C# |
a929e5bfe6c239d7f65261e11052f311e50d002f | Bump to 1.0 | neutmute/Neo4jClient.Extension,CormacdeBarra/Neo4jClient.Extension,simonpinn/Neo4jClient.Extension | SolutionItems/Properties/AssemblyInfoGlobal.cs | SolutionItems/Properties/AssemblyInfoGlobal.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCopyright("Copyright 2014")]
[assembly: AssemblyVersion("1.0.0")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyInformationalVersion("0.1.3.1-beta")] // trigger pre release package
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: InternalsVisibleTo("Neo4jClient.Extension.Test")]
[assembly: ComVisible(false)] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCopyright("Copyright 2014")]
[assembly: AssemblyVersion("0.1.3.1")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyInformationalVersion("0.1.3.1-beta")] // trigger pre release package
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: InternalsVisibleTo("Neo4jClient.Extension.Test")]
[assembly: ComVisible(false)] | mit | C# |
9ed0cdfc2006653bf387fe48ac8d5c0311185b1d | fix end date bug | PapaMufflon/StandUpTimer,PapaMufflon/StandUpTimer,PapaMufflon/StandUpTimer | StandUpTimer.Web/Views/Statistics/Index.cshtml | StandUpTimer.Web/Views/Statistics/Index.cshtml | @model StandUpTimer.Web.Statistic.StatisticModel
@{
ViewBag.Title = "Statistics";
}
@section styles
{
@Styles.Render("~/Content/Statistics.css")
}
<h2>Statistics</h2>
<div id="gantt" style="width: 100%; height: 400px"></div>
@section scripts
{
@Scripts.Render("~/bundles/d3")
<script>
var tasks = [
@foreach (var item in Model.Statuses)
{
@:{ "startDate": new Date(@Html.DisplayFor(modelItem => item.StartDate)), "endDate": @(item.EndDate.Equals("now") ? "new Date()" : "new Date("+Html.DisplayFor(modelItem => item.EndDate)+")"), "taskName": "@Html.DisplayFor(modelItem => item.Day)", "status": "@Html.DisplayFor(modelItem => item.DeskState)" },
}
];
var taskStatus = {
"Standing": "standing",
"Sitting": "sitting",
"Inactive": "inactive"
};
var taskNames = [
@foreach (var day in Model.Days)
{
@:"@Html.DisplayFor(modelItem => day)",
}
];
tasks.sort(function (a, b) {
return a.endDate - b.endDate;
});
var maxDate = tasks[tasks.length - 1].endDate;
tasks.sort(function (a, b) {
return a.startDate - b.startDate;
});
var minDate = tasks[0].startDate;
var format = "%H:%M";
var gantt = d3.gantt("#gantt").taskTypes(taskNames).taskStatus(taskStatus).tickFormat(format);
gantt(tasks);
</script>
} | @model StandUpTimer.Web.Statistic.StatisticModel
@{
ViewBag.Title = "Statistics";
}
@section styles
{
@Styles.Render("~/Content/Statistics.css")
}
<h2>Statistics</h2>
<div id="gantt" style="width: 100%; height: 400px"></div>
@section scripts
{
@Scripts.Render("~/bundles/d3")
<script>
var tasks = [
@foreach (var item in Model.Statuses)
{
@:{ "startDate": new Date(@Html.DisplayFor(modelItem => item.StartDate)), "endDate": @(item.EndDate.Equals("now") ? "Date.now()" : "new Date("+Html.DisplayFor(modelItem => item.EndDate)+")"), "taskName": "@Html.DisplayFor(modelItem => item.Day)", "status": "@Html.DisplayFor(modelItem => item.DeskState)" },
}
];
var taskStatus = {
"Standing": "standing",
"Sitting": "sitting",
"Inactive": "inactive"
};
var taskNames = [
@foreach (var day in Model.Days)
{
@:"@Html.DisplayFor(modelItem => day)",
}
];
tasks.sort(function (a, b) {
return a.endDate - b.endDate;
});
var maxDate = tasks[tasks.length - 1].endDate;
tasks.sort(function (a, b) {
return a.startDate - b.startDate;
});
var minDate = tasks[0].startDate;
var format = "%H:%M";
var gantt = d3.gantt("#gantt").taskTypes(taskNames).taskStatus(taskStatus).tickFormat(format);
gantt(tasks);
</script>
} | mit | C# |
a066bb5cecc8ce705714ca592a9f5fdf6ed6170d | connect to the NetTcp endpoint and run some operations that throw exceptions. | dinazil/blogsamples,dinazil/blogsamples,dinazil/blogsamples | run_time_code_generation/MathRunner/Program.cs | run_time_code_generation/MathRunner/Program.cs | using System;
using System.ServiceModel;
namespace MathRunner
{
class MainClass
{
public static void Main (string[] args)
{
string baseAddress = "net.tcp://localhost:12346/MathOperations";
using (var client = new MathOperationsServiceClient(
new NetTcpBinding(),
new EndpointAddress(baseAddress)))
{
client.InnerChannel.OperationTimeout = TimeSpan.FromSeconds (2);
Console.WriteLine ("Click Enter to start...");
Console.ReadLine ();
Console.WriteLine (client.Increment (0));
Console.WriteLine (client.Decrement (3));
Console.WriteLine (client.SquareRoot (9));
try
{
Console.WriteLine (client.SquareRoot (-16));
}
catch (Exception ex)
{
Console.WriteLine (ex.Message);
}
Console.WriteLine (client.SquareRoot (25));
try
{
client.Timeout(TimeSpan.FromSeconds(5));
}
catch (Exception ex)
{
Console.WriteLine (ex.Message);
}
Console.WriteLine (client.SquareRoot (36));
}
}
}
}
| using System;
using System.ServiceModel;
namespace MathRunner
{
class MainClass
{
public static void Main (string[] args)
{
string baseAddress = "http://localhost:12345/MathOperations";
using (var client = new MathOperationsServiceClient(new BasicHttpBinding(), new EndpointAddress(baseAddress)))
{
Console.WriteLine ("Click Enter to start...");
Console.ReadLine ();
Console.WriteLine (client.Increment (0));
Console.WriteLine (client.Decrement (3));
Console.WriteLine (client.SquareRoot (9));
}
}
}
}
| mit | C# |
0d5afe8d2db67603b63eaecab8828a6f76ed569a | Add gamespeed to disappearingblocxks | nicolasgustafsson/AttackLeague | AttackLeague/AttackLeague/AttackLeague/Blocks/DisappearingBlock.cs | AttackLeague/AttackLeague/AttackLeague/Blocks/DisappearingBlock.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using AttackLeague.Utility;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace AttackLeague.AttackLeague
{
class DisappearingBlock : AbstractColorBlock
{
private float myCurrentFrame = 0;
private int myStartFrame;
private int myTotalFrames;
public DisappearingBlock(EBlockColor aColor, int aTotalFrames, int aStartFrame)
{
myTotalFrames = aTotalFrames;
myStartFrame = aStartFrame;
myColor = aColor;
}
public override void LoadContent(ContentManager aContent)
{
mySprite = new Sprite("ColorBlock", aContent);
Color color = GetColorFromEnum() * 0.3f;
color.A = 255;
mySprite.SetColor(color);
}
public override void Update(float aGameSpeed)
{
myCurrentFrame += 1f + (aGameSpeed / 3.0f);
}
private float GetAnimationProgress()
{
float animationLength = 30;
float currentFrameInAnimation = (int)myCurrentFrame - myStartFrame;
return Math.Max(0f, Math.Min(currentFrameInAnimation / animationLength, 1.0f));
}
public bool IsAlive()
{
return (int)myCurrentFrame < myTotalFrames;
}
public override void Draw(SpriteBatch aSpriteBatch, Vector2 aGridOffset, int aGridHeight, float aRaisingOffset)
{
mySprite.SetScale(Vector2.One - Vector2.One * GetAnimationProgress());
mySprite.SetPosition(GetScreenPosition(aGridOffset, aGridHeight, aRaisingOffset));
mySprite.Draw(aSpriteBatch);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using AttackLeague.Utility;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace AttackLeague.AttackLeague
{
class DisappearingBlock : AbstractColorBlock
{
private int myCurrentFrame = 0;
private int myStartFrame;
private int myTotalFrames;
public DisappearingBlock(EBlockColor aColor, int aTotalFrames, int aStartFrame)
{
myTotalFrames = aTotalFrames;
myStartFrame = aStartFrame;
myColor = aColor;
}
public override void LoadContent(ContentManager aContent)
{
mySprite = new Sprite("ColorBlock", aContent);
Color color = GetColorFromEnum() * 0.3f;
color.A = 255;
mySprite.SetColor(color);
}
public override void Update(float aGameSpeed)
{
myCurrentFrame++;
}
private float GetAnimationProgress()
{
float animationLength = 30;
float currentFrameInAnimation = myCurrentFrame - myStartFrame;
return Math.Max(0f, Math.Min(currentFrameInAnimation / animationLength, 1.0f));
}
public bool IsAlive()
{
return myCurrentFrame < myTotalFrames;
}
public override void Draw(SpriteBatch aSpriteBatch, Vector2 aGridOffset, int aGridHeight, float aRaisingOffset)
{
mySprite.SetScale(Vector2.One - Vector2.One * GetAnimationProgress());
mySprite.SetPosition(GetScreenPosition(aGridOffset, aGridHeight, aRaisingOffset));
mySprite.Draw(aSpriteBatch);
}
}
}
| mit | C# |
b42e8269380ff70bfee47f5c9e752baca391b2ed | fix DEXP-589706 (#2101) | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | debugger/debugger-worker/src/UnityOptions.cs | debugger/debugger-worker/src/UnityOptions.cs | using JetBrains.Collections.Viewable;
using Mono.Debugging.Autofac;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.Debugger
{
public interface IUnityOptions
{
bool ExtensionsEnabled { get; }
bool IgnoreBreakOnUnhandledExceptionsForIl2Cpp { get; }
}
[DebuggerGlobalComponent]
public class UnityOptions : IUnityOptions
{
private readonly UnityDebuggerWorkerHost myHost;
public UnityOptions(UnityDebuggerWorkerHost host)
{
myHost = host;
}
public bool ExtensionsEnabled => myHost.Model.ShowCustomRenderers.HasTrueValue();
public bool IgnoreBreakOnUnhandledExceptionsForIl2Cpp =>
myHost.Model.IgnoreBreakOnUnhandledExceptionsForIl2Cpp.Value;
}
} | using Mono.Debugging.Autofac;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.Debugger
{
public interface IUnityOptions
{
bool ExtensionsEnabled { get; }
bool IgnoreBreakOnUnhandledExceptionsForIl2Cpp { get; }
}
[DebuggerGlobalComponent]
public class UnityOptions : IUnityOptions
{
private readonly UnityDebuggerWorkerHost myHost;
public UnityOptions(UnityDebuggerWorkerHost host)
{
myHost = host;
}
public bool ExtensionsEnabled => myHost.Model.ShowCustomRenderers.Value;
public bool IgnoreBreakOnUnhandledExceptionsForIl2Cpp =>
myHost.Model.IgnoreBreakOnUnhandledExceptionsForIl2Cpp.Value;
}
} | apache-2.0 | C# |
03807589ec9e68e2f9f42135630b161ecaa8bf9d | Remove useless Task.FromResult | rubberduck203/GitNStats,rubberduck203/GitNStats | src/gitnstats.core/DiffCollector.cs | src/gitnstats.core/DiffCollector.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using LibGit2Sharp;
namespace GitNStats.Core
{
public interface AsyncVisitor
{
Task<IEnumerable<(Commit Commit, TreeEntryChanges Diff)>> Walk(Commit commit);
}
public class DiffCollector : AsyncVisitor
{
private readonly Visitor _visitor;
private readonly IDiffListener _listener;
public DiffCollector(Visitor visitor, IDiffListener listener)
{
_visitor = visitor;
_listener = listener;
}
public Task<IEnumerable<(Commit Commit, TreeEntryChanges Diff)>> Walk(Commit commit)
{
return Task.Run(() =>
{
_visitor.Visited += _listener.OnCommitVisited;
try
{
_visitor.Walk(commit);
return _listener.Diffs;
}
finally
{
_visitor.Visited -= _listener.OnCommitVisited;
}
});
}
}
} | using System.Collections.Generic;
using System.Threading.Tasks;
using LibGit2Sharp;
namespace GitNStats.Core
{
public interface AsyncVisitor
{
Task<IEnumerable<(Commit Commit, TreeEntryChanges Diff)>> Walk(Commit commit);
}
public class DiffCollector : AsyncVisitor
{
private readonly Visitor _visitor;
private readonly IDiffListener _listener;
public DiffCollector(Visitor visitor, IDiffListener listener)
{
_visitor = visitor;
_listener = listener;
}
public Task<IEnumerable<(Commit Commit, TreeEntryChanges Diff)>> Walk(Commit commit)
{
return Task.Run(() =>
{
_visitor.Visited += _listener.OnCommitVisited;
try
{
_visitor.Walk(commit);
return Task.FromResult(_listener.Diffs);
}
finally
{
_visitor.Visited -= _listener.OnCommitVisited;
}
});
}
}
} | mit | C# |
3e6c71e2a1e41c0fbfeb6bef36497a88149f0fd4 | Change namespace | ffsantos92/pdf-signer | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace pdfSigner
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace pdfSignerWithCC
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
} | mit | C# |
6f001fb5ae908ea82451ae36c940b846158bcb53 | remove matchPath | ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP/CAP.AppBuilderExtensions.cs | src/DotNetCore.CAP/CAP.AppBuilderExtensions.cs | using System;
using DotNetCore.CAP;
using DotNetCore.CAP.Dashboard.GatewayProxy;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// app extensions for <see cref="IApplicationBuilder"/>
/// </summary>
public static class AppBuilderExtensions
{
///<summary>
/// Enables cap for the current application
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> instance this method extends.</param>
/// <returns>The <see cref="IApplicationBuilder"/> instance this method extends.</returns>
public static IApplicationBuilder UseCap(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var marker = app.ApplicationServices.GetService<CapMarkerService>();
if (marker == null)
{
throw new InvalidOperationException("Add Cap must be called on the service collection.");
}
var provider = app.ApplicationServices;
var bootstrapper = provider.GetRequiredService<IBootstrapper>();
bootstrapper.BootstrapAsync();
return app;
}
public static IApplicationBuilder UseCapDashboard(this IApplicationBuilder app)
{
if (app == null) throw new ArgumentNullException(nameof(app));
var marker = app.ApplicationServices.GetService<CapMarkerService>();
if (marker == null)
{
throw new InvalidOperationException("Add Cap must be called on the service collection.");
}
app.UseMiddleware<GatewayProxyMiddleware>();
app.UseMiddleware<DashboardMiddleware>();
return app;
}
}
} | using System;
using DotNetCore.CAP;
using DotNetCore.CAP.Dashboard.GatewayProxy;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// app extensions for <see cref="IApplicationBuilder"/>
/// </summary>
public static class AppBuilderExtensions
{
///<summary>
/// Enables cap for the current application
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> instance this method extends.</param>
/// <returns>The <see cref="IApplicationBuilder"/> instance this method extends.</returns>
public static IApplicationBuilder UseCap(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var marker = app.ApplicationServices.GetService<CapMarkerService>();
if (marker == null)
{
throw new InvalidOperationException("Add Cap must be called on the service collection.");
}
var provider = app.ApplicationServices;
var bootstrapper = provider.GetRequiredService<IBootstrapper>();
bootstrapper.BootstrapAsync();
return app;
}
public static IApplicationBuilder UseCapDashboard(
this IApplicationBuilder app,
string pathMatch = "/cap")
{
if (app == null) throw new ArgumentNullException(nameof(app));
if (pathMatch == null) throw new ArgumentNullException(nameof(pathMatch));
var marker = app.ApplicationServices.GetService<CapMarkerService>();
if (marker == null)
{
throw new InvalidOperationException("Add Cap must be called on the service collection.");
}
app.Map(new PathString(pathMatch), x =>
{
x.UseMiddleware<DashboardMiddleware>();
x.UseMiddleware<GatewayProxyMiddleware>();
});
return app;
}
}
} | mit | C# |
90eefa5f2bf1cd12b3895d4da5a1e12c5f632f5c | remove unused usings | dotnet/roslyn,AmadeusW/roslyn,bkoelman/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,dpoeschl/roslyn,wvdd007/roslyn,panopticoncentral/roslyn,gafter/roslyn,genlu/roslyn,agocke/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,heejaechang/roslyn,VSadov/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,AlekseyTs/roslyn,tmeschter/roslyn,jcouv/roslyn,genlu/roslyn,swaroop-sridhar/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,nguerrera/roslyn,reaction1989/roslyn,bartdesmet/roslyn,jmarolf/roslyn,dotnet/roslyn,jmarolf/roslyn,physhi/roslyn,DustinCampbell/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,jamesqo/roslyn,xasx/roslyn,bkoelman/roslyn,jamesqo/roslyn,abock/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,bkoelman/roslyn,eriawan/roslyn,sharwell/roslyn,AlekseyTs/roslyn,diryboy/roslyn,nguerrera/roslyn,DustinCampbell/roslyn,xasx/roslyn,physhi/roslyn,tmat/roslyn,abock/roslyn,dotnet/roslyn,davkean/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,jamesqo/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,tmeschter/roslyn,stephentoub/roslyn,physhi/roslyn,VSadov/roslyn,VSadov/roslyn,paulvanbrenk/roslyn,eriawan/roslyn,aelij/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,MichalStrehovsky/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,mavasani/roslyn,abock/roslyn,swaroop-sridhar/roslyn,tannergooding/roslyn,OmarTawfik/roslyn,dpoeschl/roslyn,jasonmalinowski/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,CyrusNajmabadi/roslyn,paulvanbrenk/roslyn,aelij/roslyn,xasx/roslyn,cston/roslyn,shyamnamboodiripad/roslyn,OmarTawfik/roslyn,wvdd007/roslyn,davkean/roslyn,stephentoub/roslyn,davkean/roslyn,weltkante/roslyn,brettfo/roslyn,sharwell/roslyn,mavasani/roslyn,OmarTawfik/roslyn,jcouv/roslyn,tmeschter/roslyn,nguerrera/roslyn,cston/roslyn,diryboy/roslyn,reaction1989/roslyn,DustinCampbell/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,brettfo/roslyn,brettfo/roslyn,genlu/roslyn,jcouv/roslyn,reaction1989/roslyn,gafter/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,panopticoncentral/roslyn,cston/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,MichalStrehovsky/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tmat/roslyn,wvdd007/roslyn,aelij/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,dpoeschl/roslyn,sharwell/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,agocke/roslyn | src/EditorFeatures/Core.Wpf/GlyphExtensions.cs | src/EditorFeatures/Core.Wpf/GlyphExtensions.cs | using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Imaging.Interop;
namespace Microsoft.CodeAnalysis.Editor.Wpf
{
internal static class GlyphExtensions
{
public static ImageMoniker GetImageMoniker(this Glyph glyph)
{
var imageId = glyph.GetImageId();
return new ImageMoniker()
{
Guid = imageId.Guid,
Id = imageId.Id
};
}
}
}
| using System;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
namespace Microsoft.CodeAnalysis.Editor.Wpf
{
internal static class GlyphExtensions
{
public static ImageMoniker GetImageMoniker(this Glyph glyph)
{
var imageId = glyph.GetImageId();
return new ImageMoniker()
{
Guid = imageId.Guid,
Id = imageId.Id
};
}
}
}
| mit | C# |
2e608f7977e58c07d37569746c3dd3b4c4b864e6 | Add EtherType enumeration for some types (not all) | shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg | trunk/src/bindings/EthernetFrame.cs | trunk/src/bindings/EthernetFrame.cs |
using System;
namespace TAPCfg {
public enum EtherType : int {
InterNetwork = 0x0800,
ARP = 0x0806,
RARP = 0x8035,
AppleTalk = 0x809b,
AARP = 0x80f3,
InterNetworkV6 = 0x86dd,
CobraNet = 0x8819,
}
public class EthernetFrame {
private byte[] data;
private byte[] src = new byte[6];
private byte[] dst = new byte[6];
private int etherType;
public EthernetFrame(byte[] data) {
this.data = data;
Array.Copy(data, 0, dst, 0, 6);
Array.Copy(data, 6, src, 0, 6);
etherType = (data[12] << 8) | data[13];
}
public byte[] Data {
get { return data; }
}
public int Length {
get { return data.Length; }
}
public byte[] SourceAddress {
get { return src; }
}
public byte[] DestinationAddress {
get { return dst; }
}
public int EtherType {
get { return etherType; }
}
public byte[] Payload {
get {
byte[] ret = new byte[data.Length - 14];
Array.Copy(data, 14, ret, 0, ret.Length);
return ret;
}
}
}
}
|
using System;
namespace TAPCfg {
public class EthernetFrame {
private byte[] data;
private byte[] src = new byte[6];
private byte[] dst = new byte[6];
private int etherType;
public EthernetFrame(byte[] data) {
this.data = data;
Array.Copy(data, 0, dst, 0, 6);
Array.Copy(data, 6, src, 0, 6);
etherType = (data[12] << 8) | data[13];
}
public byte[] Data {
get { return data; }
}
public int Length {
get { return data.Length; }
}
public byte[] SourceAddress {
get { return src; }
}
public byte[] DestinationAddress {
get { return dst; }
}
public int EtherType {
get { return etherType; }
}
public byte[] Payload {
get {
byte[] ret = new byte[data.Length - 14];
Array.Copy(data, 14, ret, 0, ret.Length);
return ret;
}
}
}
}
| lgpl-2.1 | C# |
1413f002debbc5656414ebf2e1e0f5b73f0a9b34 | fix build issue with litteral 'default' | tpierrain/NFluent,NFluent/NFluent,tpierrain/NFluent,dupdob/NFluent,dupdob/NFluent,dupdob/NFluent,NFluent/NFluent,tpierrain/NFluent | src/NFluent/Extensions/DictionaryExtensions.cs | src/NFluent/Extensions/DictionaryExtensions.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DictionaryExtensions.cs" company="NFluent">
// Copyright 2019 Cyrille DUPUYDAUBY
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NFluent.Extensions
{
using System.Collections.Generic;
internal static class DictionaryExtensions
{
public static bool TryGet<TK, TV>(this IEnumerable<KeyValuePair<TK, TV>> dico, TK key, out TV value)
{
if (dico is IDictionary<TK, TV> trueDico)
{
return trueDico.TryGetValue(key, out value);
}
#if !DOTNET_20 && !DOTNET_30 && !DOTNET_35 && !DOTNET_40 && !PORTABLE
if (dico is IReadOnlyDictionary<TK, TV> roDico)
{
return roDico.TryGetValue(key, out value);
}
#endif
foreach (var pair in dico)
{
if (Equals(pair.Key, key))
{
value = pair.Value;
return true;
}
}
value = default(TV);
return false;
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DictionaryExtensions.cs" company="NFluent">
// Copyright 2019 Cyrille DUPUYDAUBY
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NFluent.Extensions
{
using System.Collections.Generic;
internal static class DictionaryExtensions
{
public static bool TryGet<TK, TV>(this IEnumerable<KeyValuePair<TK, TV>> dico, TK key, out TV value)
{
if (dico is IDictionary<TK, TV> trueDico)
{
return trueDico.TryGetValue(key, out value);
}
#if !DOTNET_20 && !DOTNET_30 && !DOTNET_35 && !DOTNET_40 && !PORTABLE
if (dico is IReadOnlyDictionary<TK, TV> roDico)
{
return roDico.TryGetValue(key, out value);
}
#endif
foreach (var pair in dico)
{
if (Equals(pair.Key, key))
{
value = pair.Value;
return true;
}
}
value = default;
return false;
}
}
} | apache-2.0 | C# |
3ef3176fdb8186ee9bf37803ab69d5111f68a37f | Update PushalotTraceTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/Pushalot/PushalotTraceTelemeter.cs | TIKSN.Core/Analytics/Telemetry/Pushalot/PushalotTraceTelemeter.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TIKSN.Configuration;
namespace TIKSN.Analytics.Telemetry.Pushalot
{
public class PushalotTraceTelemeter : PushalotTelemeterBase, ITraceTelemeter
{
public PushalotTraceTelemeter(IPartialConfiguration<PushalotOptions> pushalotConfiguration)
: base(pushalotConfiguration)
{
}
public async Task TrackTrace(string message) => await this.SendMessage("Trace", message);
public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel) =>
await this.SendMessage(string.Format("Trace: {0}", severityLevel), message);
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration) =>
pushalotConfiguration.TraceAuthorizationTokens;
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration,
TelemetrySeverityLevel severityLevel)
{
if (pushalotConfiguration.SeverityLevelTraceAuthorizationTokens.ContainsKey(severityLevel))
{
return pushalotConfiguration.SeverityLevelTraceAuthorizationTokens[severityLevel];
}
return Enumerable.Empty<string>();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TIKSN.Configuration;
namespace TIKSN.Analytics.Telemetry.Pushalot
{
public class PushalotTraceTelemeter : PushalotTelemeterBase, ITraceTelemeter
{
public PushalotTraceTelemeter(IPartialConfiguration<PushalotOptions> pushalotConfiguration)
: base(pushalotConfiguration)
{
}
public async Task TrackTrace(string message)
{
await SendMessage("Trace", message);
}
public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel)
{
await SendMessage(string.Format("Trace: {0}", severityLevel), message);
}
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration)
{
return pushalotConfiguration.TraceAuthorizationTokens;
}
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration, TelemetrySeverityLevel severityLevel)
{
if (pushalotConfiguration.SeverityLevelTraceAuthorizationTokens.ContainsKey(severityLevel))
{
return pushalotConfiguration.SeverityLevelTraceAuthorizationTokens[severityLevel];
}
return Enumerable.Empty<string>();
}
}
} | mit | C# |
2d1982b325e425f776a2f8b6661a24d3169ba024 | Update Blocker.cs | yanyiyun/LockstepFramework,SnpM/Lockstep-Framework,erebuswolf/LockstepFramework | Core/Simulation/Grid/Utility/Tools/Blocker/Blocker.cs | Core/Simulation/Grid/Utility/Tools/Blocker/Blocker.cs | using UnityEngine;
using System.Collections;
using Lockstep;
//Blocker for static environment pieces in a scene.
[RequireComponent (typeof (LSBody))]
public class Blocker : EnvironmentObject
{
static readonly FastList<Vector2d> bufferCoordinates = new FastList<Vector2d>();
[SerializeField]
private bool _blockPathfinding;
public bool BlockPathfinding {get {return _blockPathfinding;}}
public LSBody CachedBody {get; private set;}
protected override void OnLateInitialize()
{
base.OnInitialize();
CachedBody = this.GetComponent<LSBody> ();
if (this.BlockPathfinding) {
const long gridSpacing = FixedMath.One;
bufferCoordinates.FastClear();
CachedBody.GetCoveredSnappedPositions (gridSpacing, bufferCoordinates);
foreach (Vector2d vec in bufferCoordinates) {
GridNode node = GridManager.GetNode(vec.x,vec.y);
int gridX, gridY;
GridManager.GetCoordinates(vec.x,vec.y, out gridX, out gridY);
if (node == null) continue;
node.AddObstacle();
}
}
}
}
| using UnityEngine;
using System.Collections;
using Lockstep;
[RequireComponent (typeof (LSBody))]
public class Blocker : EnvironmentObject
{
static readonly FastList<Vector2d> bufferCoordinates = new FastList<Vector2d>();
[SerializeField]
private bool _blockPathfinding;
public bool BlockPathfinding {get {return _blockPathfinding;}}
public LSBody CachedBody {get; private set;}
protected override void OnLateInitialize()
{
base.OnInitialize();
CachedBody = this.GetComponent<LSBody> ();
if (this.BlockPathfinding) {
const long gridSpacing = FixedMath.One;
bufferCoordinates.FastClear();
CachedBody.GetCoveredSnappedPositions (gridSpacing, bufferCoordinates);
foreach (Vector2d vec in bufferCoordinates) {
GridNode node = GridManager.GetNode(vec.x,vec.y);
int gridX, gridY;
GridManager.GetCoordinates(vec.x,vec.y, out gridX, out gridY);
if (node == null) continue;
node.AddObstacle();
}
}
}
}
| mit | C# |
8bbb247f10bf2a87968682fbaa04d7f41bc6e386 | Add simple mechanism to fetch JSON and display it | SolidNerd/TwitterMonkey | TwitterMonkey.Android/MainActivity.cs | TwitterMonkey.Android/MainActivity.cs | using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Android.App;
using Android.OS;
using Android.Widget;
using TwitterMonkey.Portable;
namespace TwitterMonkey {
[Activity(Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity {
protected override void OnCreate (Bundle bundle) {
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += async (sender, e) => {
var textView = FindViewById<TextView>(Resource.Id.textView1);
var jsonString = await fetchJsonAsync(new Uri ("http://goo.gl/pJwOUS"));
var tweets = TweetConverter.ConvertAll(jsonString);
foreach (Tweet t in tweets) {
textView.Text += t.Message + "\n";
}
};
}
private async Task<string> fetchJsonAsync (Uri uri) {
HttpWebRequest request = new HttpWebRequest(uri);
var resp = await request.GetResponseAsync();
StreamReader reader = new StreamReader (resp.GetResponseStream());
return await reader.ReadToEndAsync();
}
}
}
| using Android.App;
using Android.Widget;
using Android.OS;
namespace TwitterMonkey
{
[Activity (Label = "TwitterMonkey", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
button.Text = string.Format ("{0} clicks!", count++);
};
}
}
}
| mit | C# |
59c0f866a34c211a76b1d963e891b0aed8ab39ea | Fix xml doccomment syntax error | EamonNerbonne/ExpressionToCode | ExpressionToCodeLib/Internal/StringifiedExpression.cs | ExpressionToCodeLib/Internal/StringifiedExpression.cs | using System;
using System.Diagnostics.Contracts;
using System.Linq.Expressions;
namespace ExpressionToCodeLib.Internal
{
struct StringifiedExpression
{
//a node cannot have children and text. If it has neither, it is considered empty.
public readonly string Text;
readonly StringifiedExpression[] children;
//can only have a value it it has text.
public readonly Expression OptionalValue;
/// <summary>
/// The expression tree contains many symbols that are not themselves "real" expressions, e.g. the "." in "obj.field".
/// This field is true for parts that aren't just implemenation details, but proper sub-expressions; e.g. the "x" in "x && y"
/// </summary>
public readonly bool IsConceptualChild;
static readonly StringifiedExpression[] empty = new StringifiedExpression[0];
public StringifiedExpression[] Children => children ?? empty;
StringifiedExpression(string text, StringifiedExpression[] children, Expression optionalValue, bool isConceptualChild)
{
Text = text;
this.children = children;
OptionalValue = optionalValue;
IsConceptualChild = isConceptualChild;
}
[Pure]
public static StringifiedExpression TextOnly(string text)
=> new StringifiedExpression(text, null, null, false);
[Pure]
public static StringifiedExpression TextAndExpr(string text, Expression expr)
{
if (expr == null) {
throw new ArgumentNullException(nameof(expr));
}
return new StringifiedExpression(text, null, expr, false);
}
[Pure]
public static StringifiedExpression WithChildren(StringifiedExpression[] children)
=> new StringifiedExpression(null, children, null, false);
[Pure]
public override string ToString()
=> Text ?? string.Join("", children);
public StringifiedExpression MarkAsConceptualChild()
=> new StringifiedExpression(Text, children, OptionalValue, true);
}
}
| using System;
using System.Diagnostics.Contracts;
using System.Linq.Expressions;
namespace ExpressionToCodeLib.Internal
{
struct StringifiedExpression
{
//a node cannot have children and text. If it has neither, it is considered empty.
public readonly string Text;
readonly StringifiedExpression[] children;
//can only have a value it it has text.
public readonly Expression OptionalValue;
/// <summary>
/// The expression tree contains many symbols that are not themselves "real" expressions, e.g. the "." in "obj.field".
/// This field is true for parts that aren't just implemenation details, but proper sub-expressions; e.g. the "x" in "x && y"
/// </summary>
public readonly bool IsConceptualChild;
static readonly StringifiedExpression[] empty = new StringifiedExpression[0];
public StringifiedExpression[] Children => children ?? empty;
StringifiedExpression(string text, StringifiedExpression[] children, Expression optionalValue, bool isConceptualChild)
{
Text = text;
this.children = children;
OptionalValue = optionalValue;
IsConceptualChild = isConceptualChild;
}
[Pure]
public static StringifiedExpression TextOnly(string text)
=> new StringifiedExpression(text, null, null, false);
[Pure]
public static StringifiedExpression TextAndExpr(string text, Expression expr)
{
if (expr == null) {
throw new ArgumentNullException(nameof(expr));
}
return new StringifiedExpression(text, null, expr, false);
}
[Pure]
public static StringifiedExpression WithChildren(StringifiedExpression[] children)
=> new StringifiedExpression(null, children, null, false);
[Pure]
public override string ToString()
=> Text ?? string.Join("", children);
public StringifiedExpression MarkAsConceptualChild()
=> new StringifiedExpression(Text, children, OptionalValue, true);
}
}
| apache-2.0 | C# |
00eaf79ecdd207ccaf88d4d2e361f6e9daa10fe9 | use dark-geekblue theme | BioWareRu/BioEngine,BioWareRu/BioEngine,BioWareRu/BioEngine | src/BioEngine.Admin/Pages/_Layout.cshtml | src/BioEngine.Admin/Pages/_Layout.cshtml | @using Microsoft.AspNetCore.Components.Web
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>BioEngine.Admin</title>
<base href="~/"/>
<link rel="preconnect" href="https://fonts.gstatic.com"/>
<link href="_content/AntDesign.ProLayout/theme/dark-geekblue.css" rel="stylesheet"/>
<link href="BioEngine.Admin.styles.css" rel="stylesheet"/>
<link href="~/dist/index.css" rel="stylesheet"/>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body id="bioengine">
@RenderBody()
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_content/AntDesign/js/ant-design-blazor.js"></script>
<script src="_framework/blazor.server.js"></script>
<script src="~/dist/index.js"></script>
</body>
</html>
| @using Microsoft.AspNetCore.Components.Web
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>BioEngine.Admin</title>
<base href="~/"/>
<link rel="preconnect" href="https://fonts.gstatic.com"/>
<link href="_content/AntDesign/css/ant-design-blazor.dark.css" rel="stylesheet"/>
<link href="_content/AntDesign.ProLayout/css/ant-design-pro-layout-blazor.css" rel="stylesheet"/>
<link href="BioEngine.Admin.styles.css" rel="stylesheet"/>
<link href="~/dist/index.css" rel="stylesheet"/>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body id="bioengine">
@RenderBody()
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_content/AntDesign/js/ant-design-blazor.js"></script>
<script src="_framework/blazor.server.js"></script>
<script src="~/dist/index.js"></script>
</body>
</html>
| mit | C# |
b5cd2a298472186983dcfcbeed02186266d5c91d | add height for the div for quotations. | AccountGo/accountgo,AccountGo/accountgo,AccountGo/accountgo,AccountGo/accountgo | src/AccountGoWeb/Views/Quotations/Quotations.cshtml | src/AccountGoWeb/Views/Quotations/Quotations.cshtml | @model string
<div>
<a href="~/quotations/addsalesquotation" class="btn">
<i class="fa fa-plus"></i>
New Quotation
</a>
<a href="~/quotations/salesquotationpdo" id="linkViewQuotation" class="btn inactiveLink">
<i class="fa fa-edit"></i>
View
</a>
<a href="" id="linkNewOrder" class="btn inactiveLink">
<i class="fa fa-plus"></i>
New Order
</a>
</div>
<div>
<div id="quotations" class="ag-fresh" style="height: 400px;"></div>
</div>
<script>
var columnDefs = [
{headerName: "No", field: "no", width: 50},
{headerName: "Customer Name", field: "customerName", width: 350},
{headerName: "Date", field: "quotationDate", width: 100},
{headerName: "Amount", field: "amount", width: 100},
{headerName: "Ref no", field: "referenceNo", width: 100},
{headerName: "Status" , field: "salesQuoteStatus", width : 100}
];
var gridOptions = {
columnDefs: columnDefs,
rowData: @Html.Raw(Model),
enableSorting: true,
// PROPERTIES - simple boolean / string / number properties
rowSelection: 'single',
onSelectionChanged: onSelectionChanged,
};
function onSelectionChanged() {
var selectedRows = gridOptions.api.getSelectedRows();
selectedRow = selectedRows[0];
document.getElementById('linkViewQuotation').setAttribute('href', 'quotation?id=' + selectedRow.id);
document.getElementById('linkViewQuotation').setAttribute('class', 'btn');
if(selectedRow.status == 3)
{
document.getElementById('linkNewOrder').setAttribute('class', 'btn inactiveLink');
}
else if (selectedRow.status == 1){
document.getElementById('linkNewOrder').setAttribute('href', '/sales/salesorder?quotationId=' + selectedRow.id);
document.getElementById('linkNewOrder').setAttribute('class', 'btn');
}
}
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {
var eGridDiv = document.querySelector('#quotations');
new agGrid.Grid(eGridDiv, gridOptions);
});
</script>
| @model string
<div>
<a href="~/quotations/addsalesquotation" class="btn">
<i class="fa fa-plus"></i>
New Quotation
</a>
<a href="~/quotations/salesquotationpdo" id="linkViewQuotation" class="btn inactiveLink">
<i class="fa fa-edit"></i>
View
</a>
<a href="" id="linkNewOrder" class="btn inactiveLink">
<i class="fa fa-plus"></i>
New Order
</a>
</div>
<div>
<div id="quotations" class="ag-fresh"></div>
</div>
<script>
var columnDefs = [
{headerName: "No", field: "no", width: 50},
{headerName: "Customer Name", field: "customerName", width: 350},
{headerName: "Date", field: "quotationDate", width: 100},
{headerName: "Amount", field: "amount", width: 100},
{headerName: "Ref no", field: "referenceNo", width: 100},
{headerName: "Status" , field: "salesQuoteStatus", width : 100}
];
var gridOptions = {
columnDefs: columnDefs,
rowData: @Html.Raw(Model),
enableSorting: true,
// PROPERTIES - simple boolean / string / number properties
rowSelection: 'single',
onSelectionChanged: onSelectionChanged,
};
function onSelectionChanged() {
var selectedRows = gridOptions.api.getSelectedRows();
selectedRow = selectedRows[0];
document.getElementById('linkViewQuotation').setAttribute('href', 'quotation?id=' + selectedRow.id);
document.getElementById('linkViewQuotation').setAttribute('class', 'btn');
if(selectedRow.status == 3)
{
document.getElementById('linkNewOrder').setAttribute('class', 'btn inactiveLink');
}
else if (selectedRow.status == 1){
document.getElementById('linkNewOrder').setAttribute('href', '/sales/salesorder?quotationId=' + selectedRow.id);
document.getElementById('linkNewOrder').setAttribute('class', 'btn');
}
if (true) {
}
}
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {
var eGridDiv = document.querySelector('#quotations');
new agGrid.Grid(eGridDiv, gridOptions);
});
</script>
| mit | C# |
9575efb71ea0ebd9fea046a33ce48669052c44a4 | Add properties into UpdateDepotRequest | nfleet/.net-sdk | NFleetSDK/Data/UpdateDepotRequest.cs | NFleetSDK/Data/UpdateDepotRequest.cs | using System.Collections.Generic;
namespace NFleet.Data
{
public class UpdateDepotRequest
{
public int DepotId { get; set; }
public string Name { get; set; }
public string Info1 { get; set; }
public List<CapacityData> Capacities { get; set; }
public LocationData Location { get; set; }
public string Type { get; set; }
public string DataSource { get; set; }
public int VersionNumber { get; set; }
public string MimeType { get; set; }
public string MimeVersion { get; set; }
public UpdateDepotRequest()
{
Capacities = new List<CapacityData>();
}
}
}
| namespace NFleet.Data
{
public class UpdateDepotRequest : CreateDepotRequest
{
}
}
| mit | C# |
0e0ef7c263af7823922fa12968b64cb9c0be7692 | Fix lazy loads on claim list | kirillkos/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net | JoinRpg.Dal.Impl/Repositories/ClaimsRepositoryImpl.cs | JoinRpg.Dal.Impl/Repositories/ClaimsRepositoryImpl.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JoinRpg.Data.Interfaces;
using JoinRpg.DataModel;
using System.Data.Entity;
namespace JoinRpg.Dal.Impl.Repositories
{
[UsedImplicitly]
public class ClaimsRepositoryImpl : RepositoryImplBase, IClaimsRepository
{
public ClaimsRepositoryImpl(MyDbContext ctx) : base(ctx)
{
}
public async Task<IEnumerable<Claim>> GetActiveClaimsForUser(int userId)
{
return
await
Ctx.ClaimSet.Include(p => p.Character)
.Include(p => p.Group)
.Where(
c =>
c.ClaimStatus != Claim.Status.DeclinedByMaster && c.ClaimStatus != Claim.Status.DeclinedByUser &&
c.PlayerUserId == userId)
.ToListAsync();
}
public Task<Project> GetClaims(int projectId)
{
return
Ctx.ProjectsSet.Include(p => p.Claims)
.Include(p => p.ProjectAcls)
.Include(p => p.CharacterGroups)
.Include(p => p.Characters)
.Include(p => p.ProjectAcls.Select(a => a.User))
.Include(p => p.Claims.Select(c => c.Comments))
.Include(p => p.Claims.Select(c => c.Watermarks))
.Include(p => p.Claims.Select(c => c.Player))
.SingleOrDefaultAsync(p => p.ProjectId == projectId);
}
public async Task<IEnumerable<Claim>> GetMyClaimsForProject(int userId, int projectId)
=> await Ctx.ClaimSet.Where(c => c.ProjectId == projectId && c.PlayerUserId == userId).ToListAsync();
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JoinRpg.Data.Interfaces;
using JoinRpg.DataModel;
using System.Data.Entity;
namespace JoinRpg.Dal.Impl.Repositories
{
[UsedImplicitly]
public class ClaimsRepositoryImpl : RepositoryImplBase, IClaimsRepository
{
public ClaimsRepositoryImpl(MyDbContext ctx) : base(ctx)
{
}
public async Task<IEnumerable<Claim>> GetActiveClaimsForUser(int userId)
{
return
await
Ctx.ClaimSet.Include(p => p.Character)
.Include(p => p.Group)
.Where(
c =>
c.ClaimStatus != Claim.Status.DeclinedByMaster && c.ClaimStatus != Claim.Status.DeclinedByUser &&
c.PlayerUserId == userId)
.ToListAsync();
}
public Task<Project> GetClaims(int projectId)
{
return
Ctx.ProjectsSet.Include(p => p.Claims)
.Include(p => p.ProjectAcls)
.Include(p => p.ProjectAcls.Select(a => a.User))
.Include(p => p.Claims.Select(c => c.Comments))
.Include(p => p.Claims.Select(c => c.Watermarks))
.Include(p => p.Claims.Select(c => c.Player))
.SingleOrDefaultAsync(p => p.ProjectId == projectId);
}
public async Task<IEnumerable<Claim>> GetMyClaimsForProject(int userId, int projectId)
=> await Ctx.ClaimSet.Where(c => c.ProjectId == projectId && c.PlayerUserId == userId).ToListAsync();
}
}
| mit | C# |
fd1d5442c6544abf85927aece47e8fec91cafaeb | fix AlertDialogBackend DefaultButton handling | hwthomas/xwt,hamekoz/xwt,akrisiun/xwt,mminns/xwt,cra0zy/xwt,antmicro/xwt,steffenWi/xwt,directhex/xwt,mono/xwt,mminns/xwt,lytico/xwt,residuum/xwt,iainx/xwt,TheBrainTech/xwt | Xwt.Mac/Xwt.Mac/AlertDialogBackend.cs | Xwt.Mac/Xwt.Mac/AlertDialogBackend.cs | //
// AlertDialogBackend.cs
//
// Author:
// Thomas Ziegler <ziegler.thomas@web.de>
//
// Copyright (c) 2012 Thomas Ziegler
//
// 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.AppKit;
using MonoMac.Foundation;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class AlertDialogBackend : NSAlert, IAlertDialogBackend
{
public AlertDialogBackend ()
{
}
public AlertDialogBackend (System.IntPtr intptr)
{
}
public void Initialize (ApplicationContext actx)
{
}
#region IAlertDialogBackend implementation
public Command Run (WindowFrame transientFor, MessageDescription message)
{
this.MessageText = (message.Text != null) ? message.Text : String.Empty;
this.InformativeText = (message.SecondaryText != null) ? message.SecondaryText : String.Empty;
//TODO Set Icon
var sortedButtons = new Command [message.Buttons.Count];
var j = 0;
if (message.DefaultButton >= 0) {
sortedButtons [0] = message.Buttons [message.DefaultButton];
this.AddButton (message.Buttons [message.DefaultButton].Label);
j = 1;
}
for (var i = 0; i < message.Buttons.Count; i++) {
if (i == message.DefaultButton)
continue;
sortedButtons [j++] = message.Buttons [i];
this.AddButton (message.Buttons [i].Label);
}
return sortedButtons [this.RunModal () - 1000];
}
public bool ApplyToAll { get; set; }
#endregion
}
}
| //
// AlertDialogBackend.cs
//
// Author:
// Thomas Ziegler <ziegler.thomas@web.de>
//
// Copyright (c) 2012 Thomas Ziegler
//
// 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.AppKit;
using MonoMac.Foundation;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class AlertDialogBackend : NSAlert, IAlertDialogBackend
{
public AlertDialogBackend ()
{
}
public AlertDialogBackend (System.IntPtr intptr)
{
}
public void Initialize (ApplicationContext actx)
{
}
#region IAlertDialogBackend implementation
public Command Run (WindowFrame transientFor, MessageDescription message)
{
this.MessageText = (message.Text != null) ? message.Text : String.Empty;
this.InformativeText = (message.SecondaryText != null) ? message.SecondaryText : String.Empty;
//TODO Set Icon
var sortedButtons = new Command [message.Buttons.Count];
sortedButtons [0] = message.Buttons [message.DefaultButton];
this.AddButton (message.Buttons [message.DefaultButton].Label);
var j = 1;
for (var i = 0; i < message.Buttons.Count; i++) {
if (i == message.DefaultButton)
continue;
sortedButtons [j++] = message.Buttons [i];
this.AddButton (message.Buttons [i].Label);
}
return sortedButtons [this.RunModal () - 1000];
}
public bool ApplyToAll { get; set; }
#endregion
}
}
| mit | C# |
47e59f7c2ed6185bfcab513527197cf17e06c550 | Update IAdapter registration in Droid example project | tbrushwyler/Xamarin.BluetoothLE | Droid/MainActivity.cs | Droid/MainActivity.cs | using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
namespace BluetoothLE.Example.Droid
{
[Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
DependencyService.Register<BluetoothLE.Core.IAdapter, BluetoothLE.Droid.Adapter>();
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
namespace BluetoothLE.Example.Droid
{
[Activity(Label = "BluetoothLE.Example.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
DependencyService.Register<IAdapter, Adapter>();
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| mit | C# |
21f3ff6e7717b346ba7ebb7f0f9810dac4dc55a7 | Fix slider repeat points appearing far too late | ppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,naoey/osu,NeoAdonis/osu,DrabWeb/osu,ZLima12/osu,peppy/osu-new,UselessToucan/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu,NeoAdonis/osu,ZLima12/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,EVAST9919/osu,naoey/osu,DrabWeb/osu,smoogipooo/osu | osu.Game.Rulesets.Osu/Objects/RepeatPoint.cs | osu.Game.Rulesets.Osu/Objects/RepeatPoint.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;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Rulesets.Osu.Objects
{
public class RepeatPoint : OsuHitObject
{
public int RepeatIndex { get; set; }
public double SpanDuration { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
// Out preempt should be one span early to give the user ample warning.
TimePreempt += SpanDuration;
// We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders
// we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time.
if (RepeatIndex > 0)
TimePreempt = Math.Min(SpanDuration * 2, TimePreempt);
}
}
}
| // 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;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Rulesets.Osu.Objects
{
public class RepeatPoint : OsuHitObject
{
public int RepeatIndex { get; set; }
public double SpanDuration { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
// We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders
// we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time.
if (RepeatIndex > 0)
TimePreempt = Math.Min(SpanDuration * 2, TimePreempt);
}
}
}
| mit | C# |
5951284dfa4c22fdff3341c359dfb080dd8d636c | Fix typo that don't compile. | pleonex/NitroDebugger,pleonex/NitroDebugger,pleonex/NitroDebugger | NitroDebugger/RSP/Packets/ReadRegisters.cs | NitroDebugger/RSP/Packets/ReadRegisters.cs | //
// ReadRegisters.cs
//
// Author:
// Benito Palacios Sánchez <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez
//
// 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;
namespace NitroDebugger.RSP.Packets
{
public class ReadRegisters : CommandPacket
{
public ReadRegisters()
: base("g")
{
}
protected override string PackArguments()
{
return "";
}
}
}
| //
// ReadRegisters.cs
//
// Author:
// Benito Palacios Sánchez <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez
//
// 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;
namespace NitroDebugger.RSP.Packets
{
public class ReadRegisters : CommandPacket
{
public ReadRegisters()
: base('g')
{
}
protected override string PackArguments()
{
return "";
}
}
}
| mit | C# |
a039457de3e42df74d9918b996936f9a195ca07d | Update InstalledFlowSecrets.cs | pdcdeveloper/QpGoogleApi | OAuth/Models/InstalledFlowSecrets.cs | OAuth/Models/InstalledFlowSecrets.cs | /*
Date : Monday, June 13, 2016
Author : pdcdeveloper (https://github.com/pdcdeveloper)
Objective :
Version : 1.0
*/
using Newtonsoft.Json;
///
/// <summary>
/// Model for a client secrets json file.
/// </summary>
///
namespace QPGoogleAPI.OAuth.Models
{
public class InstalledFlowSecrets
{
[JsonProperty("installed")]
public Installed Installed { get; set; }
}
public class Installed
{
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("auth_uri")]
public string AuthUri { get; set; }
[JsonProperty("token_uri")]
public string TokenUri { get; set; }
[JsonProperty("auth_provider_x509_cert_url")]
public string AuthProviderX509CertUrl { get; set; }
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
//
// Do not use localhost for the installed flow, which is typically the ElementAt(1)
//
[JsonProperty("redirect_uris")]
public string[] RedirectUris { get; set; }
}
}
| /*
Date : Monday, June 13, 2016
Author : QualiP (https://github.com/QualiP)
Objective :
Version : 1.0
*/
using Newtonsoft.Json;
///
/// <summary>
/// Model for a client secrets json file.
/// </summary>
///
namespace QPGoogleAPI.OAuth.Models
{
public class InstalledFlowSecrets
{
[JsonProperty("installed")]
public Installed Installed { get; set; }
}
public class Installed
{
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("auth_uri")]
public string AuthUri { get; set; }
[JsonProperty("token_uri")]
public string TokenUri { get; set; }
[JsonProperty("auth_provider_x509_cert_url")]
public string AuthProviderX509CertUrl { get; set; }
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
//
// Do not use localhost for the installed flow, which is typically the ElementAt(1)
//
[JsonProperty("redirect_uris")]
public string[] RedirectUris { get; set; }
}
}
| mit | C# |
cdf832ce586529b1e5d7986a7e892b395c9dd8b8 | Update AssemblyInfo.cs | SimonCropp/NServiceBus.Serilog | NServiceBusSerilog/AssemblyInfo.cs | NServiceBusSerilog/AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("NServiceBusSerilog")]
[assembly: AssemblyProduct("NServiceBusSerilog")]
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")]
| using System.Reflection;
[assembly: AssemblyTitle("NServiceBusSerilog")]
[assembly: AssemblyProduct("NServiceBusSerilog")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| mit | C# |
334cd136cc9843d744d2b53ec8deb1e4567b1dad | Apply naming suppression to allow build to build. | daukantas/octokit.net,SamTheDev/octokit.net,shiftkey/octokit.net,gabrielweyer/octokit.net,editor-tools/octokit.net,TattsGroup/octokit.net,ivandrofly/octokit.net,geek0r/octokit.net,chunkychode/octokit.net,takumikub/octokit.net,eriawan/octokit.net,gabrielweyer/octokit.net,ChrisMissal/octokit.net,SLdragon1989/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,M-Zuber/octokit.net,mminns/octokit.net,gdziadkiewicz/octokit.net,thedillonb/octokit.net,fffej/octokit.net,shiftkey-tester/octokit.net,alfhenrik/octokit.net,shana/octokit.net,brramos/octokit.net,thedillonb/octokit.net,Sarmad93/octokit.net,dlsteuer/octokit.net,fake-organization/octokit.net,SmithAndr/octokit.net,shiftkey/octokit.net,devkhan/octokit.net,SamTheDev/octokit.net,nsnnnnrn/octokit.net,rlugojr/octokit.net,eriawan/octokit.net,hahmed/octokit.net,ivandrofly/octokit.net,shana/octokit.net,shiftkey-tester/octokit.net,michaKFromParis/octokit.net,kdolan/octokit.net,octokit/octokit.net,Red-Folder/octokit.net,khellang/octokit.net,Sarmad93/octokit.net,gdziadkiewicz/octokit.net,M-Zuber/octokit.net,alfhenrik/octokit.net,adamralph/octokit.net,SmithAndr/octokit.net,magoswiat/octokit.net,naveensrinivasan/octokit.net,dampir/octokit.net,darrelmiller/octokit.net,yonglehou/octokit.net,yonglehou/octokit.net,kolbasov/octokit.net,cH40z-Lord/octokit.net,dampir/octokit.net,bslliw/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,khellang/octokit.net,octokit-net-test-org/octokit.net,octokit-net-test/octokit.net,octokit/octokit.net,forki/octokit.net,hitesh97/octokit.net,editor-tools/octokit.net,TattsGroup/octokit.net,mminns/octokit.net,octokit-net-test-org/octokit.net,rlugojr/octokit.net,nsrnnnnn/octokit.net,chunkychode/octokit.net,hahmed/octokit.net,devkhan/octokit.net | Octokit/Clients/IActivitiesClient.cs | Octokit/Clients/IActivitiesClient.cs | namespace Octokit
{
public interface IActivitiesClient
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Event")]
IEventsClient Event { get; }
}
} | namespace Octokit
{
public interface IActivitiesClient
{
IEventsClient Event { get; }
}
} | mit | C# |
3cf28cb6e8a3263d7170657c548cc6905e509dc3 | Change layout | SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery | AstroPhotoGallery/AstroPhotoGallery/Views/Shared/_Layout.cshtml | AstroPhotoGallery/AstroPhotoGallery/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title Astronomy Photo Gallery </title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-collapse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("ASTRO GALLERY", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<footer class="pull-right">
<p>© @DateTime.Now.Year - Astronomy Photo Gallery </p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# |
4a38d1c5963df71b9e94bc4e409139145a359a75 | Add options to JilFormatter | studio-nine/Nine.Formatting | src/Nine.Formatting.Json/JilFormatter.cs | src/Nine.Formatting.Json/JilFormatter.cs | #if FEATURE_JIL
namespace Nine.Formatting
{
using System;
using System.IO;
using System.Text;
using Jil;
public class JilFormatter : IFormatter, ITextFormatter
{
private readonly Encoding _encoding = new UTF8Encoding(false, true);
private readonly Options _options;
public JilFormatter()
{
_options = new Options(
prettyPrint: false,
excludeNulls: true,
jsonp: false,
dateFormat: DateTimeFormat.ISO8601,
includeInherited: true,
unspecifiedDateTimeKindBehavior: UnspecifiedDateTimeKindBehavior.IsUTC,
serializationNameFormat: SerializationNameFormat.CamelCase);
}
public JilFormatter(Options options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
_options = options;
}
public void WriteTo(object value, Stream stream)
{
using (var writer = new StreamWriter(stream, _encoding, 1024, leaveOpen: true))
{
JSON.Serialize(value, writer, _options);
}
}
public object ReadFrom(Type type, Stream stream)
{
using (var reader = new StreamReader(stream, _encoding, true, 1024, leaveOpen: true))
{
return JSON.Deserialize(reader, type, _options);
}
}
public void WriteTo(object value, TextWriter writer)
{
JSON.Serialize(value, writer, _options);
}
public object ReadFrom(Type type, TextReader reader)
{
return JSON.Deserialize(reader, type, _options);
}
}
}
#endif | #if FEATURE_JIL
namespace Nine.Formatting
{
using System;
using System.IO;
using System.Text;
using Jil;
public class JilFormatter : IFormatter, ITextFormatter
{
private readonly Encoding _encoding = new UTF8Encoding(false, true);
private readonly Options _options = new Options(
prettyPrint: false,
excludeNulls: true,
jsonp: false,
dateFormat: DateTimeFormat.ISO8601,
includeInherited: true,
unspecifiedDateTimeKindBehavior: UnspecifiedDateTimeKindBehavior.IsUTC,
serializationNameFormat: SerializationNameFormat.CamelCase);
public void WriteTo(object value, Stream stream)
{
using (var writer = new StreamWriter(stream, _encoding, 1024, leaveOpen: true))
{
JSON.Serialize(value, writer, _options);
}
}
public object ReadFrom(Type type, Stream stream)
{
using (var reader = new StreamReader(stream, _encoding, true, 1024, leaveOpen: true))
{
return JSON.Deserialize(reader, type, _options);
}
}
public void WriteTo(object value, TextWriter writer)
{
JSON.Serialize(value, writer, _options);
}
public object ReadFrom(Type type, TextReader reader)
{
return JSON.Deserialize(reader, type, _options);
}
}
}
#endif | mit | C# |
2de7d0c4ed31ded829edd7529f9b7d7b974a7d1f | Fix bug when parsing players data | CSGO-Analysis/CSGO-Analyzer | DemoParser/Entities/Player.cs | DemoParser/Entities/Player.cs | using DemoParser_Core.Packets;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace DemoParser_Core.Entities
{
public class Player
{
internal Entity Entity;
public string Name { get; internal set; }
public int UserID { get; internal set; }
public long SteamID { get; internal set; }
public Team Team { get; internal set; }
public int Health { get; internal set; }
public int Money { get; internal set; }
public Vector Position { get; internal set; }
public Vector LastAlivePosition { get; internal set; }
public Vector Velocity { get; internal set; }
public float ViewDirectionX { get; internal set; }
public float ViewDirectionY { get; internal set; }
public bool IsAlive
{
get { return Health > 0; }
}
internal Player(Entity entity)
{
this.Entity = entity;
}
internal Player(PlayerInfo info)
{
Name = info.Name;
UserID = info.UserID;
SteamID = info.XUID;
}
internal void Update(PlayerInfo info)
{
Name = info.Name;
}
internal void Update(Entity entity)
{
this.Entity = entity;
if (entity.Properties.ContainsKey("m_vecOrigin"))
{
this.Position = (Vector)entity.Properties["m_vecOrigin"];
if (entity.Properties.ContainsKey("m_vecOrigin[2]"))
this.Position.Z = (float)entity.Properties.GetValueOrDefault("m_vecOrigin[2]", 0);
if (entity.Properties.ContainsKey("m_iHealth"))
this.Health = (int)entity.Properties["m_iHealth"];
else
this.Health = -1;
this.Money = (int)entity.Properties.GetValueOrDefault<string, object>("m_iAccount", 0);
this.Velocity = new Vector();
this.Velocity.X = (float)entity.Properties.GetValueOrDefault<string, object>("m_vecVelocity[0]", 0f);
this.Velocity.Y = (float)entity.Properties.GetValueOrDefault<string, object>("m_vecVelocity[1]", 0f);
this.Velocity.Z = (float)entity.Properties.GetValueOrDefault<string, object>("m_vecVelocity[2]", 0f);
if (entity.Properties.ContainsKey("m_angEyeAngles[1]"))
this.ViewDirectionX = (float)entity.Properties["m_angEyeAngles[1]"];
if (entity.Properties.ContainsKey("m_angEyeAngles[0]"))
this.ViewDirectionY = (float)entity.Properties["m_angEyeAngles[0]"];
if (this.IsAlive)
{
this.LastAlivePosition = this.Position;
}
}
}
}
}
| using DemoParser_Core.Packets;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace DemoParser_Core.Entities
{
public class Player
{
internal Entity Entity;
public string Name { get; internal set; }
public int UserID { get; internal set; }
public long SteamID { get; internal set; }
public Team Team { get; internal set; }
public int Health { get; internal set; }
public int Money { get; internal set; }
public Vector Position { get; internal set; }
public Vector LastAlivePosition { get; internal set; }
public Vector Velocity { get; internal set; }
public float ViewDirectionX { get; internal set; }
public float ViewDirectionY { get; internal set; }
public bool IsAlive
{
get { return Health > 0; }
}
internal Player(Entity entity)
{
this.Entity = entity;
}
internal Player(PlayerInfo info)
{
Name = info.Name;
UserID = info.UserID;
SteamID = info.XUID;
}
internal void Update(PlayerInfo info)
{
Name = info.Name;
}
internal void Update(Entity entity)
{
this.Entity = entity;
if (entity.Properties.ContainsKey("m_vecOrigin"))
{
this.Position = (Vector)entity.Properties["m_vecOrigin"];
this.Position.Z = (float)entity.Properties.GetValueOrDefault("m_vecOrigin[2]", 0);
if (entity.Properties.ContainsKey("m_iHealth"))
this.Health = (int)entity.Properties["m_iHealth"];
else
this.Health = -1;
this.Money = (int)entity.Properties.GetValueOrDefault<string, object>("m_iAccount", 0);
this.Velocity = new Vector();
this.Velocity.X = (float)entity.Properties.GetValueOrDefault<string, object>("m_vecVelocity[0]", 0f);
this.Velocity.Y = (float)entity.Properties.GetValueOrDefault<string, object>("m_vecVelocity[1]", 0f);
this.Velocity.Z = (float)entity.Properties.GetValueOrDefault<string, object>("m_vecVelocity[2]", 0f);
if (entity.Properties.ContainsKey("m_angEyeAngles[1]"))
this.ViewDirectionX = (float)entity.Properties["m_angEyeAngles[1]"];
if (entity.Properties.ContainsKey("m_angEyeAngles[0]"))
this.ViewDirectionY = (float)entity.Properties["m_angEyeAngles[0]"];
if (this.IsAlive)
{
this.LastAlivePosition = this.Position;
}
}
}
}
}
| mit | C# |
d85950ba03d2f17019245c30fcff2ef3413b0eb6 | Add a playback time push message | flagbug/Espera.Network | Espera.Network/PushAction.cs | Espera.Network/PushAction.cs | namespace Espera.Network
{
public enum PushAction
{
UpdateAccessPermission = 0,
UpdateCurrentPlaylist = 1,
UpdatePlaybackState = 2,
UpdateRemainingVotes = 3,
UpdateCurrentPlaybackTime = 4
}
} | namespace Espera.Network
{
public enum PushAction
{
UpdateAccessPermission = 0,
UpdateCurrentPlaylist = 1,
UpdatePlaybackState = 2,
UpdateRemainingVotes = 3
}
} | mit | C# |
4fbb1ecf729b7a134bd5a76aa739eb70242cf05e | Update Player.cs | whitneyhaddow/basic-card-shuffle | ICT711_Lab3/Player.cs | ICT711_Lab3/Player.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ICT711_Lab3
{
class Player
{
public const int HAND_COUNT = 5;
public const int NUM_PLAYERS = 4;
Deck d = new Deck();
public static List<string> p1 = new List<string>();
public static List<string> p2 = new List<string>();
public static List<string> p3 = new List<string>();
public static List<string> p4 = new List<string>();
public Player() { }
public void DealHands()
{
try //prevent from crashing
{
int count;
for (count = 0; count < HAND_COUNT; count++)
{
p1.Add(d.Deal());
p2.Add(d.Deal());
p3.Add(d.Deal());
p4.Add(d.Deal());
}
}
catch (ArgumentOutOfRangeException)
{
throw;
}
}
public string GetDealtHandP1(int i)
{
return p1.ElementAt(i);
}
public string GetDealtHandP2(int i)
{
return p2.ElementAt(i);
}
public string GetDealtHandP3(int i)
{
return p3.ElementAt(i);
}
public string GetDealtHandP4(int i)
{
return p4.ElementAt(i);
}
public void ClearHands()
{
p1.Clear();
p2.Clear();
p3.Clear();
p4.Clear();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ICT711_Lab3
{
class Player
{
//MD
public const int HAND_COUNT = 5;
public const int NUM_PLAYERS = 4;
Deck d = new Deck();
public static List<string> p1 = new List<string>();
public static List<string> p2 = new List<string>();
public static List<string> p3 = new List<string>();
public static List<string> p4 = new List<string>();
public Player() { }
public void DealHands()
{
//WH
try //prevent from crashing
{
int count;
//MD
for (count = 0; count < HAND_COUNT; count++)
{
p1.Add(d.Deal());
p2.Add(d.Deal());
p3.Add(d.Deal());
p4.Add(d.Deal());
}
}
catch (ArgumentOutOfRangeException)
{
throw;
}
}
//MD
public string GetDealtHandP1(int i)
{
return p1.ElementAt(i);
}
public string GetDealtHandP2(int i)
{
return p2.ElementAt(i);
}
public string GetDealtHandP3(int i)
{
return p3.ElementAt(i);
}
public string GetDealtHandP4(int i)
{
return p4.ElementAt(i);
}
//WH and MD
public void ClearHands()
{
p1.Clear();
p2.Clear();
p3.Clear();
p4.Clear();
}
}
}
| mit | C# |
12287d91bbf1527284a36ca14b3ce2eb24976afc | Refactor some code. | Xevle/Xevle.Imaging | Image/PooledLoader.cs | Image/PooledLoader.cs | using System;
using System.Collections.Generic;
namespace Xevle.Imaging.Image
{
public class PooledLoader
{
int maxImages;
Dictionary<string, IImage> imgPool;
List<string> imgLoadOrder;
public PooledLoader()
{
maxImages = 20;
imgPool = new Dictionary<string, IImage>();
imgLoadOrder = new List<string>();
}
public PooledLoader(uint maxSize)
{
maxImages = (int)maxSize;
imgPool = new Dictionary<string, IImage>();
imgLoadOrder = new List<string>();
}
public IImage FromFile(string filename)
{
// if (imgPool.ContainsKey(filename))
// {
// imgLoadOrder.Remove(filename);
// imgLoadOrder.Add(filename);
// return imgPool[filename];
// }
//
// while (maxImages <= imgPool.Count)
// {
// string del = imgLoadOrder[0];
// imgLoadOrder.RemoveAt(0);
// imgPool.Remove(del);
// }
//
// IImage ret = IImage.FromFile(filename);
// imgPool.Add(filename, ret);
// imgLoadOrder.Add(filename);
//
// return ret;
return null;
}
public void Clear()
{
imgPool.Clear();
imgLoadOrder.Clear();
}
public int MaxImages
{
get
{
return maxImages;
}
set
{
maxImages = value;
}
}
public int Count
{
get { return imgLoadOrder.Count; }
}
public bool RemoveFileFromPool(string filename)
{
string lower = filename.ToLower();
if (imgPool.ContainsKey(lower))
{
imgLoadOrder.Remove(lower);
imgPool.Remove(lower);
return true;
}
return false;
}
public string[] ToArray()
{
return imgLoadOrder.ToArray();
}
}
}
| using System;
using System.Collections.Generic;
namespace Xevle.Imaging.Image
{
public class PooledLoader
{
int maxImages;
Dictionary<string, IImage> imgPool;
List<string> imgLoadOrder;
public PooledLoader()
{
maxImages = 20;
imgPool = new Dictionary<string, IImage>();
imgLoadOrder = new List<string>();
}
public PooledLoader(uint mxi)
{
maxImages = (int)mxi;
imgPool = new Dictionary<string, IImage>();
imgLoadOrder = new List<string>();
}
public IImage FromFile(string filename)
{
// if (imgPool.ContainsKey(filename))
// {
// imgLoadOrder.Remove(filename);
// imgLoadOrder.Add(filename);
// return imgPool[filename];
// }
//
// while (maxImages <= imgPool.Count)
// {
// string del = imgLoadOrder[0];
// imgLoadOrder.RemoveAt(0);
// imgPool.Remove(del);
// }
//
// IImage ret = IImage.FromFile(filename);
// imgPool.Add(filename, ret);
// imgLoadOrder.Add(filename);
//
// return ret;
return null;
}
public void Clear()
{
imgPool.Clear();
imgLoadOrder.Clear();
}
public int MaxImages
{
get
{
return maxImages;
}
set
{
maxImages = value;
}
}
public int Count
{
get { return imgLoadOrder.Count; }
}
public bool RemoveFileFromPool(string filename)
{
string lower = filename.ToLower();
if (imgPool.ContainsKey(lower))
{
imgLoadOrder.Remove(lower);
imgPool.Remove(lower);
return true;
}
return false;
}
public string[] ToArray()
{
return imgLoadOrder.ToArray();
}
}
}
| mit | C# |
1a321007a12d680a32b4097dfc9b2af342865837 | Update IElement.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | Test/Core/IElement.cs | Test/Core/IElement.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test.Core
{
public interface IElement
{
void Invalidate();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test.Core
{
public interface IElement
{
void Invalidate();
}
}
| mit | C# |
30f5b2b2318ea21fd2ccbc30fa3b4c341041e960 | Clear interface before run | fpellet/Bbl.SignalR,fpellet/Bbl.SignalR,fpellet/Bbl.SignalR | Bbl.SignalR.SharedWhiteboard.Cli/Program.cs | Bbl.SignalR.SharedWhiteboard.Cli/Program.cs | using System;
using Microsoft.AspNet.SignalR.Client;
namespace Bbl.SignalR.SharedWhiteboard.Cli
{
class Program
{
static void Main(string[] args)
{
var connection = new HubConnection("http://localhost:59391");
var hubProxy = connection.CreateHubProxy("DrawingBoard");
hubProxy.On("clear", ClearConsole);
hubProxy.On("drawPoint", (int x, int y) => DrawPoint(x, y));
connection.Start();
Console.WriteLine("Ready");
ClearConsole();
Console.ReadKey();
}
private static void DrawPoint(int x, int y)
{
var translatedx = Console.WindowWidth*x/300;
var translatedy = Console.WindowHeight*y/300;
Console.SetCursorPosition(translatedx, translatedy);
Console.BackgroundColor = ConsoleColor.White;
Console.Write(" ");
}
private static void ClearConsole()
{
Console.BackgroundColor = ConsoleColor.Black;
Console.Clear();
}
}
}
| using System;
using Microsoft.AspNet.SignalR.Client;
namespace Bbl.SignalR.SharedWhiteboard.Cli
{
class Program
{
static void Main(string[] args)
{
var connection = new HubConnection("http://localhost:59391");
var hubProxy = connection.CreateHubProxy("DrawingBoard");
hubProxy.On("clear", ClearConsole);
hubProxy.On("drawPoint", (int x, int y) => DrawPoint(x, y));
connection.Start();
Console.WriteLine("Ready");
Console.ReadKey();
}
private static void DrawPoint(int x, int y)
{
var translatedx = Console.WindowWidth*x/300;
var translatedy = Console.WindowHeight*y/300;
Console.SetCursorPosition(translatedx, translatedy);
Console.BackgroundColor = ConsoleColor.White;
Console.Write(" ");
}
private static void ClearConsole()
{
Console.BackgroundColor = ConsoleColor.Black;
Console.Clear();
}
}
}
| mit | C# |
e596fbd81c46f3e756b3b393a32effaff09ba0ac | debug lines | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.UI/Parsing/Messages/S_SPAWN_NPC.cs | TCC.UI/Parsing/Messages/S_SPAWN_NPC.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCC.Data;
using Tera.Game;
using Tera.Game.Messages;
namespace TCC.Parsing.Messages
{
public class S_SPAWN_NPC : ParsedMessage
{
ulong id;
uint templateId;
ushort huntingZoneId;
public ulong EntityId { get => id;}
public uint TemplateId { get => templateId; }
public ushort HuntingZoneId { get => huntingZoneId; }
public S_SPAWN_NPC(TeraMessageReader reader) : base(reader)
{
reader.Skip(10);
id = reader.ReadUInt64();
reader.Skip(26);
templateId = reader.ReadUInt32();
huntingZoneId = reader.ReadUInt16();
//Console.WriteLine("[S_SPAWN NPC] id:{0} tId:{1} hzId:{2}", id, templateId, huntingZoneId);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCC.Data;
using Tera.Game;
using Tera.Game.Messages;
namespace TCC.Parsing.Messages
{
public class S_SPAWN_NPC : ParsedMessage
{
ulong id;
uint templateId;
ushort huntingZoneId;
public ulong EntityId { get => id;}
public uint TemplateId { get => templateId; }
public ushort HuntingZoneId { get => huntingZoneId; }
public S_SPAWN_NPC(TeraMessageReader reader) : base(reader)
{
reader.Skip(10);
id = reader.ReadUInt64();
reader.Skip(26);
templateId = reader.ReadUInt32();
huntingZoneId = reader.ReadUInt16();
// Console.WriteLine("[S_SPAWN NPC] id:{0} name:{1}", id, MonsterDatabase.GetName(npc, (uint)type));
}
}
}
| mit | C# |
1d53c62dd7515a5b9fc3f3a3d3e198a1d6a0511e | Fix on windows: types were resolved to wrong implementations On windows AutoFac resolved IGLMatrixBuilder and IGLBoundingBoxBuilder to private classes(!). Fixed by declaring explicit resolves for those types. | tzachshabtay/MonoAGS | Engine/Misc/DependencyInjection/Resolver.cs | Engine/Misc/DependencyInjection/Resolver.cs | using System;
using Autofac;
using System.Reflection;
using AGS.API;
using System.Collections.Generic;
using Autofac.Features.ResolveAnything;
namespace AGS.Engine
{
public class Resolver
{
public Resolver(IEngineConfigFile configFile)
{
Builder = new ContainerBuilder ();
if (configFile.DebugResolves)
{
Builder.RegisterModule(new AutofacResolveLoggingModule ());
}
Builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).
Except<SpatialAStarPathFinder>().AsImplementedInterfaces();
Builder.RegisterType<GLImageRenderer>().As<IImageRenderer>();
Builder.RegisterType<AGSObject>().As<IObject>();
Builder.RegisterType<GLImage>().As<IImage>();
Builder.RegisterType<AGSGameState>().SingleInstance().As<IGameState>();
Builder.RegisterType<AGSGame>().SingleInstance().As<IGame>();
Builder.RegisterType<AGSGameEvents>().SingleInstance().As<IGameEvents>();
Builder.RegisterType<BitmapPool>().SingleInstance();
Builder.RegisterType<GLViewportMatrix>().SingleInstance().As<IGLViewportMatrix>();
Builder.RegisterType<AGSPlayer>().SingleInstance().As<IPlayer>();
Builder.RegisterType<ResourceLoader>().SingleInstance().As<IResourceLoader>();
Builder.RegisterType<AGSCutscene>().SingleInstance().As<ICutscene>();
registerComponents();
Builder.RegisterType<AGSSprite>().As<ISprite>();
Builder.RegisterType<GLMatrixBuilder>().As<IGLMatrixBuilder>();
Builder.RegisterType<GLBoundingBoxesBuilder>().As<IGLBoundingBoxBuilder>();
Builder.RegisterGeneric(typeof(AGSEvent<>)).As(typeof(IEvent<>));
Dictionary<string, GLImage> textures = new Dictionary<string, GLImage> (1024);
Builder.RegisterInstance(textures);
Builder.RegisterInstance(textures).As(typeof(IDictionary<string, GLImage>));
FastFingerChecker checker = new FastFingerChecker ();
Builder.RegisterInstance(checker);
Builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
}
public ContainerBuilder Builder { get; private set; }
public IContainer Container { get; private set; }
public void Build()
{
Container = Builder.Build();
var updater = new ContainerBuilder ();
updater.RegisterInstance(Container);
updater.RegisterInstance(this);
updater.Update(Container);
}
private void registerComponents()
{
var assembly = Assembly.GetCallingAssembly();
foreach (var type in assembly.GetTypes())
{
if (!isComponent(type)) continue;
registerComponent(type);
}
Builder.RegisterType<VisibleProperty>().As<IVisibleComponent>();
Builder.RegisterType<EnabledProperty>().As<IEnabledComponent>();
}
private bool isComponent(Type type)
{
return (type.BaseType == typeof(AGSComponent));
}
private void registerComponent(Type type)
{
foreach (var compInterface in type.GetInterfaces())
{
if (compInterface == typeof(IComponent) || compInterface == typeof(IDisposable)) continue;
Builder.RegisterType(type).As(compInterface);
}
}
}
}
| using System;
using Autofac;
using System.Reflection;
using AGS.API;
using System.Collections.Generic;
using Autofac.Features.ResolveAnything;
namespace AGS.Engine
{
public class Resolver
{
public Resolver(IEngineConfigFile configFile)
{
Builder = new ContainerBuilder ();
if (configFile.DebugResolves)
{
Builder.RegisterModule(new AutofacResolveLoggingModule ());
}
Builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).
Except<SpatialAStarPathFinder>().AsImplementedInterfaces();
Builder.RegisterType<GLImageRenderer>().As<IImageRenderer>();
Builder.RegisterType<AGSObject>().As<IObject>();
Builder.RegisterType<GLImage>().As<IImage>();
Builder.RegisterType<AGSGameState>().SingleInstance().As<IGameState>();
Builder.RegisterType<AGSGame>().SingleInstance().As<IGame>();
Builder.RegisterType<AGSGameEvents>().SingleInstance().As<IGameEvents>();
Builder.RegisterType<BitmapPool>().SingleInstance();
Builder.RegisterType<GLViewportMatrix>().SingleInstance().As<IGLViewportMatrix>();
Builder.RegisterType<AGSPlayer>().SingleInstance().As<IPlayer>();
Builder.RegisterType<ResourceLoader>().SingleInstance().As<IResourceLoader>();
Builder.RegisterType<AGSCutscene>().SingleInstance().As<ICutscene>();
registerComponents();
Builder.RegisterType<AGSSprite>().As<ISprite>();
Builder.RegisterGeneric(typeof(AGSEvent<>)).As(typeof(IEvent<>));
Dictionary<string, GLImage> textures = new Dictionary<string, GLImage> (1024);
Builder.RegisterInstance(textures);
Builder.RegisterInstance(textures).As(typeof(IDictionary<string, GLImage>));
FastFingerChecker checker = new FastFingerChecker ();
Builder.RegisterInstance(checker);
Builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
}
public ContainerBuilder Builder { get; private set; }
public IContainer Container { get; private set; }
public void Build()
{
Container = Builder.Build();
var updater = new ContainerBuilder ();
updater.RegisterInstance(Container);
updater.RegisterInstance(this);
updater.Update(Container);
}
private void registerComponents()
{
var assembly = Assembly.GetCallingAssembly();
foreach (var type in assembly.GetTypes())
{
if (!isComponent(type)) continue;
registerComponent(type);
}
Builder.RegisterType<VisibleProperty>().As<IVisibleComponent>();
Builder.RegisterType<EnabledProperty>().As<IEnabledComponent>();
}
private bool isComponent(Type type)
{
return (type.BaseType == typeof(AGSComponent));
}
private void registerComponent(Type type)
{
foreach (var compInterface in type.GetInterfaces())
{
if (compInterface == typeof(IComponent) || compInterface == typeof(IDisposable)) continue;
Builder.RegisterType(type).As(compInterface);
}
}
}
}
| artistic-2.0 | C# |
fed7307ff25f32749381be821c561a71919d67d7 | Make it easier to retrieve block's data values | zpqrtbnk/Zbu.Blocks,zpqrtbnk/Zbu.Blocks | zbu.blocks/Zbu.Blocks/RenderingBlock.cs | zbu.blocks/Zbu.Blocks/RenderingBlock.cs | using System.Collections.Generic;
using Umbraco.Core.Models;
namespace Zbu.Blocks
{
/// <summary>
/// Represents a block to be rendered.
/// </summary>
/// <remarks>Name makes a block named ie unique, Type initialized all properties from a predefined
/// type, Source overrides name if needed. Such as when using the same source for two types of blocks
/// which would be differenciated by their name.</remarks>
public class RenderingBlock
{
/// <summary>
/// Initializes a new instance of the <see cref="RenderingBlock"/> class with a name, a source,
/// a collection of blocks, and data and fragment json.
/// </summary>
/// <param name="name">The name of the block.</param>
/// <param name="source">The block source.</param>
/// <param name="blocks">The block inner blocks.</param>
/// <param name="data">The block data dictionary (using case-insensitive keys).</param>
/// <param name="fragment">The block content fragment.</param>
/// <remarks>The block data can be null.</remarks>
public RenderingBlock(string name, string source, IEnumerable<RenderingBlock> blocks,
IDictionary<string, object> data, IPublishedContent fragment)
{
Name = name;
Source = source;
Blocks = new RenderingBlockCollection(blocks);
Data = data;
Fragment = fragment;
}
/// <summary>
/// Gets or sets the name of the block.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets or sets the source of the block.
/// </summary>
/// <remarks>The source determines the view that should be used to render the block.</remarks>
public string Source { get; private set; }
/// <summary>
/// Gets or sets the inner blocks collection of the block.
/// </summary>
public RenderingBlockCollection Blocks { get; private set; }
/// <summary>
/// Gets or sets the block data dictionary.
/// </summary>
/// <remarks>The dictionary uses case-insensitive keys.</remarks>
public IDictionary<string, object> Data{ get; private set; }
/// <summary>
/// Gets or sets the block content fragment.
/// </summary>
public IPublishedContent Fragment { get; private set; }
public T GetData<T>(string key)
{
return GetData(key, default(T));
}
public T GetData<T>(string key, T defaultValue)
{
if (Data == null) return defaultValue;
object o;
if (!Data.TryGetValue(key, out o)) return defaultValue;
return o is T ? (T) o : defaultValue;
}
}
} | using System.Collections.Generic;
using Umbraco.Core.Models;
namespace Zbu.Blocks
{
/// <summary>
/// Represents a block to be rendered.
/// </summary>
/// <remarks>Name makes a block named ie unique, Type initialized all properties from a predefined
/// type, Source overrides name if needed. Such as when using the same source for two types of blocks
/// which would be differenciated by their name.</remarks>
public class RenderingBlock
{
/// <summary>
/// Initializes a new instance of the <see cref="RenderingBlock"/> class with a name, a source,
/// a collection of blocks, and data and fragment json.
/// </summary>
/// <param name="name">The name of the block.</param>
/// <param name="source">The block source.</param>
/// <param name="blocks">The block inner blocks.</param>
/// <param name="data">The block data dictionary (using case-insensitive keys).</param>
/// <param name="fragment">The block content fragment.</param>
/// <remarks>The block data can be null.</remarks>
public RenderingBlock(string name, string source, IEnumerable<RenderingBlock> blocks,
IDictionary<string, object> data, IPublishedContent fragment)
{
Name = name;
Source = source;
Blocks = new RenderingBlockCollection(blocks);
Data = data;
Fragment = fragment;
}
/// <summary>
/// Gets or sets the name of the block.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets or sets the source of the block.
/// </summary>
/// <remarks>The source determines the view that should be used to render the block.</remarks>
public string Source { get; private set; }
/// <summary>
/// Gets or sets the inner blocks collection of the block.
/// </summary>
public RenderingBlockCollection Blocks { get; private set; }
/// <summary>
/// Gets or sets the block data dictionary.
/// </summary>
/// <remarks>The dictionary uses case-insensitive keys.</remarks>
public IDictionary<string, object> Data{ get; private set; }
/// <summary>
/// Gets or sets the block content fragment.
/// </summary>
public IPublishedContent Fragment { get; private set; }
}
} | mit | C# |
814e83f21052e969e4f9bfe7c7e22e80c8a35eaf | fix tests | Stelmashenko-A/GameOfLife,Stelmashenko-A/GameOfLife,Stelmashenko-A/GameOfLife | GameOfLife.Services.Tests/GameOfLifeTest.cs | GameOfLife.Services.Tests/GameOfLifeTest.cs | using System;
using LifeHost.Business.GameStorage;
using LifeHost.Models;
using NUnit.Framework;
namespace GameOfLife.Services.Tests
{
public class GameOfLifeTest
{
[Test]
public void TestGame()
{
var gol = new LifeHost.Business.GameOfLife.GameOfLife();
gol.StateCalculator = new StateCalculator();
gol.Converter = new Converter();
gol.GameStorage=new GameStorage();
gol.Process(new RequestForProcessing {Field = "0000000100000100111000000",Id = Guid.NewGuid(),Pats = 10,Steps = 100});
}
}
} | using System;
using LifeHost.Business.GameStorage;
using LifeHost.Controllers;
using NUnit.Framework;
namespace GameOfLife.Services.Tests
{
public class GameOfLifeTest
{
[Test]
public void TestGame()
{
LifeHost.Controllers.GameOfLife gol = new LifeHost.Controllers.GameOfLife();
gol.StateCalculator = new StateCalculator();
gol.Converter = new Converter();
gol.GameStorage=new GameStorage();
gol.Process(new RequestForProcessing {Field = "0000000100000100111000000",Id = Guid.NewGuid(),Pats = 10,Steps = 100});
}
}
} | mit | C# |
079d0133ccbd271b4fd51cfa29ad79380b32ac17 | Update StaticServeBootstrapper.cs | phonicmouse/SharpPaste,phonicmouse/SharpPaste | Bootstrappers/StaticServeBootstrapper.cs | Bootstrappers/StaticServeBootstrapper.cs | /*
* Created by SharpDevelop.
* User: Phonic Mouse
* Date: 02/08/2016
* Time: 17:32
*/
using Nancy;
using Nancy.Conventions;
namespace SharpPaste
{
public class StaticServeBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/custom", @"custom")); // Serve custom CSS & JS folder
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/fonts", @"packages\bootstrap.3.3.4\content\fonts")); // Serve bootstrap's fonts folder
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/css/bootstrap.css", @"packages\bootstrap.3.3.4\content\content\bootstrap.min.css")); // Serve Bootstrap CSS
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/css/bootstrap-flat.css", @"packages\bootstrap.flat.3.3.4\content\content\bootstrap-flat.min.css")); // Serve Bootstrap Flat Theme CSS
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/js/bootstrap.js", @"packages\bootstrap.3.3.4\content\scripts\bootstrap.min.js")); // Serve Bootstrap JS
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/js/jquery.js", @"packages\jquery.3.1.1\content\scripts\jquery-3.1.1.min.js")); // Serve jQuery
base.ConfigureConventions(nancyConventions);
}
}
}
| /*
* Created by SharpDevelop.
* User: Phonic Mouse
* Date: 02/08/2016
* Time: 17:32
*/
using Nancy
using Nancy.Conventions
namespace SharpPaste
{
public class StaticServeBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/custom", @"custom")); // Serve custom CSS & JS folder
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/fonts", @"packages\bootstrap.3.3.4\content\fonts")); // Serve bootstrap's fonts folder
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/css/bootstrap.css", @"packages\bootstrap.3.3.4\content\content\bootstrap.min.css")); // Serve Bootstrap CSS
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/css/bootstrap-flat.css", @"packages\bootstrap.flat.3.3.4\content\content\bootstrap-flat.min.css")); // Serve Bootstrap Flat Theme CSS
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/js/bootstrap.js", @"packages\bootstrap.3.3.4\content\scripts\bootstrap.min.js")); // Serve Bootstrap JS
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile("/js/jquery.js", @"packages\jquery.3.1.1\content\scripts\jquery-3.1.1.min.js")); // Serve jQuery
base.ConfigureConventions(nancyConventions);
}
}
}
| mit | C# |
5931de61ab266e5e75223af528d9d748cb49f9c4 | Fix rounding in ChallengeSolution.ClearanceQuery when calls Answer.ToString | elcattivo/CloudFlareUtilities | CloudFlareUtilities/ChallengeSolution.cs | CloudFlareUtilities/ChallengeSolution.cs | using System;
using System.Globalization;
namespace CloudFlareUtilities
{
/// <summary>
/// Holds the information, which is required to pass the CloudFlare clearance.
/// </summary>
public struct ChallengeSolution : IEquatable<ChallengeSolution>
{
public ChallengeSolution(string clearancePage, string verificationCode, string pass, double answer)
{
ClearancePage = clearancePage;
VerificationCode = verificationCode;
Pass = pass;
Answer = answer;
}
public string ClearancePage { get; }
public string VerificationCode { get; }
public string Pass { get; }
public double Answer { get; }
// Using .ToString("R") to reduse answer rounding
public string ClearanceQuery => $"{ClearancePage}?jschl_vc={VerificationCode}&pass={Pass}&jschl_answer={Answer.ToString("R", CultureInfo.InvariantCulture)}";
public static bool operator ==(ChallengeSolution solutionA, ChallengeSolution solutionB)
{
return solutionA.Equals(solutionB);
}
public static bool operator !=(ChallengeSolution solutionA, ChallengeSolution solutionB)
{
return !(solutionA == solutionB);
}
public override bool Equals(object obj)
{
var other = obj as ChallengeSolution?;
return other.HasValue && Equals(other.Value);
}
public override int GetHashCode()
{
return ClearanceQuery.GetHashCode();
}
public bool Equals(ChallengeSolution other)
{
return other.ClearanceQuery == ClearanceQuery;
}
}
} | using System;
using System.Globalization;
namespace CloudFlareUtilities
{
/// <summary>
/// Holds the information, which is required to pass the CloudFlare clearance.
/// </summary>
public struct ChallengeSolution : IEquatable<ChallengeSolution>
{
public ChallengeSolution(string clearancePage, string verificationCode, string pass, double answer)
{
ClearancePage = clearancePage;
VerificationCode = verificationCode;
Pass = pass;
Answer = answer;
}
public string ClearancePage { get; }
public string VerificationCode { get; }
public string Pass { get; }
public double Answer { get; }
public string ClearanceQuery => $"{ClearancePage}?jschl_vc={VerificationCode}&pass={Pass}&jschl_answer={Answer.ToString(CultureInfo.InvariantCulture)}";
public static bool operator ==(ChallengeSolution solutionA, ChallengeSolution solutionB)
{
return solutionA.Equals(solutionB);
}
public static bool operator !=(ChallengeSolution solutionA, ChallengeSolution solutionB)
{
return !(solutionA == solutionB);
}
public override bool Equals(object obj)
{
var other = obj as ChallengeSolution?;
return other.HasValue && Equals(other.Value);
}
public override int GetHashCode()
{
return ClearanceQuery.GetHashCode();
}
public bool Equals(ChallengeSolution other)
{
return other.ClearanceQuery == ClearanceQuery;
}
}
} | mit | C# |
758134ded669f65f125f6bb8b4452839c95efe9e | Optimize Brazil | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Nager.Date/PublicHolidays/BrazilProvider.cs | Nager.Date/PublicHolidays/BrazilProvider.cs | using Nager.Date.Contract;
using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class BrazilProvider : IPublicHolidayProvider
{
public IEnumerable<PublicHoliday> Get(int year)
{
//Brazil
//https://en.wikipedia.org/wiki/Public_holidays_in_Brazil
//Contribution: github.com/mauricioribeiro
var countryCode = CountryCode.BR;
var items = new List<PublicHoliday>();
// official holidays
items.Add(new PublicHoliday(year, 1, 1, "Confraternização Universal", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 21, "Dia de Tiradentes", "Tiradentes", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Dia do Trabalhador", "Labour Day", countryCode));
items.Add(new PublicHoliday(year, 9, 7, "Dia da Independência", "Independence Day", countryCode));
items.Add(new PublicHoliday(year, 10, 12, "Nossa Senhora Aparecida", "Children's Day", countryCode));
items.Add(new PublicHoliday(year, 11, 2, "Dia de Finados", "Day of the Dead", countryCode));
items.Add(new PublicHoliday(year, 11, 15, "Proclamação da República", "Republic Proclamation Day", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "Natal", "Christmas Day", countryCode, null));
// TODO non-official holidays
return items.OrderBy(o => o.Date);
}
}
}
| using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class BrazilProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Brazil
//https://en.wikipedia.org/wiki/Public_holidays_in_Brazil
//Contribution: github.com/mauricioribeiro
var countryCode = CountryCode.BR;
var easterSunday = base.EasterSunday(year);
var items = new List<PublicHoliday>();
// official holidays
items.Add(new PublicHoliday(year, 1, 1, "Confraternização Universal", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 21, "Dia de Tiradentes", "Tiradentes", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Dia do Trabalhador", "Labour Day", countryCode));
items.Add(new PublicHoliday(year, 9, 7, "Dia da Independência", "Independence Day", countryCode));
items.Add(new PublicHoliday(year, 10, 12, "Nossa Senhora Aparecida", "Children's Day", countryCode));
items.Add(new PublicHoliday(year, 11, 2, "Dia de Finados", "Day of the Dead", countryCode));
items.Add(new PublicHoliday(year, 11, 15, "Proclamação da República", "Republic Proclamation Day", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "Natal", "Christmas Day", countryCode, null));
// TODO non-official holidays
return items.OrderBy(o => o.Date);
}
}
}
| mit | C# |
218c0de0cd7f1f72cc46e199444c183fad329adf | Fix exception when dumping a null parameter | mios-fi/mios.localization | Localization/Localizers/NullLocalizer.cs | Localization/Localizers/NullLocalizer.cs | using System;
using System.Linq;
namespace Mios.Localization.Localizers {
public class NullLocalizer {
public static LocalizedString Instance(string key, params object[] args) {
var parameters = args.Any()
? "["+String.Join(",",args.Select(t=>(t??String.Empty).ToString()).ToArray())+"]"
: String.Empty;
return new LocalizedString(key+parameters, null);
}
}
}
| using System;
namespace Mios.Localization.Localizers {
public class NullLocalizer {
public static LocalizedString Instance(string key, params object[] args) {
return new LocalizedString(String.Format(key,args), null);
}
}
}
| bsd-2-clause | C# |
262a1c27dd9948dbcc0052a618f2815c81c6eefb | Update WordDelimiterTokenFilter.cs | joehmchan/elasticsearch-net,joehmchan/elasticsearch-net,joehmchan/elasticsearch-net,wawrzyn/elasticsearch-net,robertlyson/elasticsearch-net,robrich/elasticsearch-net,robertlyson/elasticsearch-net,wawrzyn/elasticsearch-net,gayancc/elasticsearch-net,gayancc/elasticsearch-net,robertlyson/elasticsearch-net,gayancc/elasticsearch-net,robrich/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net | src/Nest/Domain/Analysis/TokenFilter/WordDelimiterTokenFilter.cs | src/Nest/Domain/Analysis/TokenFilter/WordDelimiterTokenFilter.cs | using System.Collections.Generic;
using Newtonsoft.Json;
using System;
namespace Nest
{
/// <summary>
/// Named word_delimiter, it Splits words into subwords and performs optional transformations on subword groups.
/// </summary>
public class WordDelimiterTokenFilter : TokenFilterBase
{
public WordDelimiterTokenFilter()
: base("word_delimiter")
{
}
[JsonProperty("generate_word_parts")]
public bool? GenerateWordParts { get; set; }
[JsonProperty("generate_number_parts")]
public bool? GenerateNumberParts { get; set; }
[JsonProperty("catenate_words")]
public bool? CatenateWords { get; set; }
[JsonProperty("catenate_numbers")]
public bool? CatenateNumbers { get; set; }
[JsonProperty("catenate_all")]
public bool? CatenateAll { get; set; }
[JsonProperty("split_on_case_change")]
public bool? SplitOnCaseChange { get; set; }
[JsonProperty("preserve_original")]
public bool? PreserveOriginal { get; set; }
[JsonProperty("split_on_numerics")]
public bool? SplitOnNumerics { get; set; }
[JsonProperty("stem_english_possessive")]
public bool? StemEnglishPossessive { get; set; }
[JsonProperty("protected_words")]
public IList<string> ProtectedWords { get; set; }
[JsonProperty("protected_words_path")]
public string ProtectedWordsPath { get; set; }
[Obsolete("Please switch to TypeTableList property", true)]
public string TypeTable { get; set; }
[JsonProperty("type_table")]
public List<string> TypeTableList { get; set; }
[JsonProperty("type_table_path")]
public string TypeTablePath { get; set; }
}
}
| using System.Collections.Generic;
using Newtonsoft.Json;
using System;
namespace Nest
{
/// <summary>
/// Named word_delimiter, it Splits words into subwords and performs optional transformations on subword groups.
/// </summary>
public class WordDelimiterTokenFilter : TokenFilterBase
{
public WordDelimiterTokenFilter()
: base("word_delimiter")
{
}
[JsonProperty("generate_word_parts")]
public bool? GenerateWordParts { get; set; }
[JsonProperty("generate_number_parts")]
public bool? GenerateNumberParts { get; set; }
[JsonProperty("catenate_words")]
public bool? CatenateWords { get; set; }
[JsonProperty("catenate_numbers")]
public bool? CatenateNumbers { get; set; }
[JsonProperty("catenate_all")]
public bool? CatenateAll { get; set; }
[JsonProperty("split_on_case_change")]
public bool? SplitOnCaseChange { get; set; }
[JsonProperty("preserve_original")]
public bool? PreserveOriginal { get; set; }
[JsonProperty("split_on_numerics")]
public bool? SplitOnNumerics { get; set; }
[JsonProperty("stem_english_possessive")]
public bool? StemEnglishPossessive { get; set; }
[JsonProperty("protected_words")]
public IList<string> ProtectedWords { get; set; }
[JsonProperty("protected_words_path ")]
public string ProtectedWordsPath { get; set; }
[Obsolete("Please switch to TypeTableList property", true)]
public string TypeTable { get; set; }
[JsonProperty("type_table")]
public List<string> TypeTableList { get; set; }
[JsonProperty("type_table_path")]
public string TypeTablePath { get; set; }
}
} | apache-2.0 | C# |
acaf9e0fa25b231229f0e9b2d8120f8c6aa0d5ff | Change naming in test and add one | horsdal/Nancy.Linker | src/Nancy.Linker.Tests/ResourceLinkerTests.cs | src/Nancy.Linker.Tests/ResourceLinkerTests.cs | namespace Nancy.Linker.Tests
{
using System;
using System.Runtime.InteropServices;
using Testing;
using Xunit;
public class ResourceLinker_Should
{
private Browser app;
public class TestModule : NancyModule
{
public static ResourceLinker linker;
public TestModule(ResourceLinker linker)
{
TestModule.linker = linker;
Get["foo", "/foo"] = _ => 200;
Get["bar", "/bar/{id}"] = _ => 200;
}
}
public ResourceLinker_Should()
{
app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost"));
}
[Fact]
public void generate_absolute_uri_correctly_when_route_has_no_params()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo", new {});
Assert.Equal("http://localhost/foo", uriString.ToString());
}
[Fact]
public void generate_absolute_uri_correctly_when_route_has_params()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 });
Assert.Equal("http://localhost/bar/123", uriString.ToString());
}
[Fact]
public void throw_if_parameter_from_template_cannot_be_bound()
{
Assert.Throws<ArgumentException>(() =>
TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new { })
);
}
}
} | namespace Nancy.Linker.Tests
{
using System.Runtime.InteropServices;
using Testing;
using Xunit;
public class ResourceLinkerTests
{
private Browser app;
public class TestModule : NancyModule
{
public static ResourceLinker linker;
public TestModule(ResourceLinker linker)
{
TestModule.linker = linker;
Get["foo", "/foo"] = _ => 200;
Get["bar", "/bar/{id}"] = _ => 200;
}
}
public ResourceLinkerTests()
{
app = new Browser(with => with.Module<TestModule>(), defaults: to => to.HostName("localhost"));
}
[Fact]
public void Link_generated_is_correct_when_base_uri_has_trailing_slash()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "foo", new {});
Assert.Equal("http://localhost/foo", uriString.ToString());
}
[Fact]
public void Link_generated_is_correct_with_bound_parameter()
{
var uriString = TestModule.linker.BuildAbsoluteUri(app.Get("/foo").Context, "bar", new {id = 123 });
Assert.Equal("http://localhost/bar/123", uriString.ToString());
}
[Fact]
public void Argument_exception_is_thrown_if_parameter_from_template_cannot_be_bound()
{
}
}
} | mit | C# |
37571700433256d480106f7627450f19003ef87d | Update src/Umbraco.Core/WebAssets/BundlingOptions.cs | marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS | src/Umbraco.Core/WebAssets/BundlingOptions.cs | src/Umbraco.Core/WebAssets/BundlingOptions.cs | using System;
namespace Umbraco.Cms.Core.WebAssets
{
public struct BundlingOptions : IEquatable<BundlingOptions>
{
public static BundlingOptions OptimizedAndComposite => new BundlingOptions(true, true);
public static BundlingOptions OptimizedNotComposite => new BundlingOptions(true, false);
public static BundlingOptions NotOptimizedNotComposite => new BundlingOptions(false, false);
public static BundlingOptions NotOptimizedAndComposite => new BundlingOptions(false, true);
public BundlingOptions(bool optimizeOutput = true, bool enabledCompositeFiles = true)
{
OptimizeOutput = optimizeOutput;
EnabledCompositeFiles = enabledCompositeFiles;
}
/// <summary>
/// If true, the files in the bundle will be minified
/// </summary>
public bool OptimizeOutput { get; }
/// <summary>
/// If true, the files in the bundle will be combined, if false the files
/// will be served as individual files.
/// </summary>
public bool EnabledCompositeFiles { get; }
public override bool Equals(object obj) => obj is BundlingOptions options && Equals(options);
public bool Equals(BundlingOptions other) => OptimizeOutput == other.OptimizeOutput && EnabledCompositeFiles == other.EnabledCompositeFiles;
public override int GetHashCode()
{
int hashCode = 2130304063;
hashCode = hashCode * -1521134295 + OptimizeOutput.GetHashCode();
hashCode = hashCode * -1521134295 + EnabledCompositeFiles.GetHashCode();
return hashCode;
}
public static bool operator ==(BundlingOptions left, BundlingOptions right) => left.Equals(right);
public static bool operator !=(BundlingOptions left, BundlingOptions right) => !(left == right);
}
}
| using System;
namespace Umbraco.Cms.Core.WebAssets
{
public struct BundlingOptions : IEquatable<BundlingOptions>
{
public static BundlingOptions OptimizedAndComposite => new BundlingOptions(true, true);
public static BundlingOptions OptimizedNotComposite => new BundlingOptions(true, false);
public static BundlingOptions NotOptimizedNotComposite => new BundlingOptions(false, false);
public static BundlingOptions NotOptimizedAndComposite => new BundlingOptions(false, false);
public BundlingOptions(bool optimizeOutput = true, bool enabledCompositeFiles = true)
{
OptimizeOutput = optimizeOutput;
EnabledCompositeFiles = enabledCompositeFiles;
}
/// <summary>
/// If true, the files in the bundle will be minified
/// </summary>
public bool OptimizeOutput { get; }
/// <summary>
/// If true, the files in the bundle will be combined, if false the files
/// will be served as individual files.
/// </summary>
public bool EnabledCompositeFiles { get; }
public override bool Equals(object obj) => obj is BundlingOptions options && Equals(options);
public bool Equals(BundlingOptions other) => OptimizeOutput == other.OptimizeOutput && EnabledCompositeFiles == other.EnabledCompositeFiles;
public override int GetHashCode()
{
int hashCode = 2130304063;
hashCode = hashCode * -1521134295 + OptimizeOutput.GetHashCode();
hashCode = hashCode * -1521134295 + EnabledCompositeFiles.GetHashCode();
return hashCode;
}
public static bool operator ==(BundlingOptions left, BundlingOptions right) => left.Equals(right);
public static bool operator !=(BundlingOptions left, BundlingOptions right) => !(left == right);
}
}
| mit | C# |
a8a89b7738224f6c1b9d4b5b2874d8cbf321d17c | add TryGet track | lucas-miranda/Raccoon | Raccoon/Graphics/Atlas/AtlasAnimation.cs | Raccoon/Graphics/Atlas/AtlasAnimation.cs | using System.Collections;
using System.Collections.Generic;
namespace Raccoon.Graphics {
public class AtlasAnimation : AtlasSubTexture, IEnumerable {
public const string DefaultAllFramesTrackName = "all";
#region Private Members
private Dictionary<string, List<AtlasAnimationFrame>> _tracks;
#endregion Private Members
#region Constructors
public AtlasAnimation(Texture texture, Rectangle sourceRegion) : base(texture, sourceRegion, new Rectangle(Vector2.Zero, sourceRegion.Size)) {
_tracks = new Dictionary<string, List<AtlasAnimationFrame>> {
{ DefaultAllFramesTrackName, new List<AtlasAnimationFrame>() }
};
}
public AtlasAnimation(Texture texture) : this(texture, texture.Bounds) {
}
#endregion Constructors
#region Public Properties
public List<AtlasAnimationFrame> this[string tag] {
get {
return _tracks[tag];
}
}
#endregion Public Properties
#region Public Methods
public bool TryGetTrack(string tag, out List<AtlasAnimationFrame> track) {
return _tracks.TryGetValue(tag, out track);
}
public bool TryGetDefaultTrack(out List<AtlasAnimationFrame> frames) {
return TryGetTrack(DefaultAllFramesTrackName, out frames);
}
public void AddFrame(Rectangle clippingRegion, int duration, Rectangle originalFrame, string targetTag) {
if (!_tracks.ContainsKey(targetTag)) {
_tracks.Add(targetTag, new List<AtlasAnimationFrame>());
}
_tracks[targetTag].Add(new AtlasAnimationFrame(duration, clippingRegion, originalFrame));
}
public void AddFrame(Rectangle clippingRegion, int duration, string targetTag) {
if (!_tracks.ContainsKey(targetTag)) {
_tracks.Add(targetTag, new List<AtlasAnimationFrame>());
}
_tracks[targetTag].Add(new AtlasAnimationFrame(duration, clippingRegion));
}
public override void Dispose() {
if (IsDisposed) {
return;
}
_tracks.Clear();
base.Dispose();
}
public IEnumerator GetEnumerator() {
return _tracks.GetEnumerator();
}
#endregion Public Methods
}
}
| using System.Collections;
using System.Collections.Generic;
namespace Raccoon.Graphics {
public class AtlasAnimation : AtlasSubTexture, IEnumerable {
#region Private Members
private Dictionary<string, List<AtlasAnimationFrame>> _tracks;
#endregion Private Members
#region Constructors
public AtlasAnimation(Texture texture, Rectangle sourceRegion) : base(texture, sourceRegion, new Rectangle(Vector2.Zero, sourceRegion.Size)) {
_tracks = new Dictionary<string, List<AtlasAnimationFrame>> {
{ "all", new List<AtlasAnimationFrame>() }
};
}
public AtlasAnimation(Texture texture) : this(texture, texture.Bounds) {
}
#endregion Constructors
#region Public Properties
public List<AtlasAnimationFrame> this[string tag] {
get {
return _tracks[tag];
}
}
#endregion Public Properties
#region Public Methods
public void AddFrame(Rectangle clippingRegion, int duration, Rectangle originalFrame, string targetTag) {
if (!_tracks.ContainsKey(targetTag)) {
_tracks.Add(targetTag, new List<AtlasAnimationFrame>());
}
_tracks[targetTag].Add(new AtlasAnimationFrame(duration, clippingRegion, originalFrame));
}
public void AddFrame(Rectangle clippingRegion, int duration, string targetTag) {
if (!_tracks.ContainsKey(targetTag)) {
_tracks.Add(targetTag, new List<AtlasAnimationFrame>());
}
_tracks[targetTag].Add(new AtlasAnimationFrame(duration, clippingRegion));
}
public override void Dispose() {
if (IsDisposed) {
return;
}
_tracks.Clear();
base.Dispose();
}
public IEnumerator GetEnumerator() {
return _tracks.GetEnumerator();
}
#endregion Public Methods
}
}
| mit | C# |
2942aeb7512e15debdbc070b04591df60a63147a | Fix bugs that native functions with parameters are not instantiable due to parsing mistakes | Seddryck/NBi,Seddryck/NBi | NBi.Core/Transformation/Transformer/NativeTransformationfactory.cs | NBi.Core/Transformation/Transformer/NativeTransformationfactory.cs | using NBi.Core.Transformation.Transformer.Native;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Transformation.Transformer
{
public class NativeTransformationFactory
{
public INativeTransformation Instantiate(string code)
{
var textInfo = CultureInfo.InvariantCulture.TextInfo;
var parameters = code.Replace("(", ",")
.Replace(")", ",")
.Replace(" ", "")
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.ToList().Skip(1).Select(x => x.Trim()).ToArray();
var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(') - 1) : code;
var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime");
var clazz = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(t => t.GetTypes())
.Where(
t => t.IsClass
&& t.IsAbstract == false
&& t.Name == className
&& t.GetInterface("INativeTransformation") != null)
.SingleOrDefault();
if (clazz == null)
throw new NotImplementedTransformationException(className);
return (INativeTransformation)Activator.CreateInstance(clazz, parameters);
}
}
}
| using NBi.Core.Transformation.Transformer.Native;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Transformation.Transformer
{
public class NativeTransformationFactory
{
public INativeTransformation Instantiate(string code)
{
var textInfo = CultureInfo.InvariantCulture.TextInfo;
var parameters = code.Replace("(", ",")
.Replace(")", ",")
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.ToList().Skip(1).Select(x => x.Trim()).ToArray();
var classToken = code.Contains("(") ? code.Replace(" ", "").Substring(0, code.IndexOf('(')) : code;
var className = textInfo.ToTitleCase(classToken.Trim().Replace("-", " ")).Replace(" ", "").Replace("Datetime", "DateTime");
var clazz = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(t => t.GetTypes())
.Where(
t => t.IsClass
&& t.IsAbstract == false
&& t.Name == className
&& t.GetInterface("INativeTransformation") != null)
.SingleOrDefault();
if (clazz == null)
throw new NotImplementedTransformationException(className);
return (INativeTransformation)Activator.CreateInstance(clazz, parameters);
}
}
}
| apache-2.0 | C# |
224a615e09bf89ffd8cb939ac6cb6f3080422f95 | Send send damage call | nterry/AS3RG | Assets/Scripts/Spikes/Spikes.cs | Assets/Scripts/Spikes/Spikes.cs | /*
* Ben - 3/26/2015
*
* This script still needs to have the animate added
* and be tested to see if the sending the damage
* message works.
*
* */
using UnityEngine;
using System.Collections;
public class Spikes : MonoBehaviour
{
public float damageValue = 1.0f;
void awake()
{
Debug.Log ("Spikes are awake!");
}
/* This will check to see if the player has stepped onto the spikes
* if so then it will send a message to the player object to run
* the damage method.
* */
void onTriggerStay(Collider other)
{
other.SendMessage("Damage", damageValue, SendMessageOptions.DontRequireReceiver);
}
}
| /*
* Ben - 3/26/2015
*
* This script still needs to have the animate added
* and be tested to see if the sending the damage
* message works.
*
* */
using UnityEngine;
using System.Collections;
public class Spikes : MonoBehaviour
{
public float damageValue = 1.0f;
GameObject player;
void awake()
{
//Get the player object
player = GameObject.FindGameObjectWithTag ("Player");
}
/* This will check to see if the player has stepped onto the spikes
* if so then it will send a message to the player object to run
* the damage method.
* */
void onTriggerStay(Collider other)
{
if (other.gameObject == player)
{
other.SendMessage("Damage", damageValue, SendMessageOptions.DontRequireReceiver);
}
}
}
| mit | C# |
5ed8b7bc92d6be52abb5b07d698e72ca8de03730 | simplify importer | SimonCropp/CaptureSnippets | CaptureSnippets/CodeImporter.cs | CaptureSnippets/CodeImporter.cs | using System.Diagnostics;
using System.Linq;
namespace CaptureSnippets
{
public static class CodeImporter
{
public static UpdateResult Update(string codeFolder, string[] extensionsToSearch, string docsFolder)
{
var stopwatch = Stopwatch.StartNew();
var result = new UpdateResult();
var codeParser = new CodeFileParser(codeFolder);
var snippets = codeParser.Parse(extensionsToSearch);
var incompleteSnippets = snippets.Where(s => string.IsNullOrWhiteSpace(s.Value)).ToArray();
if (incompleteSnippets.Any())
{
var messages = incompleteSnippets.FormatIncomplete();
result.Errors.AddRange(messages);
return result;
}
result.Snippets = snippets.Count;
var processor = new DocumentFileProcessor(docsFolder);
var processResult = processor.Apply(snippets);
var snippetsNotUsed = snippets.Except(processResult.SnippetsUsed).ToArray();
var snippetsMissed = processResult.SnippetReferences;
if (snippetsMissed.Any())
{
var messages = snippetsMissed.FormatNotFound();
result.Errors.AddRange(messages);
}
if (snippetsNotUsed.Any())
{
var messages = snippetsNotUsed.FormatUnused();
result.Warnings.AddRange(messages);
}
result.Files = processResult.Count;
result.Completed = !result.Errors.Any();
result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
return result;
}
}
} | using System.Diagnostics;
using System.Linq;
namespace CaptureSnippets
{
public class CodeImporter
{
public static UpdateResult Update(string codeFolder, string[] extensionsToSearch, string docsFolder)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = new UpdateResult();
var codeParser = new CodeFileParser(codeFolder);
var snippets = codeParser.Parse(extensionsToSearch);
var incompleteSnippets = snippets.Where(s => string.IsNullOrWhiteSpace(s.Value)).ToArray();
if (incompleteSnippets.Any())
{
var messages = incompleteSnippets.FormatIncomplete();
result.Errors.AddRange(messages);
return result;
}
result.Snippets = snippets.Count;
var processor = new DocumentFileProcessor(docsFolder);
var processResult = processor.Apply(snippets);
var snippetsNotUsed = snippets.Except(processResult.SnippetsUsed).ToArray();
var snippetsMissed = processResult.SnippetReferences;
if (snippetsMissed.Any())
{
var messages = snippetsMissed.FormatNotFound();
result.Errors.AddRange(messages);
}
if (snippetsNotUsed.Any())
{
var messages = snippetsNotUsed.FormatUnused();
result.Warnings.AddRange(messages);
}
result.Files = processResult.Count;
result.Completed = !result.Errors.Any();
stopwatch.Stop();
result.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
return result;
}
}
} | mit | C# |
fc935e354ff6fa5a334e2be56d50941b252a9290 | Fix build break | ErikEJ/EntityFramework.SqlServerCompact,ErikEJ/EntityFramework7.SqlServerCompact | test/EntityFramework.SqlServerCompact.FunctionalTests/BasicEndToEndScenarioForIdentity.cs | test/EntityFramework.SqlServerCompact.FunctionalTests/BasicEndToEndScenarioForIdentity.cs | using System.Data.SqlServerCe;
using System.Linq;
using Xunit;
namespace Microsoft.Data.Entity.FunctionalTests
{
public class BasicEndToEndScenarioForIdentity
{
[Fact]
public void Can_run_end_to_end_scenario()
{
using (var db = new BloggingContext())
{
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
db.Blogs.Add(new Blog { Url = "http://erikej.blogspot.com" });
db.SaveChanges();
var blogs = db.Blogs.ToList();
Assert.Equal(blogs.Count, 1);
Assert.Equal(blogs[0].Url, "http://erikej.blogspot.com");
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
#if SQLCE35
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlCe(@"Data Source=BloggingIdentity.sdf");
}
#else
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlCe(
new SqlCeConnectionStringBuilder
{
DataSource = "BloggingIdentity.sdf"
}
.ConnectionString);
}
#endif
}
public class Blog
{
public int Id { get; set; }
public string Url { get; set; }
}
}
}
| using System.Data.SqlServerCe;
using System.Linq;
using Xunit;
namespace Microsoft.Data.Entity.FunctionalTests
{
public class BasicEndToEndScenarioForIdentity
{
[Fact]
public void Can_run_end_to_end_scenario()
{
using (var db = new BloggingContext())
{
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
db.Blogs.Add(new Blog { Url = "http://erikej.blogspot.com" });
db.SaveChanges();
var blogs = db.Blogs.ToList();
Assert.Equal(blogs.Count, 1);
Assert.Equal(blogs[0].Url, "http://erikej.blogspot.com");
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlCe(
new SqlCeConnectionStringBuilder
{
DataSource = "BloggingIdentity.sdf"
}
.ConnectionString);
}
}
public class Blog
{
public int Id { get; set; }
public string Url { get; set; }
}
}
}
| apache-2.0 | C# |
79bd5d028a561c32991c13a81686e992d466c35d | add last indexed | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string product_description { get; set; }
public string product_quantity { get; set; }
public string product_type { get; set; }
public string code_info { get; set; }
public string reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string recall_number { get; set; }
public string recalling_firm { get; set; }
public string voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string status { get; set; }
public DateTime date_last_indexed { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string product_description { get; set; }
public string product_quantity { get; set; }
public string product_type { get; set; }
public string code_info { get; set; }
public string reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string recall_number { get; set; }
public string recalling_firm { get; set; }
public string voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string status { get; set; }
}
}
| apache-2.0 | C# |
a347bd5bb87d548bc61d4b4e550b5067fe7be770 | update AssemblyInfo | punker76/MahApps.Metro.SimpleChildWindow | MahApps.Metro.SimpleChildWindow/MahApps.Metro.SimpleChildWindow/Properties/AssemblyInfo.cs | MahApps.Metro.SimpleChildWindow/MahApps.Metro.SimpleChildWindow/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("MahApps.Metro.SimpleChildWindow")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MahApps.Metro.SimpleChildWindow")]
[assembly: AssemblyCopyright("Copyright © Jan Karger")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 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("MahApps.Metro.SimpleChildWindow")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("INFORM GmbH")]
[assembly: AssemblyProduct("MahApps.Metro.SimpleChildWindow")]
[assembly: AssemblyCopyright("Copyright © INFORM GmbH 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
75cfcf8ca68fa9b513cfadffdbd2257420ee86d1 | add unit test to the car advert mapper | mdavid626/artemis | src/Artemis.Web.Tests/CarAdvertMapperTest.cs | src/Artemis.Web.Tests/CarAdvertMapperTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Artemis.Common;
using Artemis.Web.Models;
namespace Artemis.Web.Tests
{
[TestClass]
public class CarAdvertMapperTest
{
[TestMethod]
public void TestValidMapping()
{
var vm = new CarAdvertViewModel();
vm.Id = 1;
vm.Title = "Audi";
vm.Price = 5000;
vm.Fuel = "gasoline";
vm.New = false;
var carAdvert = new CarAdvert();
var result = vm.MapTo(carAdvert);
Assert.IsTrue(result);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Artemis.Web.Tests
{
[TestClass]
public class CarAdvertMapperTest
{
[TestMethod]
public void TestMethod1()
{
}
}
}
| mit | C# |
63af54c98411cdcb78fa3ecf7faa2e4d58254c96 | Clean up | Weingartner/SolidworksAddinFramework | DemoMacroFeature/SampleMacroFeature/SampleMacroFeatureDataBase.cs | DemoMacroFeature/SampleMacroFeature/SampleMacroFeatureDataBase.cs | using System.Runtime.Serialization;
using ReactiveUI;
using SolidworksAddinFramework;
namespace DemoMacroFeatures.SampleMacroFeature
{
[DataContract]
public class SampleMacroFeatureDataBase : ReactiveObject
{
private double _Alpha;
[DataMember]
public double Alpha
{
get { return _Alpha; }
set { this.RaiseAndSetIfChanged(ref _Alpha, value); }
}
private SelectionData _Body = SelectionData.Empty;
[DataMember]
public SelectionData Body
{
get { return _Body; }
set { this.RaiseAndSetIfChanged(ref _Body, value); }
}
}
} | using System.Runtime.Serialization;
using ReactiveUI;
using SolidworksAddinFramework;
using SolidWorks.Interop.sldworks;
namespace DemoMacroFeatures.SampleMacroFeature
{
[DataContract]
public class SampleMacroFeatureDataBase : ReactiveObject
{
private double _Alpha;
[DataMember]
public double Alpha
{
get { return _Alpha; }
set { this.RaiseAndSetIfChanged(ref _Alpha, value); }
}
private SelectionData _Body = SelectionData.Empty;
[DataMember]
public SelectionData Body
{
get { return _Body; }
set { this.RaiseAndSetIfChanged(ref _Body, value); }
}
}
} | mit | C# |
79f4e6ce1063950d21ffc534f6f6351e2c8577a8 | Bump version to 2.2.1 | rickyah/ini-parser,davidgrupp/ini-parser,rickyah/ini-parser | src/IniFileParser/Properties/AssemblyInfo.cs | src/IniFileParser/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("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.2.0.1")]
[assembly: AssemblyVersion("2.2.0.1")] | 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("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")] | mit | C# |
d4272e2a1343c67f8f75ad7086371f568f6f973a | Bump version to v2.5.0 | rickyah/ini-parser,rickyah/ini-parser | src/IniFileParser/Properties/AssemblyInfo.cs | src/IniFileParser/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("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.5.0")]
[assembly: AssemblyFileVersion("2.5.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.4.0")]
[assembly: AssemblyFileVersion("2.4.0")]
| mit | C# |
eae62ad4f6f67e5b1f5aa20912682c78bde8ee9a | set network time | azure-contrib/netmfazurestorage | TestRunner/Program.cs | TestRunner/Program.cs | using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Net.NetworkInformation;
using netmfazurestorage.NTP;
using netmfazurestorage.Tests;
namespace netmfazurestorage.TestRunner
{
public class Program
{
private const string AccountName = "netmftest"; // please upload pictures of cats and other larger animals to this storage account.
private const string AccountKey = "gYU/Nf/ib97kHQrVkxhdD3y0lKz6ZOVaR1FjeDpESecGuqZOEq1TE+5+SXfZ/DBzKsXH3m0NDsLxTbTqQxL9yA==";
public static void Main()
{
NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0];
if (!networkInterface.IsDhcpEnabled || !networkInterface.IsDynamicDnsEnabled)
{
networkInterface.EnableDhcp();
networkInterface.EnableDynamicDns();
networkInterface.RenewDhcpLease();
Debug.Print("Interface set to " + networkInterface.IPAddress);
}
if (DateTime.Now < new DateTime(2012, 01, 01))
{
var networkTime = NtpClient.GetNetworkTime();
Utility.SetLocalTime(networkTime);
}
var queueTests = new QueueTests(AccountName, AccountKey);
queueTests.Run();
var tableTests = new TableTests(AccountName, AccountKey);
tableTests.Run();
}
}
}
| using Microsoft.SPOT;
using Microsoft.SPOT.Net.NetworkInformation;
using netmfazurestorage.Tests;
namespace netmfazurestorage.TestRunner
{
public class Program
{
private const string AccountName = "netmftest"; // please upload pictures of cats and other larger animals to this storage account.
private const string AccountKey = "gYU/Nf/ib97kHQrVkxhdD3y0lKz6ZOVaR1FjeDpESecGuqZOEq1TE+5+SXfZ/DBzKsXH3m0NDsLxTbTqQxL9yA==";
public static void Main()
{
NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0];
if (!networkInterface.IsDhcpEnabled || !networkInterface.IsDynamicDnsEnabled)
{
networkInterface.EnableDhcp();
networkInterface.EnableDynamicDns();
networkInterface.RenewDhcpLease();
Debug.Print("Interface set to " + networkInterface.IPAddress);
}
var queueTests = new QueueTests(AccountName, AccountKey);
queueTests.Run();
var tableTests = new TableTests(AccountName, AccountKey);
tableTests.Run();
}
}
}
| apache-2.0 | C# |
64232514172352374120127774ed151d88413de3 | fix test fail | MagnusTiberius/GigaBoom | UnitTest/UnitTest1.cs | UnitTest/UnitTest1.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using GigaBoomLib;
using GigaBoomLib.Data;
namespace UnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
//Connection c = new Connection();
}
[TestMethod]
public void TestMethod2()
{
User u = new User();
bool v1 = u.FindLoginName("test2324");
bool v2 = u.Find(3);
}
[TestMethod]
public void TestMethod3()
{
User u = new User();
u.Insert("Aaaaaa");
u.AddEmail("test1@email.com","pass1");
}
[TestMethod]
public void TestMethod1001()
{
List<PersonProfile> list = new List<PersonProfile>();
for (int i = 0; i < 200; i++)
{
PersonProfile p = DataGenerator.GeneratePersonProfile();
System.Diagnostics.Debug.WriteLine(string.Format( "{0} \n", p.ToString() ));
list.Add(p);
}
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using GigaBoomLib;
using GigaBoomLib.Data;
namespace UnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Connection c = new Connection();
}
[TestMethod]
public void TestMethod2()
{
User u = new User();
bool v1 = u.FindLoginName("test2324");
bool v2 = u.Find(3);
}
[TestMethod]
public void TestMethod3()
{
User u = new User();
u.Insert("Aaaaaa");
u.AddEmail("test1@email.com","pass1");
}
[TestMethod]
public void TestMethod1001()
{
List<PersonProfile> list = new List<PersonProfile>();
for (int i = 0; i < 200; i++)
{
PersonProfile p = DataGenerator.GeneratePersonProfile();
System.Diagnostics.Debug.WriteLine(string.Format( "{0} \n", p.ToString() ));
list.Add(p);
}
}
}
}
| mit | C# |
384fb4e3e4a1325c436213751a61b141c6e604b9 | Update src/Avalonia.Controls/Notifications/Notification.cs | akrisiun/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia | src/Avalonia.Controls/Notifications/Notification.cs | src/Avalonia.Controls/Notifications/Notification.cs | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
namespace Avalonia.Controls.Notifications
{
/// <summary>
/// A notification that can be shown in a window or by the host operating system.
/// Can be displayed by both <see cref="INotificationManager"/> and <see cref="IManagedNotificationManager"/>
/// </summary>
/// <remarks>
/// This class represents a notification that can be displayed either in a window using
/// <see cref="WindowNotificationManager"/> or by the host operating system (to be implemented).
/// </remarks>
public class Notification : INotification
{
/// <summary>
/// Initializes a new instance of the <see cref="Notification"/> class.
/// </summary>
/// <param name="title">The title of the notification.</param>
/// <param name="message">The message to be displayed in the notification.</param>
/// <param name="type">The <see cref="NotificationType"/> of the notification.</param>
/// <param name="expiration">The expiry time at which the notification will close.
/// Use <see cref="TimeSpan.Zero"/> for notifications that will remain open.</param>
/// <param name="onClick">An Action to call when the notification is clicked.</param>
/// <param name="onClose">An Action to call when the notification is closed.</param>
public Notification(string title,
string message,
NotificationType type = NotificationType.Information,
TimeSpan? expiration = null,
Action onClick = null,
Action onClose = null)
{
Title = title;
Message = message;
Type = type;
Expiration = expiration.HasValue ? expiration.Value : TimeSpan.FromSeconds(5);
OnClick = onClick;
OnClose = onClose;
}
/// <inheritdoc/>
public string Title { get; private set; }
/// <inheritdoc/>
public string Message { get; private set; }
/// <inheritdoc/>
public NotificationType Type { get; private set; }
/// <inheritdoc/>
public TimeSpan Expiration { get; private set; }
/// <inheritdoc/>
public Action OnClick { get; private set; }
/// <inheritdoc/>
public Action OnClose { get; private set; }
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
namespace Avalonia.Controls.Notifications
{
/// <summary>
/// A notification that can be shown in a window or by the host operating system.
/// Can be displayed by both <see cref="INotificationManager"/> and <see cref="IManagedNotificationManager"/>
/// </summary>
/// <remarks>
/// This class represents a notification that can be displayed either in a window using
/// <see cref="WindowNotificationManager"/> or by the host operating system (to be implemented).
/// </remarks>
public class Notification : INotification
{
/// <summary>
/// Initializes a new instance of the <see cref="Notification"/> class.
/// </summary>
/// <param name="title">The title of the notification.</param>
/// <param name="message">The message to be displayed in the notification.</param>
/// <param name="type">The <see cref="NotificationType"/> of the notification.</param>
/// <param name="expiration">The expiry time at which the notification will close.
/// Use <see cref="TimeSpan.Zero"/> for notifications that will remain open.</param>
/// <param name="onClick">An Action to call when the notification is clicked.</param>
/// <param name="onClose">The Action to call when the notification is closed.</param>
public Notification(string title,
string message,
NotificationType type = NotificationType.Information,
TimeSpan? expiration = null,
Action onClick = null,
Action onClose = null)
{
Title = title;
Message = message;
Type = type;
Expiration = expiration.HasValue ? expiration.Value : TimeSpan.FromSeconds(5);
OnClick = onClick;
OnClose = onClose;
}
/// <inheritdoc/>
public string Title { get; private set; }
/// <inheritdoc/>
public string Message { get; private set; }
/// <inheritdoc/>
public NotificationType Type { get; private set; }
/// <inheritdoc/>
public TimeSpan Expiration { get; private set; }
/// <inheritdoc/>
public Action OnClick { get; private set; }
/// <inheritdoc/>
public Action OnClose { get; private set; }
}
}
| mit | C# |
469532ac8716aca5abda3479b91c1e93f69b8705 | Remove bulk from list qual view | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | BatteryCommander.Web/Views/Qualification/List.cshtml | BatteryCommander.Web/Views/Qualification/List.cshtml | @model IEnumerable<BatteryCommander.Common.Models.Qualification>
@using BatteryCommander.Common.Models;
@{
ViewBag.Title = "Qualifications";
}
<h2>@ViewBag.Title @Html.ActionLink("Add New", "New", null, new { @class = "btn btn-primary" })</h2>
<table class="table table-bordered">
<tr>
<th> @Html.DisplayNameFor(model => model.Name)</th>
<th> @Html.DisplayNameFor(model => model.Description)</th>
<th>GO</th>
<th>NOGO</th>
<th>UNKNOWN</th>
<th>Tasks</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.ActionLink(item.Name, "View", new { qualificationId = item.Id }, null)</td>
<td>@Html.DisplayFor(modelItem => item.Description)</td>
<td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Pass)</td>
<td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Fail)</td>
<td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Unknown)</td>
<td>
@foreach (var task in item.Tasks.OrderBy(t => t.Name))
{
<li>@Html.DisplayFor(t => task)</li>
}
</td>
<td>
@Html.ActionLink("View", "View", new { qualificationId = item.Id }, new { @class = "btn btn-default" })
</td>
</tr>
}
</table>
| @model IEnumerable<BatteryCommander.Common.Models.Qualification>
@using BatteryCommander.Common.Models;
@{
ViewBag.Title = "Qualifications";
}
<h2>@ViewBag.Title @Html.ActionLink("Add New", "New", null, new { @class = "btn btn-primary" })</h2>
<table class="table table-bordered">
<tr>
<th> @Html.DisplayNameFor(model => model.Name)</th>
<th> @Html.DisplayNameFor(model => model.Description)</th>
<th>GO</th>
<th>NOGO</th>
<th>UNKNOWN</th>
<th>Tasks</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.ActionLink(item.Name, "View", new { qualificationId = item.Id }, null)</td>
<td>@Html.DisplayFor(modelItem => item.Description)</td>
<td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Pass)</td>
<td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Fail)</td>
<td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Unknown)</td>
<td>
@foreach (var task in item.Tasks.OrderBy(t => t.Name))
{
<li>@Html.DisplayFor(t => task)</li>
}
</td>
<td>
@Html.ActionLink("View", "View", new { qualificationId = item.Id }, new { @class = "btn btn-default" })
<a href="~/Qualification/@item.Id/Update" class="btn btn-warning">Bulk Update Soldiers</a>
</td>
</tr>
}
</table>
| mit | C# |
6954794704cb9f04413d4d7a91f694b75302057b | Fix typo in InfrastrucureTests/Properties | MER-Consulting/chula | Chula/InfrastructureTests/Properties/AssemblyInfo.cs | Chula/InfrastructureTests/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("Tests project for Chula Infrastructure Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MER Consulting")]
[assembly: AssemblyProduct("Chula")]
[assembly: AssemblyCopyright("Copyright © MER Consulting 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("658c5f5d-abd0-4585-b32d-2d0ea5742420")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.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("Tests project for Chula Infrastructure Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MER Consulting")]
[assembly: AssemblyProduct("Chul")]
[assembly: AssemblyCopyright("Copyright © MER Consulting 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("658c5f5d-abd0-4585-b32d-2d0ea5742420")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
867d0b330d0547f10f129359e0d237f912c33a38 | add empty default constructor for json.net to use. (#32) | DynamoDS/GRegClientNET | src/GregClient/Requests/PackageUploadRequestBody.cs | src/GregClient/Requests/PackageUploadRequestBody.cs | using System;
using System.Collections.Generic;
namespace Greg.Requests
{
public class PackageUploadRequestBody : PackageVersionUploadRequestBody
{
//!!!! it is important to keep this in mind:
//https://stackoverflow.com/questions/33107789/json-net-deserialization-constructor-vs-property-rules
/// <summary>
/// Default constructor - should only be used for deserialization with json.net.
/// json.net will construct an empty object and fill it with properties with matching names.
/// </summary>
public PackageUploadRequestBody()
{
}
public PackageUploadRequestBody(string name, string version, string description,
IEnumerable<string> keywords, string license,
string contents, string engine, string engineVersion,
string metadata, string group, IEnumerable<PackageDependency> dependencies,
string siteUrl, string repositoryUrl, bool containsBinaries,
IEnumerable<string> nodeLibraryNames, IEnumerable<string> hostDependencies):
this(name,version,description,
keywords,license,
contents,engine,engineVersion,
metadata,group,dependencies,
siteUrl,repositoryUrl,containsBinaries,
nodeLibraryNames)
{
this.host_dependencies = hostDependencies;
}
[Obsolete("This constructor will be removed in a future release of packageManagerClient.")]
public PackageUploadRequestBody(string name, string version, string description,
IEnumerable<string> keywords, string license,
string contents, string engine, string engineVersion,
string metadata, string group, IEnumerable<PackageDependency> dependencies,
string siteUrl, string repositoryUrl, bool containsBinaries,
IEnumerable<string> nodeLibraryNames)
{
this.name = name;
this.version = version;
this.description = description;
this.keywords = keywords;
this.dependencies = dependencies;
this.contents = contents;
this.engine = engine;
this.group = group;
this.engine_version = engineVersion;
this.engine_metadata = metadata;
this.site_url = siteUrl;
this.repository_url = repositoryUrl;
this.contains_binaries = containsBinaries;
this.node_libraries = nodeLibraryNames;
this.license = license;
}
public string license { get; set; }
}
} | using System;
using System.Collections.Generic;
namespace Greg.Requests
{
public class PackageUploadRequestBody : PackageVersionUploadRequestBody
{
public PackageUploadRequestBody(string name, string version, string description,
IEnumerable<string> keywords, string license,
string contents, string engine, string engineVersion,
string metadata, string group, IEnumerable<PackageDependency> dependencies,
string siteUrl, string repositoryUrl, bool containsBinaries,
IEnumerable<string> nodeLibraryNames, IEnumerable<string> hostDependencies):
this(name,version,description,
keywords,license,
contents,engine,engineVersion,
metadata,group,dependencies,
siteUrl,repositoryUrl,containsBinaries,
nodeLibraryNames)
{
this.host_dependencies = hostDependencies;
}
[Obsolete("This constructor will be removed in a future release of packageManagerClient.")]
public PackageUploadRequestBody(string name, string version, string description,
IEnumerable<string> keywords, string license,
string contents, string engine, string engineVersion,
string metadata, string group, IEnumerable<PackageDependency> dependencies,
string siteUrl, string repositoryUrl, bool containsBinaries,
IEnumerable<string> nodeLibraryNames)
{
this.name = name;
this.version = version;
this.description = description;
this.keywords = keywords;
this.dependencies = dependencies;
this.contents = contents;
this.engine = engine;
this.group = group;
this.engine_version = engineVersion;
this.engine_metadata = metadata;
this.site_url = siteUrl;
this.repository_url = repositoryUrl;
this.contains_binaries = containsBinaries;
this.node_libraries = nodeLibraryNames;
this.license = license;
}
public string license { get; set; }
}
} | mit | C# |
8c9e916eca554675f30c2198c7bb25bcf28603ce | Add message key to jasper headers if set on inbound kafka message | JasperFx/jasper,JasperFx/jasper,JasperFx/jasper | src/Jasper.ConfluentKafka/KafkaTransportProtocol.cs | src/Jasper.ConfluentKafka/KafkaTransportProtocol.cs | using System.Collections.Generic;
using System.Linq;
using System.Text;
using Confluent.Kafka;
using Jasper.Transports;
namespace Jasper.ConfluentKafka
{
public class KafkaTransportProtocol : ITransportProtocol<Message<byte[], byte[]>>
{
public const string KafkaMessageKeyHeader = "Confluent.Kafka.Message.Key";
public Message<byte[], byte[]> WriteFromEnvelope(Envelope envelope)
{
var message = new Message<byte[], byte[]>
{
Headers = new Headers(),
Value = envelope.Data
};
IDictionary<string, object> envelopHeaders = new Dictionary<string, object>();
envelope.WriteToDictionary(envelopHeaders);
var headers = new Headers();
foreach (Header header in envelopHeaders.Select(h => new Header(h.Key, Encoding.UTF8.GetBytes(h.Value.ToString()))))
{
headers.Add(header);
}
message.Headers = headers;
if (!envelopHeaders.TryGetValue(KafkaMessageKeyHeader, out object msgKey)) return message;
if (msgKey is byte[] key)
{
message.Key = key;
}
else
{
message.Key = Encoding.UTF8.GetBytes(msgKey.ToString());
}
return message;
}
public Envelope ReadEnvelope(Message<byte[], byte[]> message)
{
var env = new Envelope()
{
Data = message.Value
};
Dictionary<string, object> incomingHeaders = message.Headers.Select(h => new {h.Key, Value = h.GetValueBytes()})
.ToDictionary(k => k.Key, v => (object)Encoding.UTF8.GetString(v.Value));
if(message.Key != null && !incomingHeaders.ContainsKey(KafkaMessageKeyHeader))
{
env.Headers.Add(KafkaMessageKeyHeader, Encoding.UTF8.GetString(message.Key));
}
env.ReadPropertiesFromDictionary(incomingHeaders);
return env;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Text;
using Confluent.Kafka;
using Jasper.Transports;
namespace Jasper.ConfluentKafka
{
public class KafkaTransportProtocol : ITransportProtocol<Message<byte[], byte[]>>
{
public Message<byte[], byte[]> WriteFromEnvelope(Envelope envelope)
{
var message = new Message<byte[], byte[]>
{
Headers = new Headers(),
Value = envelope.Data
};
IDictionary<string, object> envelopHeaders = new Dictionary<string, object>();
envelope.WriteToDictionary(envelopHeaders);
var headers = new Headers();
foreach (Header header in envelopHeaders.Select(h => new Header(h.Key, Encoding.UTF8.GetBytes(h.Value.ToString()))))
{
headers.Add(header);
}
message.Headers = headers;
if (envelopHeaders.TryGetValue("MessageKey", out var msgKey))
{
if (msgKey is byte[])
{
message.Key = (byte[])msgKey;
}
else
{
message.Key = Encoding.UTF8.GetBytes(msgKey.ToString());
}
}
return message;
}
public Envelope ReadEnvelope(Message<byte[], byte[]> message)
{
var env = new Envelope()
{
Data = message.Value
};
Dictionary<string, object> incomingHeaders = message.Headers.Select(h => new {h.Key, Value = h.GetValueBytes()})
.ToDictionary(k => k.Key, v => (object)Encoding.UTF8.GetString(v.Value));
env.ReadPropertiesFromDictionary(incomingHeaders);
return env;
}
}
}
| mit | C# |
55220fe9248af5874f4b1bb3e8ccb05deaa3254d | Fix ServerErrorException constructor | tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server | src/Tgstation.Server.Client/ServerErrorException.cs | src/Tgstation.Server.Client/ServerErrorException.cs | using System;
using System.Net;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Client
{
/// <summary>
/// Occurs when an error occurs in the server
/// </summary>
public sealed class ServerErrorException : ClientException
{
/// <summary>
/// The raw HTML of the error
/// </summary>
public string Html { get; }
/// <summary>
/// Construct an <see cref="ServerErrorException"/>
/// </summary>
public ServerErrorException() { }
/// <summary>
/// Construct an <see cref="ServerErrorException"/> with <paramref name="html"/>
/// </summary>
/// <param name="html">The raw HTML response of the <see cref="ServerErrorException"/></param>
public ServerErrorException(string html) : base(new ErrorMessage
{
Message = "An internal server error occurred!",
SeverApiVersion = null
}, HttpStatusCode.InternalServerError)
{
Html = html;
}
/// <summary>
/// Construct an <see cref="ServerErrorException"/> with a <paramref name="message"/> and <paramref name="innerException"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
/// <param name="innerException">The inner <see cref="Exception"/> for the base <see cref="Exception"/></param>
public ServerErrorException(string message, Exception innerException) : base(message, innerException) { }
}
} | using System;
using System.Net;
namespace Tgstation.Server.Client
{
/// <summary>
/// Occurs when an error occurs in the server
/// </summary>
public sealed class ServerErrorException : ClientException
{
/// <summary>
/// The raw HTML of the error
/// </summary>
public string Html { get; }
/// <summary>
/// Construct an <see cref="ServerErrorException"/>
/// </summary>
public ServerErrorException() { }
/// <summary>
/// Construct an <see cref="ServerErrorException"/> with <paramref name="html"/>
/// </summary>
/// <param name="html">The raw HTML response of the <see cref="ServerErrorException"/></param>
public ServerErrorException(string html) : base(null, HttpStatusCode.InternalServerError)
{
Html = html;
}
/// <summary>
/// Construct an <see cref="ServerErrorException"/> with a <paramref name="message"/> and <paramref name="innerException"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
/// <param name="innerException">The inner <see cref="Exception"/> for the base <see cref="Exception"/></param>
public ServerErrorException(string message, Exception innerException) : base(message, innerException) { }
}
} | agpl-3.0 | C# |
4da6788cb8799e927e7a36282e660a0fe2798867 | Fix PartialView Tree Controller to display a folder icon as opposed to an article icon for nested folders - looks odd/broken to me otherwise | JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,tompipe/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,lars-erik/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,WebCentrum/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,WebCentrum/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,tompipe/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,tompipe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,lars-erik/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,robertjf/Umbraco-CMS,lars-erik/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,WebCentrum/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arknu/Umbraco-CMS | src/Umbraco.Web/Trees/PartialViewsTreeController.cs | src/Umbraco.Web/Trees/PartialViewsTreeController.cs | using umbraco;
using Umbraco.Core.IO;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Trees
{
/// <summary>
/// Tree for displaying partial views in the settings app
/// </summary>
[Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)]
[UmbracoTreeAuthorize(Constants.Trees.PartialViews)]
[PluginController("UmbracoTrees")]
[CoreTree(TreeGroup = Constants.Trees.Groups.Templating)]
public class PartialViewsTreeController : FileSystemTreeController
{
protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem;
private static readonly string[] ExtensionsStatic = {"cshtml"};
protected override string[] Extensions => ExtensionsStatic;
protected override string FileIcon => "icon-article";
protected override void OnRenderFolderNode(ref TreeNode treeNode)
{
//TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now.
treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);";
treeNode.Icon = "icon-folder";
}
}
}
| using umbraco;
using Umbraco.Core.IO;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Trees
{
/// <summary>
/// Tree for displaying partial views in the settings app
/// </summary>
[Tree(Constants.Applications.Settings, Constants.Trees.PartialViews, null, sortOrder: 7)]
[UmbracoTreeAuthorize(Constants.Trees.PartialViews)]
[PluginController("UmbracoTrees")]
[CoreTree(TreeGroup = Constants.Trees.Groups.Templating)]
public class PartialViewsTreeController : FileSystemTreeController
{
protected override IFileSystem FileSystem => Current.FileSystems.PartialViewsFileSystem;
private static readonly string[] ExtensionsStatic = {"cshtml"};
protected override string[] Extensions => ExtensionsStatic;
protected override string FileIcon => "icon-article";
protected override void OnRenderFolderNode(ref TreeNode treeNode)
{
//TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now.
treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);";
treeNode.Icon = "icon-article";
}
}
}
| mit | C# |
2c65da58c73e364e5bfc0cb22bd548f07909e8c5 | Fix a bug | kawatan/Milk | Megalopolis/ActivationFunctions/HyperbolicTangent.cs | Megalopolis/ActivationFunctions/HyperbolicTangent.cs | using System;
namespace Megalopolis
{
namespace ActivationFunctions
{
public class HyperbolicTangent : IActivationFunction
{
public double Function(double x)
{
// (Math.Pow(Math.E, x) - Math.Pow(Math.E, -x)) / (Math.Pow(Math.E, x) + Math.Pow(Math.E, -x))
return Math.Tanh(x);
}
public double Derivative(double x)
{
var y = Math.Tanh(x);
return 1.0 - y * y;
}
}
}
}
| using System;
namespace Megalopolis
{
namespace ActivationFunctions
{
public class HyperbolicTangent : IActivationFunction
{
public double Function(double x)
{
return Math.Tanh(x);
}
public double Derivative(double x)
{
return 1.0 - x * x;
}
}
}
}
| apache-2.0 | C# |
67ba64b0a1ef49939233115098eaac09b4ec8f14 | Fix build | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Services/Cheater.cs | BTCPayServer/Services/Cheater.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
using Microsoft.Extensions.Hosting;
using NBitcoin;
using NBitcoin.RPC;
namespace BTCPayServer.Services
{
public class Cheater : IHostedService
{
private readonly ApplicationDbContextFactory _applicationDbContextFactory;
public Cheater(BTCPayServerOptions opts, ApplicationDbContextFactory applicationDbContextFactory)
{
CashCow = new RPCClient(RPCCredentialString.Parse("server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3"), Bitcoin.Instance.GetNetwork(opts.NetworkType));
_applicationDbContextFactory = applicationDbContextFactory;
}
public RPCClient CashCow
{
get;
set;
}
public async Task UpdateInvoiceExpiry(string invoiceId, DateTimeOffset dateTimeOffset)
{
using (var ctx = _applicationDbContextFactory.CreateContext())
{
var invoiceData = await ctx.Invoices.FindAsync(invoiceId).ConfigureAwait(false);
if (invoiceData == null)
return;
// TODO change the expiry time. But how?
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
}
Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
_ = CashCow.ScanRPCCapabilitiesAsync();
return Task.CompletedTask;
}
Task IHostedService.StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
using Microsoft.Extensions.Hosting;
using NBitcoin;
using NBitcoin.RPC;
namespace BTCPayServer.Services
{
public class Cheater : IHostedService
{
private readonly ApplicationDbContextFactory _applicationDbContextFactory;
public Cheater(BTCPayServerOptions opts, ApplicationDbContextFactory applicationDbContextFactory)
{
CashCow = new RPCClient(RPCCredentialString.Parse("server=http://127.0.0.1:43782;ceiwHEbqWI83:DwubwWsoo3"), Bitcoin.Instance.GetNetwork(opts.NetworkType));
_applicationDbContextFactory = applicationDbContextFactory;
}
public RPCClient CashCow
{
get;
set;
}
public async Task UpdateInvoiceExpiry(string invoiceId, DateTimeOffset dateTimeOffset)
{
using (var ctx = _applicationDbContextFactory.CreateContext())
{
var invoiceData = await ctx.Invoices.FindAsync(invoiceId).ConfigureAwait(false);
if (invoiceData == null)
return;
// TODO change the expiry time. But how?
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
}
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
await CashCow.ScanRPCCapabilitiesAsync();
}
Task IHostedService.StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
| mit | C# |
98c8b032932f626f4bca59ce6c22d7ba324d1c77 | Update Trace region comment | GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples | trace/api/Global.asax.cs | trace/api/Global.asax.cs | // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START import_client_library]
using Google.Cloud.Diagnostics.AspNet;
using Google.Cloud.Diagnostics.Common;
// [END import_client_library]
using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
namespace Trace
{
public class WebApiApplication : System.Web.HttpApplication
{
// [START configure_services_trace]
public override void Init()
{
string projectId = ConfigurationManager.AppSettings["projectId"];
// [START_EXCLUDE]
// Confirm that projectId has been changed from placeholder value.
if (projectId == ("YOUR-PROJECT-ID"))
{
throw new Exception("Update Web.config and replace "
+ "YOUR-PROJECT-ID with your project id, and recompile.");
}
// [END_EXCLUDE]
base.Init();
TraceConfiguration traceConfig = TraceConfiguration
.Create(bufferOptions: BufferOptions.NoBuffer());
CloudTrace.Initialize(this, projectId, traceConfig);
}
// [END configure_services_trace]
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
| // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START import_client_library]
using Google.Cloud.Diagnostics.AspNet;
using Google.Cloud.Diagnostics.Common;
// [END import_client_library]
using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
namespace Trace
{
public class WebApiApplication : System.Web.HttpApplication
{
// [START configure_services_trace]
public override void Init()
{
// [START_EXCLUDE]
string projectId = ConfigurationManager.AppSettings["projectId"];
// Confirm that projectId has been changed from placeholder value.
if (projectId == ("YOUR-PROJECT-ID"))
{
throw new Exception("Update Web.config and replace "
+ "YOUR-PROJECT-ID with your project id, and recompile.");
}
// [END_EXCLUDE]
base.Init();
TraceConfiguration traceConfig = TraceConfiguration
.Create(bufferOptions: BufferOptions.NoBuffer());
CloudTrace.Initialize(this, projectId, traceConfig);
}
// [END configure_services_trace]
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
| apache-2.0 | C# |
47bfc7ce5f06499a878e1887b8728d5658804c5a | Clean up using statement in test | DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,hal-ler/omnisharp-roslyn,nabychan/omnisharp-roslyn,jtbm37/omnisharp-roslyn,jtbm37/omnisharp-roslyn,nabychan/omnisharp-roslyn,hal-ler/omnisharp-roslyn | tests/OmniSharp.DotNet.Tests/ProjectSearcherTest.cs | tests/OmniSharp.DotNet.Tests/ProjectSearcherTest.cs | using System.IO;
using System.Linq;
using OmniSharp.DotNet.Projects;
using TestCommon;
using Xunit;
namespace OmniSharp.DotNet.Tests
{
public class ProjectSearcherTest
{
private readonly TestsContext _context;
public ProjectSearcherTest()
{
_context = TestsContext.Default;
}
[Theory]
[InlineData("ProjectSearchSample01", "ProjectSearchSample01")]
[InlineData("ProjectSearchSample03", "Project1")]
[InlineData("ProjectSearchSample04", "ProjectSearchSample04")]
public void SingleResultExpect(string testSampleName, string projectName)
{
var projectPath = _context.GetTestSample(testSampleName);
var project = ProjectSearcher.Search(projectPath).Single();
Assert.Equal(projectName, Path.GetFileName(project));
}
[Fact]
public void NoneProjectJson()
{
var projectPath = _context.GetTestSample("ProjectSearchSample02");
Assert.Empty(ProjectSearcher.Search(projectPath));
}
[Fact]
public void RecursivelySearch()
{
var projectPath = _context.GetTestSample("ProjectSearchSample05");
var results = ProjectSearcher.Search(projectPath);
Assert.Equal(3, results.Count());
}
[Fact]
public void GlobalJsonExpand()
{
var projectPath = _context.GetTestSample("ProjectSearchSample06");
var results = ProjectSearcher.Search(projectPath);
Assert.Equal(2, results.Count());
}
[Fact]
public void GlobalJsonFindNothing()
{
var projectPath = _context.GetTestSample("ProjectSearchSample07");
Assert.Empty(ProjectSearcher.Search(projectPath));
}
}
} | using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.ProjectModel;
using OmniSharp.DotNet.Projects;
using TestCommon;
using Xunit;
namespace OmniSharp.DotNet.Tests
{
public class ProjectSearcherTest
{
private readonly TestsContext _context;
public ProjectSearcherTest()
{
_context = TestsContext.Default;
}
[Theory]
[InlineData("ProjectSearchSample01", "ProjectSearchSample01")]
[InlineData("ProjectSearchSample03", "Project1")]
[InlineData("ProjectSearchSample04", "ProjectSearchSample04")]
public void SingleResultExpect(string testSampleName, string projectName)
{
var projectPath = _context.GetTestSample(testSampleName);
var project = ProjectSearcher.Search(projectPath).Single();
Assert.Equal(projectName, Path.GetFileName(project));
}
[Fact]
public void NoneProjectJson()
{
var projectPath = _context.GetTestSample("ProjectSearchSample02");
Assert.Empty(ProjectSearcher.Search(projectPath));
}
[Fact]
public void RecursivelySearch()
{
var projectPath = _context.GetTestSample("ProjectSearchSample05");
var results = ProjectSearcher.Search(projectPath);
Assert.Equal(3, results.Count());
}
[Fact]
public void GlobalJsonExpand()
{
var projectPath = _context.GetTestSample("ProjectSearchSample06");
var results = ProjectSearcher.Search(projectPath);
Assert.Equal(2, results.Count());
}
[Fact]
public void GlobalJsonFindNothing()
{
var projectPath = _context.GetTestSample("ProjectSearchSample07");
Assert.Empty(ProjectSearcher.Search(projectPath));
}
}
} | mit | C# |
f9c5bd7faf1a8878bc5cd7b081c45f60fd74d22b | Fix bug in IQuery interface | csf-dev/CSF.Core,csf-dev/CSF.Core | CSF/Data/IQuery.cs | CSF/Data/IQuery.cs | //
// IQuery.cs
//
// Author:
// Craig Fowler <craig@craigfowler.me.uk>
//
// Copyright (c) 2016 Craig Fowler
//
// 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.Linq;
namespace CSF.Data
{
/// <summary>
/// Interface for a query component that is capable of returning a queryable data source.
/// </summary>
public interface IQuery
{
/// <summary>
/// Creates an instance of the given object-type, based upon a theory that it exists in the underlying data-source.
/// </summary>
/// <remarks>
/// <para>
/// This method will always return a non-null object instance, even if the underlying object does not exist in the
/// data source. If a 'thoery object' is created for an object which does not actually exist, then an exception
/// could be thrown if that theory object is used.
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Theorise<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a single instance from the underlying data source, identified by an identity value.
/// </summary>
/// <remarks>
/// <para>
/// This method will either get an object instance, or it will return <c>null</c> (if no instance is found).
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Get<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a new queryable data-source.
/// </summary>
/// <typeparam name="TQueried">The type of queried-for object.</typeparam>
IQueryable<TQueried> Query<TQueried>() where TQueried : class;
}
}
| //
// IQuery.cs
//
// Author:
// Craig Fowler <craig@craigfowler.me.uk>
//
// Copyright (c) 2016 Craig Fowler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace CSF.Data
{
/// <summary>
/// Interface for a query component that is capable of returning a queryable data source.
/// </summary>
public interface IQuery
{
/// <summary>
/// Creates an instance of the given object-type, based upon a theory that it exists in the underlying data-source.
/// </summary>
/// <remarks>
/// <para>
/// This method will always return a non-null object instance, even if the underlying object does not exist in the
/// data source. If a 'thoery object' is created for an object which does not actually exist, then an exception
/// could be thrown if that theory object is used.
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Theorise<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a single instance from the underlying data source, identified by an identity value.
/// </summary>
/// <remarks>
/// <para>
/// This method will either get an object instance, or it will return <c>null</c> (if no instance is found).
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Get<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a new queryable data-source.
/// </summary>
/// <typeparam name="TQueried">The type of queried-for object.</typeparam>
TQueried Query<TQueried>() where TQueried : class;
}
}
| mit | C# |
1066cbdb923b6e9a80b4d77f0bcbf80825da7a4d | Fix TreeModel iteration to not make a reference cycle. | sillsdev/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp | gtk/TreeEnumerator.cs | gtk/TreeEnumerator.cs | // TreeEnumerator.cs - .NET-style Enumerator for TreeModel classes
//
// Author: Eric Butler <eric@extremeboredom.net>
//
// Copyright (c) 2005 Eric Butler
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.Collections;
namespace Gtk
{
internal class TreeEnumerator : IEnumerator, IDisposable
{
private Gtk.TreeIter iter;
private Gtk.TreeModel model;
private bool reset = true;
private bool changed = false;
public TreeEnumerator (TreeModel model)
{
this.model = model;
model.RowChanged += row_changed;
model.RowDeleted += row_deleted;
model.RowInserted += row_inserted;
model.RowsReordered += rows_reordered;
}
public object Current
{
get {
if (reset == false) {
object[] row = new object[model.NColumns];
for (int x = 0; x < model.NColumns; x++) {
row[x] = model.GetValue(iter, x);
}
return row;
} else {
throw new InvalidOperationException("Enumerator not started.");
}
}
}
public bool MoveNext()
{
if (changed == false) {
if (reset == true) {
reset = false;
return model.GetIterFirst(out iter);
} else {
return model.IterNext(ref iter);
}
} else {
throw new InvalidOperationException("List has changed.");
}
}
public void Reset()
{
reset = true;
changed = false;
}
private void row_changed(object o, RowChangedArgs args)
{
changed = true;
}
private void row_deleted(object o, RowDeletedArgs args)
{
changed = true;
}
private void row_inserted(object o, RowInsertedArgs args)
{
changed = true;
}
private void rows_reordered(object o, RowsReorderedArgs args)
{
changed = true;
}
public void Dispose ()
{
model.RowChanged -= row_changed;
model.RowDeleted -= row_deleted;
model.RowInserted -= row_inserted;
model.RowsReordered -= rows_reordered;
model = null;
}
}
}
| // TreeEnumerator.cs - .NET-style Enumerator for TreeModel classes
//
// Author: Eric Butler <eric@extremeboredom.net>
//
// Copyright (c) 2005 Eric Butler
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.Collections;
namespace Gtk
{
internal class TreeEnumerator : IEnumerator
{
private Gtk.TreeIter iter;
private Gtk.TreeModel model;
private bool reset = true;
private bool changed = false;
public TreeEnumerator (TreeModel model)
{
this.model = model;
model.RowChanged += new RowChangedHandler (row_changed);
model.RowDeleted += new RowDeletedHandler (row_deleted);
model.RowInserted += new RowInsertedHandler (row_inserted);
model.RowsReordered += new RowsReorderedHandler (rows_reordered);
}
public object Current
{
get {
if (reset == false) {
object[] row = new object[model.NColumns];
for (int x = 0; x < model.NColumns; x++) {
row[x] = model.GetValue(iter, x);
}
return row;
} else {
throw new InvalidOperationException("Enumerator not started.");
}
}
}
public bool MoveNext()
{
if (changed == false) {
if (reset == true) {
reset = false;
return model.GetIterFirst(out iter);
} else {
return model.IterNext(ref iter);
}
} else {
throw new InvalidOperationException("List has changed.");
}
}
public void Reset()
{
reset = true;
changed = false;
}
private void row_changed(object o, RowChangedArgs args)
{
changed = true;
}
private void row_deleted(object o, RowDeletedArgs args)
{
changed = true;
}
private void row_inserted(object o, RowInsertedArgs args)
{
changed = true;
}
private void rows_reordered(object o, RowsReorderedArgs args)
{
changed = true;
}
}
}
| lgpl-2.1 | C# |
4343695a60aa56733bdfa215599b97b33b65c998 | add greeting scenario supported | adipatl/ken,adipatl/ken,adipatl/ken | KenBot/Ai/KenAi.cs | KenBot/Ai/KenAi.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
namespace Ken
{
[LuisModel("829ee634-ba62-4240-baf7-70a66163ab01", "d018c3a25fcc49889b863595ceef2ffd")]
[Serializable]
public class KenAi : LuisDialog<object>
{
public const string EntityStockSymbol = "StockSymbol";
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{
string message = $"Sorry I did not understand: " + string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("Greeting")]
public async Task GetStockPrice(IDialogContext context, LuisResult result)
{
EntityRecommendation symbol;
await context.PostAsync($"Hi There");
context.Wait(MessageReceived);
}
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
namespace Ken
{
[LuisModel("829ee634-ba62-4240-baf7-70a66163ab01", "d018c3a25fcc49889b863595ceef2ffd")]
[Serializable]
public class KenAi : LuisDialog<object>
{
public const string EntityStockSymbol = "StockSymbol";
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{
string message = $"Sorry I did not understand: " + string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("StockPrice")]
public async Task GetStockPrice(IDialogContext context, LuisResult result)
{
EntityRecommendation symbol;
if (result.TryFindEntity(EntityStockSymbol, out symbol))
{
await context.PostAsync($"found symbol {symbol.Entity}");
}
else
{
await context.PostAsync("did not find symbol");
}
context.Wait(MessageReceived);
}
}
} | mit | C# |
882bdcab7ad78ca48cdcd240926bc8c21a3a36d7 | Revert "更新版本1.8.6.5" | tsanie/ElectronicObserver,CNA-Bld/ElectronicObserver,herix001/ElectronicObserver,kanonmelodis/ElectronicObserver | ElectronicObserver/Properties/AssemblyInfo.cs | ElectronicObserver/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle( "ElectronicObserver" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "ElectronicObserver" )]
[assembly: AssemblyCopyright( "Copyright © 2014 Andante" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible( false )]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid( "bee10a07-cace-44fe-8a74-53ae44d224c2" )]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.8.0.0")]
[assembly: AssemblyFileVersion("1.8.6.0")]
[assembly: AssemblyInformationalVersion("1.8.6.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle( "ElectronicObserver" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "ElectronicObserver" )]
[assembly: AssemblyCopyright( "Copyright © 2014 Andante" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible( false )]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid( "bee10a07-cace-44fe-8a74-53ae44d224c2" )]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.8.0.5")]
[assembly: AssemblyFileVersion("1.8.6.5")]
[assembly: AssemblyInformationalVersion("1.8.6.5")] | mit | C# |
d393507d3ebc7d7780235d9920121f2e3de9f661 | Refactor LoginAuthCommand to use AutoCommandData | appharbor/appharbor-cli | src/AppHarbor.Tests/Commands/LoginAuthCommandTest.cs | src/AppHarbor.Tests/Commands/LoginAuthCommandTest.cs | using System;
using System.IO;
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class LoginAuthCommandTest
{
[Theory, AutoCommandData]
public void ShouldSetAppHarborTokenIfUserIsntLoggedIn(string username, string password, [Frozen]Mock<TextWriter> writer, [Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock, Mock<LoginAuthCommand> loginCommand)
{
using (var reader = new StringReader(string.Format("{0}{2}{1}{2}", username, password, Environment.NewLine)))
{
Console.SetIn(reader);
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns((string)null);
loginCommand.Setup(x => x.GetAccessToken(username, password)).Returns("foo");
loginCommand.Object.Execute(new string[] { });
writer.Verify(x => x.Write("Username: "), Times.Once());
writer.Verify(x => x.Write("Password: "), Times.Once());
writer.Verify(x => x.WriteLine("Successfully logged in as {0}", username), Times.Once());
accessTokenConfigurationMock.Verify(x => x.SetAccessToken("foo"), Times.Once());
}
}
[Theory, AutoCommandData]
public void ShouldThrowIfUserIsAlreadyLoggedIn([Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock, LoginAuthCommand loginCommand)
{
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns("foo");
var exception = Assert.Throws<CommandException>(() => loginCommand.Execute(new string[] { }));
Assert.Equal("You're already logged in", exception.Message);
}
}
}
| using System;
using System.IO;
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class LoginAuthCommandTest
{
[Theory, AutoData]
public void ShouldSetAppHarborTokenIfUserIsntLoggedIn(string username, string password, [Frozen]Mock<TextWriter> writer, [Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock)
{
using (var reader = new StringReader(string.Format("{0}{2}{1}{2}", username, password, Environment.NewLine)))
{
Console.SetIn(reader);
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns((string)null);
var loginCommand = new Mock<LoginAuthCommand>(accessTokenConfigurationMock.Object, writer.Object);
loginCommand.Setup(x => x.GetAccessToken(username, password)).Returns("foo");
loginCommand.Object.Execute(new string[] { });
writer.Verify(x => x.Write("Username: "), Times.Once());
writer.Verify(x => x.Write("Password: "), Times.Once());
writer.Verify(x => x.WriteLine("Successfully logged in as {0}", username), Times.Once());
accessTokenConfigurationMock.Verify(x => x.SetAccessToken("foo"), Times.Once());
}
}
[Theory, AutoData]
public void ShouldThrowIfUserIsAlreadyLoggedIn([Frozen]Mock<TextWriter> writer, [Frozen]Mock<AccessTokenConfiguration> accessTokenConfigurationMock)
{
accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns("foo");
var loginCommand = new LoginAuthCommand(accessTokenConfigurationMock.Object, writer.Object);
var exception = Assert.Throws<CommandException>(() => loginCommand.Execute(new string[] { }));
Assert.Equal("You're already logged in", exception.Message);
}
}
}
| mit | C# |
10b921c658796f9e2d838d73036ea6d4cfc24035 | Add Dictionary.AddPair overload | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Utilities/Collections/Dictionary.AddKeyValue.cs | source/Nuke.Common/Utilities/Collections/Dictionary.AddKeyValue.cs | // Copyright 2021 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 JetBrains.Annotations;
namespace Nuke.Common.Utilities.Collections
{
public static partial class DictionaryExtensions
{
public static IDictionary<TKey, TValue> AddPair<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
[CanBeNull] TValue value = default)
{
dictionary.Add(key, value);
return dictionary;
}
public static IDictionary<TKey, string> AddPair<TKey, TValue>(
this IDictionary<TKey, string> dictionary,
TKey key,
[CanBeNull] TValue value = default)
{
dictionary.Add(key, value.ToString());
return dictionary;
}
public static IDictionary<TKey, TValue> AddPairWhenKeyNotNull<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
[CanBeNull] TKey key,
[CanBeNull] TValue value = default)
where TKey : class
{
return key != null
? dictionary.AddPair(key, value)
: dictionary;
}
public static IDictionary<TKey, TValue> AddPairWhenValueNotNull<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
[CanBeNull] TKey key,
[CanBeNull] TValue value)
where TValue : class
{
return value != null
? dictionary.AddPair(key, value)
: dictionary;
}
}
}
| // Copyright 2021 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 JetBrains.Annotations;
namespace Nuke.Common.Utilities.Collections
{
public static partial class DictionaryExtensions
{
public static IDictionary<TKey, TValue> AddPair<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
[CanBeNull] TValue value = default)
{
dictionary.Add(key, value);
return dictionary;
}
public static IDictionary<TKey, TValue> AddPairWhenKeyNotNull<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
[CanBeNull] TKey key,
[CanBeNull] TValue value = default)
where TKey : class
{
return key != null
? dictionary.AddPair(key, value)
: dictionary;
}
public static IDictionary<TKey, TValue> AddPairWhenValueNotNull<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
[CanBeNull] TKey key,
[CanBeNull] TValue value)
where TValue : class
{
return value != null
? dictionary.AddPair(key, value)
: dictionary;
}
}
}
| mit | C# |
5a4b3223c5ee5d33a2df89850962aacc1321bbd3 | Fix the way the current directory is retrieved (#47) | mgrosperrin/commandlineparser | src/MGR.CommandLineParser/Extensibility/AssemblyProviderBase.cs | src/MGR.CommandLineParser/Extensibility/AssemblyProviderBase.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
namespace MGR.CommandLineParser.Extensibility
{
/// <summary>
/// Base class for providing all files (*.dll and *.exe) in the current folder (recursive or not).
/// </summary>
public abstract class AssemblyProviderBase : IAssemblyProvider
{
/// <summary>
/// Gets the recursivity options for browsing the current folder.
/// </summary>
protected abstract SearchOption SearchOption { get; }
/// <inheritdoc />
private IEnumerable<string> GetFilesToLoad()
{
var thisDirectory = Environment.CurrentDirectory;
foreach (var item in Directory.EnumerateFiles(thisDirectory, "*.exe", SearchOption))
{
yield return new FileInfo(item).FullName;
}
foreach (var item in Directory.EnumerateFiles(thisDirectory, "*.dll", SearchOption))
{
yield return new FileInfo(item).FullName;
}
}
/// <inheritdoc />
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods",
MessageId = "System.Reflection.Assembly.LoadFrom")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public IEnumerable<Assembly> GetAssembliesToBrowse()
{
foreach (var assemblyFile in GetFilesToLoad())
{
try
{
Assembly.LoadFrom(assemblyFile);
}
#pragma warning disable CC0004 // Catch block cannot be empty
// ReSharper disable once EmptyGeneralCatchClause
catch
#pragma warning restore CC0004 // Catch block cannot be empty
{
}
}
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
return assemblies;
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
namespace MGR.CommandLineParser.Extensibility
{
/// <summary>
/// Base class for providing all files (*.dll and *.exe) in the current folder (recursive or not).
/// </summary>
public abstract class AssemblyProviderBase : IAssemblyProvider
{
/// <summary>
/// Gets the recursivity options for browsing the current folder.
/// </summary>
protected abstract SearchOption SearchOption { get; }
/// <inheritdoc />
private IEnumerable<string> GetFilesToLoad()
{
var directory = Path.GetDirectoryName(typeof (AssemblyProviderBase).Assembly.CodeBase);
if (!string.IsNullOrEmpty(directory))
{
var thisDirectory = new Uri(directory).AbsolutePath;
foreach (var item in Directory.EnumerateFiles(thisDirectory, "*.exe", SearchOption))
{
yield return new FileInfo(item).FullName;
}
foreach (var item in Directory.EnumerateFiles(thisDirectory, "*.dll", SearchOption))
{
yield return new FileInfo(item).FullName;
}
}
}
/// <inheritdoc />
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods",
MessageId = "System.Reflection.Assembly.LoadFrom")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public IEnumerable<Assembly> GetAssembliesToBrowse()
{
foreach (var assemblyFile in GetFilesToLoad())
{
try
{
Assembly.LoadFrom(assemblyFile);
}
#pragma warning disable CC0004 // Catch block cannot be empty
// ReSharper disable once EmptyGeneralCatchClause
catch
#pragma warning restore CC0004 // Catch block cannot be empty
{
}
}
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
return assemblies;
}
}
} | mit | C# |
5d2798fa9a57bb1f1a00618fd7bf3e6ba0bd9040 | Add failing test steps | smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework | osu.Framework.Tests/Visual/UserInterface/TestSceneColourPicker.cs | osu.Framework.Tests/Visual/UserInterface/TestSceneColourPicker.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.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneColourPicker : FrameworkTestScene
{
[SetUpSteps]
public void SetUpSteps()
{
ColourPicker colourPicker = null;
AddStep("create picker", () => Child = colourPicker = new BasicColourPicker());
AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.Goldenrod);
AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod);
}
}
}
| // 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.Graphics.UserInterface;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneColourPicker : FrameworkTestScene
{
[SetUpSteps]
public void SetUpSteps()
{
ColourPicker colourPicker = null;
AddStep("create picker", () => Child = colourPicker = new BasicColourPicker());
AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.CornflowerBlue);
}
}
}
| mit | C# |
49fdae9c4622de67bcff548b52775785df518810 | Update OnGUI menu | IanEarnest/Unity-GUI | Assets/OnGUI/OnGUIMenu.cs | Assets/OnGUI/OnGUIMenu.cs | using UnityEngine;
using System.Collections;
public class OnGUIMenu : MonoBehaviour {
public static int menuSelect = 3;
Rect guiRect = new Rect(Screen.width-100, Screen.height/2-75, 100, 150);
void OnGUI(){
GUILayout.BeginArea (guiRect);
GUILayout.Label ("OnGUI Select");
if(GUILayout.Button("First menus")){
menuSelect = 1;
}
if(GUILayout.Button("Custom menus")){
menuSelect = 2;
}
if(GUILayout.Button("Color Slider")){
menuSelect = 3;
}
GUILayout.EndArea ();
}
}
| using UnityEngine;
using System.Collections;
public class OnGUIMenu : MonoBehaviour {
Rect guiRect = new Rect(Screen.width-100, Screen.height/2-75, 100, 150);
void OnGUI(){
GUILayout.BeginArea (guiRect);
GUILayout.Label ("OnGUI Select");
if(GUILayout.Button("First menus")){
}
if(GUILayout.Button("Custom menus")){
}
GUILayout.EndArea ();
}
}
| mit | C# |
4eb7fbea23840344db330340461aeeeeda42f697 | Mark IPublisher<> descriptor as overrider | Elders/Cronus.Transport.RabbitMQ,Elders/Cronus.Transport.RabbitMQ | src/Elders.Cronus.Transport.RabbitMQ/RabbitMqPublisherDiscovery.cs | src/Elders.Cronus.Transport.RabbitMQ/RabbitMqPublisherDiscovery.cs | using System.Collections.Generic;
using Elders.Cronus.Discoveries;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
namespace Elders.Cronus.Transport.RabbitMQ
{
public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>>
{
protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context)
{
return new DiscoveryResult<IPublisher<IMessage>>(GetModels());
}
IEnumerable<DiscoveredModel> GetModels()
{
yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton);
yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton);
var publisherModel = new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton);
publisherModel.CanOverrideDefaults = true;
yield return publisherModel;
}
}
}
| using System.Collections.Generic;
using Elders.Cronus.Discoveries;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
namespace Elders.Cronus.Transport.RabbitMQ
{
public class RabbitMqPublisherDiscovery : DiscoveryBasedOnExecutingDirAssemblies<IPublisher<IMessage>>
{
protected override DiscoveryResult<IPublisher<IMessage>> DiscoverFromAssemblies(DiscoveryContext context)
{
return new DiscoveryResult<IPublisher<IMessage>>(GetModels());
}
IEnumerable<DiscoveredModel> GetModels()
{
yield return new DiscoveredModel(typeof(RabbitMqSettings), typeof(RabbitMqSettings), ServiceLifetime.Singleton);
yield return new DiscoveredModel(typeof(IConnectionFactory), typeof(RabbitMqConnectionFactory), ServiceLifetime.Singleton);
yield return new DiscoveredModel(typeof(IPublisher<>), typeof(RabbitMqPublisher<>), ServiceLifetime.Singleton);
}
}
}
| apache-2.0 | C# |
39c1468b0ab58eac7876bf3b52c68b3c530e4a57 | Write JSON as prettified string to file for better readability. | n-develop/tickettimer | TicketTimer.Core/Infrastructure/JsonWorkItemStore.cs | TicketTimer.Core/Infrastructure/JsonWorkItemStore.cs | using Newtonsoft.Json;
namespace TicketTimer.Core.Infrastructure
{
public class JsonWorkItemStore : WorkItemStore
{
private readonly FileStore _fileStore;
private const string FileName = "timer.state";
private TimerState _state;
public JsonWorkItemStore(FileStore fileStore)
{
_fileStore = fileStore;
Load();
}
public void AddToArchive(WorkItem workItem)
{
GetState().WorkItemArchive.Add(workItem);
Save();
}
public TimerState GetState()
{
if (_state == null)
{
Load();
}
return _state;
}
public void Save()
{
var json = JsonConvert.SerializeObject(_state, Formatting.Indented);
_fileStore.WriteFile(json, FileName);
}
private void Load()
{
var json = _fileStore.ReadFile(FileName);
if (!string.IsNullOrEmpty(json))
{
_state = JsonConvert.DeserializeObject<TimerState>(json);
}
else
{
_state = new TimerState();
}
}
public void SetCurrent(WorkItem workItem)
{
GetState().CurrentWorkItem = workItem;
Save();
}
public void ClearArchive()
{
GetState().WorkItemArchive.Clear();
Save();
}
}
}
| using Newtonsoft.Json;
namespace TicketTimer.Core.Infrastructure
{
public class JsonWorkItemStore : WorkItemStore
{
private readonly FileStore _fileStore;
private const string FileName = "timer.state";
private TimerState _state;
public JsonWorkItemStore(FileStore fileStore)
{
_fileStore = fileStore;
Load();
}
public void AddToArchive(WorkItem workItem)
{
GetState().WorkItemArchive.Add(workItem);
Save();
}
public TimerState GetState()
{
if (_state == null)
{
Load();
}
return _state;
}
public void Save()
{
var json = JsonConvert.SerializeObject(_state);
_fileStore.WriteFile(json, FileName);
}
private void Load()
{
var json = _fileStore.ReadFile(FileName);
if (!string.IsNullOrEmpty(json))
{
_state = JsonConvert.DeserializeObject<TimerState>(json);
}
else
{
_state = new TimerState();
}
}
public void SetCurrent(WorkItem workItem)
{
GetState().CurrentWorkItem = workItem;
Save();
}
public void ClearArchive()
{
GetState().WorkItemArchive.Clear();
Save();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.