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 |
|---|---|---|---|---|---|---|---|---|
23091ff4ffc8cbc3b53853912a8735c1faf94f5b | Fix issue when adding type to ExtensionsProvider | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/DotVVM.Framework/Compilation/Binding/DefaultExtensionsProvider.cs | src/DotVVM.Framework/Compilation/Binding/DefaultExtensionsProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DotVVM.Framework.Compilation.Binding
{
public class DefaultExtensionsProvider : IExtensionsProvider
{
private readonly List<Type> typesLookup;
public DefaultExtensionsProvider()
{
typesLookup = new List<Type>();
AddTypeForExtensionsLookup(typeof(Enumerable));
}
protected void AddTypeForExtensionsLookup(Type type)
{
typesLookup.Add(type);
}
public virtual IEnumerable<MethodInfo> GetExtensionMethods()
{
foreach (var registeredType in typesLookup)
foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static))
yield return method;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DotVVM.Framework.Compilation.Binding
{
public class DefaultExtensionsProvider : IExtensionsProvider
{
private readonly List<Type> typesLookup;
public DefaultExtensionsProvider()
{
typesLookup = new List<Type>();
AddTypeForExtensionsLookup(typeof(Enumerable));
}
protected void AddTypeForExtensionsLookup(Type type)
{
typesLookup.Add(typeof(Enumerable));
}
public virtual IEnumerable<MethodInfo> GetExtensionMethods()
{
foreach (var registeredType in typesLookup)
foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static))
yield return method;
}
}
}
| apache-2.0 | C# |
0d72bdd83a4c85064bc0adef8d0f331076c6313e | Support for Microsoft.Data.Sqlite | igitur/fluentmigrator,fluentmigrator/fluentmigrator,eloekset/fluentmigrator,igitur/fluentmigrator,amroel/fluentmigrator,stsrki/fluentmigrator,amroel/fluentmigrator,spaccabit/fluentmigrator,fluentmigrator/fluentmigrator,schambers/fluentmigrator,schambers/fluentmigrator,stsrki/fluentmigrator,eloekset/fluentmigrator,spaccabit/fluentmigrator | src/FluentMigrator.Runner.SQLite/Processors/SQLite/SQLiteDbFactory.cs | src/FluentMigrator.Runner.SQLite/Processors/SQLite/SQLiteDbFactory.cs | namespace FluentMigrator.Runner.Processors.SQLite
{
public class SQLiteDbFactory : ReflectionBasedDbFactory
{
private static readonly TestEntry[] _testEntries =
{
new TestEntry("System.Data.SQLite", "System.Data.SQLite.SQLiteFactory"),
new TestEntry("Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756", "Mono.Data.Sqlite.SqliteFactory"),
new TestEntry("Microsoft.Data.Sqlite", "Microsoft.Data.Sqlite.SqliteFactory"),
};
public SQLiteDbFactory()
: base(_testEntries)
{
}
}
}
| using System;
namespace FluentMigrator.Runner.Processors.SQLite
{
public class SQLiteDbFactory : ReflectionBasedDbFactory
{
public SQLiteDbFactory()
: base(DefaultAssemblyName, DefaultFactoryClassName)
{
}
private static string DefaultAssemblyName
{
get
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
return "Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";
return "System.Data.SQLite";
}
}
private static string DefaultFactoryClassName
{
get
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
return "Mono.Data.Sqlite.SqliteFactory";
return "System.Data.SQLite.SQLiteFactory";
}
}
}
}
| apache-2.0 | C# |
a05c5ce715322dc9807b46ab5ebd0ddac0b18126 | put some content in order successful view | lderache/LeTruck,lderache/LeTruck,lderache/LeTruck | src/mvc5/TheTruck.Web/Views/Orders/OrderSuccessful.cshtml | src/mvc5/TheTruck.Web/Views/Orders/OrderSuccessful.cshtml |
<h2>Order successfull!</h2>
<p>Your order has been received and will be processed for the coming week-end!</p>
<p>If you have any question do not hesitate to <a href="/Home/Contact">contact us</a></p> |
<h2>Order successfull!</h2> | mit | C# |
df5a781b1e31473f4baa8c558edc74172b0d1755 | Stop exception when no argument sare suppplied to minigzip | McNeight/SharpZipLib | samples/cs/minigzip/Main.cs | samples/cs/minigzip/Main.cs | // project created on 11.11.2001 at 15:19
using System;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;
class MainClass
{
public static void Main(string[] args)
{
if ( args.Length > 0 ) {
if ( args[0] == "-d" ) { // decompress
Stream s = new GZipInputStream(File.OpenRead(args[1]));
FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1]));
int size = 2048;
byte[] writeData = new byte[2048];
while (true) {
size = s.Read(writeData, 0, size);
if (size > 0) {
fs.Write(writeData, 0, size);
} else {
break;
}
}
s.Close();
} else { // compress
Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"));
FileStream fs = File.OpenRead(args[0]);
byte[] writeData = new byte[fs.Length];
fs.Read(writeData, 0, (int)fs.Length);
s.Write(writeData, 0, writeData.Length);
s.Close();
}
}
}
}
| // project created on 11.11.2001 at 15:19
using System;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;
class MainClass
{
public static void Main(string[] args)
{
if (args[0] == "-d") { // decompress
Stream s = new GZipInputStream(File.OpenRead(args[1]));
FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1]));
int size = 2048;
byte[] writeData = new byte[2048];
while (true) {
size = s.Read(writeData, 0, size);
if (size > 0) {
fs.Write(writeData, 0, size);
} else {
break;
}
}
s.Close();
} else { // compress
Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"));
FileStream fs = File.OpenRead(args[0]);
byte[] writeData = new byte[fs.Length];
fs.Read(writeData, 0, (int)fs.Length);
s.Write(writeData, 0, writeData.Length);
s.Close();
}
}
}
| mit | C# |
7fdd98a7a2f237e8ac9082ed65a495e40afafadc | Use HostName in Node instead of IpAddress | Teleopti/Stardust | Node/Node/NodeConfiguration.cs | Node/Node/NodeConfiguration.cs | using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
namespace Stardust.Node
{
public class NodeConfiguration
{
public NodeConfiguration(Uri managerLocation, Assembly handlerAssembly, int port, string nodeName, int pingToManagerSeconds, int sendDetailsToManagerMilliSeconds)
{
BaseAddress = CreateNodeAddress(port);
ManagerLocation = managerLocation;
HandlerAssembly = handlerAssembly;
NodeName = nodeName;
PingToManagerSeconds = pingToManagerSeconds;
SendDetailsToManagerMilliSeconds = sendDetailsToManagerMilliSeconds;
ValidateParameters();
}
public Uri BaseAddress { get; }
public Uri ManagerLocation { get; }
public string NodeName { get; }
public Assembly HandlerAssembly { get; }
public double PingToManagerSeconds { get; }
public double SendDetailsToManagerMilliSeconds { get; }
private void ValidateParameters()
{
if (ManagerLocation == null)
{
throw new ArgumentNullException(nameof(ManagerLocation));
}
if (HandlerAssembly == null)
{
throw new ArgumentNullException(nameof(HandlerAssembly));
}
if (PingToManagerSeconds <= 0)
{
throw new ArgumentNullException(nameof(PingToManagerSeconds));
}
}
private static string GetHostName()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return host.HostName;
}
private Uri CreateNodeAddress(int port)
{
if (port <= 0)
{
throw new ArgumentNullException(nameof(port));
}
return new Uri("http://" + GetHostName() + ":" + port + "/");
}
}
} | using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
namespace Stardust.Node
{
public class NodeConfiguration
{
public NodeConfiguration(Uri managerLocation, Assembly handlerAssembly, int port, string nodeName, int pingToManagerSeconds, int sendDetailsToManagerMilliSeconds)
{
BaseAddress = CreateNodeAddress(port);
ManagerLocation = managerLocation;
HandlerAssembly = handlerAssembly;
NodeName = nodeName;
PingToManagerSeconds = pingToManagerSeconds;
SendDetailsToManagerMilliSeconds = sendDetailsToManagerMilliSeconds;
ValidateParameters();
}
public Uri BaseAddress { get; }
public Uri ManagerLocation { get; }
public string NodeName { get; }
public Assembly HandlerAssembly { get; }
public double PingToManagerSeconds { get; }
public double SendDetailsToManagerMilliSeconds { get; }
private void ValidateParameters()
{
if (ManagerLocation == null)
{
throw new ArgumentNullException(nameof(ManagerLocation));
}
if (HandlerAssembly == null)
{
throw new ArgumentNullException(nameof(HandlerAssembly));
}
if (PingToManagerSeconds <= 0)
{
throw new ArgumentNullException(nameof(PingToManagerSeconds));
}
}
private static string GetIpAddress()
{
var localIp = "?";
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIp = ip.ToString();
}
}
return localIp;
}
private Uri CreateNodeAddress(int port)
{
if (port <= 0)
{
throw new ArgumentNullException(nameof(port));
}
return new Uri("http://" + GetIpAddress() + ":" + port + "/");
}
}
} | mit | C# |
1cea040c48466d64f5e637202df3cbb051d692ab | Remove assembly load debug lines. | icedream/citizenmp-server-updater | src/wrapper/Program.cs | src/wrapper/Program.cs | using System;
using System.IO;
using System.Reflection;
// ReSharper disable once CheckNamespace
internal static class Program
{
private static int Main(string[] args)
{
var mainAsm = Assembly.Load("citizenmp_server_updater");
mainAsm.GetType("Costura.AssemblyLoader")
.GetMethod("Attach")
.Invoke(null, null);
return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program")
.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
.Invoke(null, new object[] {args});
}
} | using System;
using System.IO;
using System.Reflection;
// ReSharper disable once CheckNamespace
internal static class Program
{
private static int Main(string[] args)
{
// Mono's XBuild uses assembly redirects to make sure it uses .NET 4.5 target binaries.
// We emulate it using our own assembly redirector.
AppDomain.CurrentDomain.AssemblyLoad += (sender, e) =>
{
var assemblyName = e.LoadedAssembly.GetName();
Console.WriteLine("Assembly load: {0}", assemblyName);
};
var mainAsm = Assembly.Load("citizenmp_server_updater");
mainAsm.GetType("Costura.AssemblyLoader")
.GetMethod("Attach")
.Invoke(null, null);
return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program")
.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
.Invoke(null, new object[] {args});
}
} | mit | C# |
52f6524c5b5f7207246846bebff2076d279723c1 | Clean usings | OShop/OShop.PayPal,OShop/OShop.PayPal | Services/IPaypalSettingsService.cs | Services/IPaypalSettingsService.cs | using Orchard;
using OShop.PayPal.Models;
namespace OShop.PayPal.Services {
public interface IPaypalSettingsService : IDependency {
PaypalSettings GetSettings();
void SetSettings(PaypalSettings Settings);
}
}
| using Orchard;
using OShop.PayPal.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OShop.PayPal.Services {
public interface IPaypalSettingsService : IDependency {
PaypalSettings GetSettings();
void SetSettings(PaypalSettings Settings);
}
}
| mit | C# |
1247e8053ff624e39a75337b9f3f630be85c3eef | Update Program.cs | sfederella/connect-4-ai | programs/player/Program.cs | programs/player/Program.cs | using connect_4_ai.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace connect_4_ai
{
class Program
{
/* ---- Parameters ---- */
// Board: Complete with 1 or -1 (player 1 always starts)
static Board board = new Board(new int[,] {
{ 0, 0, 0, 0, 0, 0 }, //1
{ 0, 0, 0, 0, 0, 0 }, //2
{ 0, 0, 0, 0, 0, 0 }, //3
{ 0, 0, 0, 0, 0, 0 }, //4
{ 0, 0, 0, 0, 0, 0 }, //5
{ 0, 0, 0, 0, 0, 0 }, //6
{ 0, 0, 0, 0, 0, 0 } //7
});
// Number of games that will be played
static int numGames = 1000;
// Path of the CSV file where the results will be saved
static string datasetPath = "C:/Users/Santi/UTN/Inteligecia Artificial/connect-4-ai/Datasets/dataset1000555.csv";
/* ---- Program ---- */
static void Main(string[] args)
{
Player player1 = new RandomAlgoritmicPlayer(6, datasetPath, 0.25);
Player player2 = new RandomAlgoritmicPlayer(6, datasetPath, 0.25);
Players players = new Players(player1, player2);
Game game = new Game(board, players);
Console.WriteLine(board.getStringBoard());
Console.Write("Partidas: " + numGames + " \nPresione una tecla para continuar...");
Console.ReadKey();
game.play(numGames);
Console.Write("Juego finalizado. Presione una tecla para continuar...");
Console.ReadKey();
}
}
}
| using connect_4_ai.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace connect_4_ai
{
class Program
{
/* ---- Parameters ---- */
// Board: Complete with 1 or -1 (player 1 always starts)
static Board board = new Board(new int[,] {
{ 0, 0, 0, 0, 0, 0 }, //1
{ 0, 0, 0, 0, 0, 0 }, //2
{ 0, 0, 0, 0, 0, 0 }, //3
{ 0, 0, 0, 0, 0, 0 }, //4
{ 0, 0, 0, 0, 0, 0 }, //5
{ 0, 0, 0, 0, 0, 0 }, //6
{ 0, 0, 0, 0, 0, 0 } //7
});
// Number of games that will be played
static int numGames = 1000;
// Path of the CSV file where the results will be saved
static string datasetPath = "C:/Users/Santi/UTN/Inteligecia Artificial/connect-4-ai/Datasets/dataset1000555.csv";
/* ---- Program ---- */
static void Main(string[] args)
{
Player player1 = new StupidAlgoritmicPlayer(6, datasetPath, 0.25);
Player player2 = new StupidAlgoritmicPlayer(6, datasetPath, 0.25);
Players players = new Players(player1, player2);
Game game = new Game(board, players);
Console.WriteLine(board.getStringBoard());
Console.Write("Partidas: " + numGames + " \nPresione una tecla para continuar...");
Console.ReadKey();
game.play(numGames);
Console.Write("Juego finalizado. Presione una tecla para continuar...");
Console.ReadKey();
}
}
}
| apache-2.0 | C# |
272aec4235237b3811c6a40387365c452502eaa4 | Swap BoundUnaryExpression.Result and Expression | terrajobst/nquery-vnext | src/NQuery/Binding/BoundUnaryExpression.cs | src/NQuery/Binding/BoundUnaryExpression.cs | using System;
using System.Linq;
namespace NQuery.Binding
{
internal sealed class BoundUnaryExpression : BoundExpression
{
private readonly OverloadResolutionResult<UnaryOperatorSignature> _result;
private readonly BoundExpression _expression;
public BoundUnaryExpression(OverloadResolutionResult<UnaryOperatorSignature> result, BoundExpression expression)
{
_expression = expression;
_result = result;
}
public override BoundNodeKind Kind
{
get { return BoundNodeKind.UnaryExpression; }
}
public override Type Type
{
get
{
return _result.Selected == null
? TypeFacts.Unknown
: _result.Selected.Signature.ReturnType;
}
}
public OverloadResolutionResult<UnaryOperatorSignature> Result
{
get { return _result; }
}
public BoundExpression Expression
{
get { return _expression; }
}
public BoundUnaryExpression Update(OverloadResolutionResult<UnaryOperatorSignature> result, BoundExpression expression)
{
if (result == _result && expression == _expression)
return this;
return new BoundUnaryExpression(result, expression);
}
public override string ToString()
{
var unaryOperatorKind = _result.Candidates.First().Signature.Kind;
return $"{unaryOperatorKind.ToDisplayName()}({_expression})";
}
}
} | using System;
using System.Linq;
namespace NQuery.Binding
{
internal sealed class BoundUnaryExpression : BoundExpression
{
private readonly BoundExpression _expression;
private readonly OverloadResolutionResult<UnaryOperatorSignature> _result;
public BoundUnaryExpression(BoundExpression expression, OverloadResolutionResult<UnaryOperatorSignature> result)
{
_expression = expression;
_result = result;
}
public override BoundNodeKind Kind
{
get { return BoundNodeKind.UnaryExpression; }
}
public override Type Type
{
get
{
return _result.Selected == null
? TypeFacts.Unknown
: _result.Selected.Signature.ReturnType;
}
}
public BoundExpression Expression
{
get { return _expression; }
}
public OverloadResolutionResult<UnaryOperatorSignature> Result
{
get { return _result; }
}
public BoundUnaryExpression Update(BoundExpression expression, OverloadResolutionResult<UnaryOperatorSignature> result)
{
if (expression == _expression && result == _result)
return this;
return new BoundUnaryExpression(expression, result);
}
public override string ToString()
{
var unaryOperatorKind = _result.Candidates.First().Signature.Kind;
return $"{unaryOperatorKind.ToDisplayName()}({_expression})";
}
}
} | mit | C# |
89b8ed0269244fa96c8972bbdb313681a2eca96b | Remove unused actions | peterblazejewicz/AspNet5Watcher,peterblazejewicz/AspNet5Watcher | Controllers/HomeController.cs | Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace AspNet5Watcher.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
return View("~/Views/Shared/Error.cshtml");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace AspNet5Watcher.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View("~/Views/Shared/Error.cshtml");
}
}
}
| mit | C# |
b3ff0a89d24794f2929ead218227c345ec664f46 | Bump version | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/Properties/AssemblyInfo.cs | src/SyncTrayzor/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("SyncTrayzor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SyncTrayzor")]
[assembly: AssemblyCopyright("Copyright © Antony Male 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)]
//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.5.0")]
[assembly: AssemblyFileVersion("1.0.5.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("SyncTrayzor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SyncTrayzor")]
[assembly: AssemblyCopyright("Copyright © Antony Male 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)]
//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.4.0")]
[assembly: AssemblyFileVersion("1.0.4.0")]
| mit | C# |
ef220c14cdef4e4844b041795863bab7d76a1fef | Test if a failed test will fail the build | plzb0ss/Saurus-Othello | SaurusConsole.Tests/MoveTests.cs | SaurusConsole.Tests/MoveTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using SaurusConsole.OthelloAI;
namespace SaurusConsoleTests
{
[TestClass]
public class MoveTests
{
[TestMethod]
public void NotationConstuctorTest()
{
Move e4move = new Move("E4");
Assert.AreEqual("E4", e4move.ToString());
Move a1move = new Move("A1");
Assert.AreEqual("A1", a1move.ToString());
Move a8move = new Move("A8");
Assert.AreEqual("A8", a8move.ToString());
Move h1move = new Move("H1");
Assert.AreEqual("H1", h1move.ToString());
Move h8move = new Move("H8");
Assert.AreEqual("H8", h8move.ToString());
Assert.Fail();
}
[TestMethod]
public void ToStringTest()
{
ulong h1Mask = 1;
Move h1Move = new Move(h1Mask);
Assert.AreEqual("H1", h1Move.ToString());
ulong e4Mask = 0x8000000;
Move e4Move = new Move(e4Mask);
Assert.AreEqual("E4", e4Move.ToString());
}
[TestMethod]
public void GetBitMaskTest()
{
ulong mask = 0b1000000000000;
Move move = new Move(mask);
Assert.AreEqual(mask, move.GetBitMask());
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using SaurusConsole.OthelloAI;
namespace SaurusConsoleTests
{
[TestClass]
public class MoveTests
{
[TestMethod]
public void NotationConstuctorTest()
{
Move e4move = new Move("E4");
Assert.AreEqual("E4", e4move.ToString());
Move a1move = new Move("A1");
Assert.AreEqual("A1", a1move.ToString());
Move a8move = new Move("A8");
Assert.AreEqual("A8", a8move.ToString());
Move h1move = new Move("H1");
Assert.AreEqual("H1", h1move.ToString());
Move h8move = new Move("H8");
Assert.AreEqual("H8", h8move.ToString());
}
[TestMethod]
public void ToStringTest()
{
ulong h1Mask = 1;
Move h1Move = new Move(h1Mask);
Assert.AreEqual("H1", h1Move.ToString());
ulong e4Mask = 0x8000000;
Move e4Move = new Move(e4Mask);
Assert.AreEqual("E4", e4Move.ToString());
}
[TestMethod]
public void GetBitMaskTest()
{
ulong mask = 0b1000000000000;
Move move = new Move(mask);
Assert.AreEqual(mask, move.GetBitMask());
}
}
}
| mit | C# |
dee0adcd8c61436cf2f88bced371ec9256ca3af3 | Add new overloads. | chkr1011/MQTTnet,JTrotta/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet | Source/MQTTnet/MqttFactory.cs | Source/MQTTnet/MqttFactory.cs | using System;
using System.Collections.Generic;
using MQTTnet.Adapter;
using MQTTnet.Client;
using MQTTnet.Diagnostics;
using MQTTnet.Implementations;
using MQTTnet.Server;
namespace MQTTnet
{
public class MqttFactory : IMqttClientFactory, IMqttServerFactory
{
public IMqttClient CreateMqttClient()
{
return CreateMqttClient(new MqttNetLogger());
}
public IMqttClient CreateMqttClient(IMqttNetLogger logger)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
return new MqttClient(new MqttClientAdapterFactory(), logger);
}
public IMqttClient CreateMqttClient(IMqttClientAdapterFactory adapterFactory)
{
if (adapterFactory == null) throw new ArgumentNullException(nameof(adapterFactory));
return new MqttClient(adapterFactory, new MqttNetLogger());
}
public IMqttClient CreateMqttClient(IMqttNetLogger logger, IMqttClientAdapterFactory adapterFactory)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
if (adapterFactory == null) throw new ArgumentNullException(nameof(adapterFactory));
return new MqttClient(adapterFactory, logger);
}
public IMqttServer CreateMqttServer()
{
var logger = new MqttNetLogger();
return CreateMqttServer(logger);
}
public IMqttServer CreateMqttServer(IMqttNetLogger logger)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
return CreateMqttServer(new List<IMqttServerAdapter> { new MqttTcpServerAdapter(logger.CreateChildLogger()) }, logger);
}
public IMqttServer CreateMqttServer(IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger)
{
if (adapters == null) throw new ArgumentNullException(nameof(adapters));
if (logger == null) throw new ArgumentNullException(nameof(logger));
return new MqttServer(adapters, logger.CreateChildLogger());
}
}
} | using System;
using System.Collections.Generic;
using MQTTnet.Adapter;
using MQTTnet.Client;
using MQTTnet.Diagnostics;
using MQTTnet.Implementations;
using MQTTnet.Server;
namespace MQTTnet
{
public class MqttFactory : IMqttClientFactory, IMqttServerFactory
{
public IMqttClient CreateMqttClient()
{
return CreateMqttClient(new MqttNetLogger());
}
public IMqttClient CreateMqttClient(IMqttNetLogger logger)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
return new MqttClient(new MqttClientAdapterFactory(), logger);
}
public IMqttClient CreateMqttClient(IMqttNetLogger logger, IMqttClientAdapterFactory mqttClientAdapterFactory)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
if (mqttClientAdapterFactory == null) throw new ArgumentNullException(nameof(mqttClientAdapterFactory));
return new MqttClient(mqttClientAdapterFactory, logger);
}
public IMqttServer CreateMqttServer()
{
var logger = new MqttNetLogger();
return CreateMqttServer(logger);
}
public IMqttServer CreateMqttServer(IMqttNetLogger logger)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
return CreateMqttServer(new List<IMqttServerAdapter> { new MqttTcpServerAdapter(logger.CreateChildLogger()) }, logger);
}
public IMqttServer CreateMqttServer(IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger)
{
if (adapters == null) throw new ArgumentNullException(nameof(adapters));
if (logger == null) throw new ArgumentNullException(nameof(logger));
return new MqttServer(adapters, logger.CreateChildLogger());
}
}
} | mit | C# |
8f461884c967be466cbfa2457fd982835f66b730 | Update JSCallResultTypeHelper.cs (#25628) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Shared/JSInterop/JSCallResultTypeHelper.cs | src/Shared/JSInterop/JSCallResultTypeHelper.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
namespace Microsoft.JSInterop
{
internal static class JSCallResultTypeHelper
{
// We avoid using Assembly.GetExecutingAssembly() because this is shared code.
private static readonly Assembly _currentAssembly = typeof(JSCallResultType).Assembly;
public static JSCallResultType FromGeneric<TResult>()
{
if (typeof(TResult).Assembly == _currentAssembly
&& (typeof(TResult) == typeof(IJSObjectReference)
|| typeof(TResult) == typeof(IJSInProcessObjectReference)
|| typeof(TResult) == typeof(IJSUnmarshalledObjectReference)))
{
return JSCallResultType.JSObjectReference;
}
else
{
return JSCallResultType.Default;
}
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.JSInterop
{
internal static class JSCallResultTypeHelper
{
public static JSCallResultType FromGeneric<TResult>()
=> typeof(TResult) == typeof(IJSObjectReference)
|| typeof(TResult) == typeof(IJSInProcessObjectReference)
|| typeof(TResult) == typeof(IJSUnmarshalledObjectReference) ?
JSCallResultType.JSObjectReference :
JSCallResultType.Default;
}
}
| apache-2.0 | C# |
c05a102a54ae3ad1302a8001df72384930de77ae | Remove double licence header | peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework | osu.Framework/Testing/TearDownStepsAttribute.cs | osu.Framework/Testing/TearDownStepsAttribute.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using JetBrains.Annotations;
namespace osu.Framework.Testing
{
/// <summary>
/// Denotes a method which adds <see cref="TestScene"/> steps at the end.
/// Invoked via <see cref="TestScene.RunTearDownSteps"/> (which is called from nUnit's [TearDown] or <see cref="TestBrowser.LoadTest"/>).
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[MeansImplicitUse]
public class TearDownStepsAttribute : Attribute
{
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using JetBrains.Annotations;
namespace osu.Framework.Testing
{
/// <summary>
/// Denotes a method which adds <see cref="TestScene"/> steps at the end.
/// Invoked via <see cref="TestScene.RunTearDownSteps"/> (which is called from nUnit's [TearDown] or <see cref="TestBrowser.LoadTest"/>).
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[MeansImplicitUse]
public class TearDownStepsAttribute : Attribute
{
}
}
| mit | C# |
fa3a3f4f0b3e0325d018e0946331b0416e2e1d33 | Set interval to 10 minutes | mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager | SupportManager.Web/Program.cs | SupportManager.Web/Program.cs | using System.Diagnostics;
using System.IO;
using Hangfire;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using SupportManager.Contracts;
using Topshelf;
namespace SupportManager.Web
{
public class Program
{
private static string[] args;
public static void Main()
{
HostFactory.Run(cfg =>
{
cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' '));
cfg.SetServiceName("SupportManager.Web");
cfg.SetDisplayName("SupportManager.Web");
cfg.SetDescription("SupportManager Web Interface");
cfg.Service<IWebHost>(svc =>
{
svc.ConstructUsing(CreateWebHost);
svc.WhenStarted(webHost =>
{
webHost.Start();
RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.MinuteInterval(10));
});
svc.WhenStopped(webHost => webHost.Dispose());
});
cfg.RunAsLocalSystem();
cfg.StartAutomatically();
});
}
private static IWebHost CreateWebHost()
{
var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
if (!Debugger.IsAttached)
{
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
options.Authentication.AllowAnonymous = true;
});
builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
}
return builder.Build();
}
}
}
| using System.Diagnostics;
using System.IO;
using Hangfire;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using SupportManager.Contracts;
using Topshelf;
namespace SupportManager.Web
{
public class Program
{
private static string[] args;
public static void Main()
{
HostFactory.Run(cfg =>
{
cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' '));
cfg.SetServiceName("SupportManager.Web");
cfg.SetDisplayName("SupportManager.Web");
cfg.SetDescription("SupportManager Web Interface");
cfg.Service<IWebHost>(svc =>
{
svc.ConstructUsing(CreateWebHost);
svc.WhenStarted(webHost =>
{
webHost.Start();
RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.Minutely);
});
svc.WhenStopped(webHost => webHost.Dispose());
});
cfg.RunAsLocalSystem();
cfg.StartAutomatically();
});
}
private static IWebHost CreateWebHost()
{
var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
if (!Debugger.IsAttached)
{
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
options.Authentication.AllowAnonymous = true;
});
builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
}
return builder.Build();
}
}
}
| mit | C# |
3c10c350723b807f43c3c7ff1e3b5e0fdd6378d1 | delete spaces | sunkaixuan/SqlSugar | Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Enum/ProperyType.cs | Src/Asp.NetCore2/SqlSeverTest/SqlSugar/Enum/ProperyType.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar
{
public enum CSharpDataType
{
@int,
@bool,
@string,
@DateTime,
@decimal,
@double,
@Guid,
@byte,
@enum,
@short,
@long,
@object,
@other,
@byteArray,
@float,
@time,
@DateTimeOffset,
@Single,
@TimeSpan
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar
{
public enum CSharpDataType
{
@int,
@bool,
@string,
@DateTime,
@decimal,
@double,
@Guid,
@byte,
@enum,
@short,
@long,
@object,
@other,
@byteArray,
@float,
@time,
@DateTimeOffset,
@Single,
@TimeSpan
}
}
| apache-2.0 | C# |
53af96df6dd139030ca29a9e36dc1ba9a6b7d6d8 | Apply filtering to sessions payload | bugsnag/bugsnag-dotnet,bugsnag/bugsnag-dotnet | src/Bugsnag/Payload/BatchedSessions.cs | src/Bugsnag/Payload/BatchedSessions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Bugsnag.Payload
{
public class BatchedSessions : Dictionary<string, object>, IPayload
{
private readonly KeyValuePair<string, string>[] _headers;
private readonly IConfiguration _configuration;
public BatchedSessions(IConfiguration configuration, IEnumerable<KeyValuePair<string, long>> sessionData) : this(configuration, NotifierInfo.Instance, new App(configuration), new Device(), sessionData)
{
}
public BatchedSessions(IConfiguration configuration, NotifierInfo notifier, App app, Device device, IEnumerable<KeyValuePair<string, long>> sessionData)
{
_configuration = configuration;
Endpoint = configuration.SessionEndpoint;
Proxy = configuration.Proxy;
_headers = new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>(Payload.Headers.ApiKeyHeader, configuration.ApiKey),
new KeyValuePair<string, string>(Payload.Headers.PayloadVersionHeader, "1.0")
};
this.AddToPayload("notifier", notifier);
this.AddToPayload("device", device);
this.AddToPayload("app", app);
this.AddToPayload("sessionCounts", sessionData.Select(kv => new SessionCount(kv.Key, kv.Value)).ToArray());
}
public Uri Endpoint { get; set; }
public IWebProxy Proxy { get; set; }
public KeyValuePair<string, string>[] Headers => _headers;
public byte[] Serialize()
{
return Serializer.SerializeObjectToByteArray(this, _configuration.MetadataFilters);
}
}
public class SessionCount : Dictionary<string, object>
{
public SessionCount(string startedAt, long sessionStarted)
{
this.AddToPayload("startedAt", startedAt);
this.AddToPayload("sessionsStarted", sessionStarted);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Bugsnag.Payload
{
public class BatchedSessions : Dictionary<string, object>, IPayload
{
private readonly KeyValuePair<string, string>[] _headers;
public BatchedSessions(IConfiguration configuration, IEnumerable<KeyValuePair<string, long>> sessionData) : this(configuration, NotifierInfo.Instance, new App(configuration), new Device(), sessionData)
{
}
public BatchedSessions(IConfiguration configuration, NotifierInfo notifier, App app, Device device, IEnumerable<KeyValuePair<string, long>> sessionData)
{
Endpoint = configuration.SessionEndpoint;
Proxy = configuration.Proxy;
_headers = new KeyValuePair<string, string>[] {
new KeyValuePair<string, string>(Payload.Headers.ApiKeyHeader, configuration.ApiKey),
new KeyValuePair<string, string>(Payload.Headers.PayloadVersionHeader, "1.0")
};
this.AddToPayload("notifier", notifier);
this.AddToPayload("device", device);
this.AddToPayload("app", app);
this.AddToPayload("sessionCounts", sessionData.Select(kv => new SessionCount(kv.Key, kv.Value)).ToArray());
}
public Uri Endpoint { get; set; }
public IWebProxy Proxy { get; set; }
public KeyValuePair<string, string>[] Headers => _headers;
public byte[] Serialize()
{
return Serializer.SerializeObjectToByteArray(this);
}
}
public class SessionCount : Dictionary<string, object>
{
public SessionCount(string startedAt, long sessionStarted)
{
this.AddToPayload("startedAt", startedAt);
this.AddToPayload("sessionsStarted", sessionStarted);
}
}
}
| mit | C# |
072ec05a990bd14a55a486d865a059ce4b57d6ad | Update StringExtensions.cs | BenjaminAbt/snippets | CSharp/StringExtensions.cs | CSharp/StringExtensions.cs | public static class StringExtensions
{
/// <summary>
/// Cuts a string with the given max length
/// </summary>
public static string WithMaxLength(this string value, int maxLength)
{
return value?.Substring(0, Math.Min(value.Length, maxLength));
}
}
| public static class StringExtensions
{
public static string WithMaxLength(this string value, int maxLength)
{
return value?.Substring(0, Math.Min(value.Length, maxLength));
}
}
| mit | C# |
80057eabb1049f10db1784ad8ba4e6da6979de76 | Fix null reference exception then accessing viewstate | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/components/XmlSerializationHelper.cs | R7.University/components/XmlSerializationHelper.cs | //
// XmlSerializationHelper.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Xml.Serialization;
namespace R7.University
{
public static class XmlSerializationHelper
{
public static string Serialize<T> (T value) where T: class, new()
{
var xmlSerializer = new XmlSerializer (typeof (T));
var stringWritter = new StringWriter ();
xmlSerializer.Serialize (stringWritter, value);
return stringWritter.ToString ();
}
public static T Deserialize<T> (object value) where T: class, new()
{
if (value != null && !string.IsNullOrEmpty (value.ToString ()))
{
var xmlSerializer = new XmlSerializer (typeof (T));
var stringReader = new StringReader (value.ToString ());
return xmlSerializer.Deserialize (stringReader) as T;
}
return null;
}
}
}
| //
// XmlSerializationHelper.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Xml.Serialization;
namespace R7.University
{
public static class XmlSerializationHelper
{
public static string Serialize<T> (T value) where T: class, new()
{
var xmlSerializer = new XmlSerializer (typeof (T));
var stringWritter = new StringWriter ();
xmlSerializer.Serialize (stringWritter, value);
return stringWritter.ToString ();
}
public static T Deserialize<T> (object value) where T: class, new()
{
if (!string.IsNullOrEmpty (value.ToString ()))
{
var xmlSerializer = new XmlSerializer (typeof (T));
var stringReader = new StringReader (value.ToString ());
return xmlSerializer.Deserialize (stringReader) as T;
}
return null;
}
}
}
| agpl-3.0 | C# |
3caefc73d2279b39a2fc781c11099f735ad343c7 | Build before first Start if the executable doesn't exist | xilec/VisualRust,dlsteuer/VisualRust,vosen/VisualRust,tempbottle/VisualRust,yacoder/VisualRust,yacoder/VisualRust,drewet/VisualRust,tempbottle/VisualRust,Stitchous/VisualRust,xilec/VisualRust,Vbif/VisualRust,vosen/VisualRust,Boddlnagg/VisualRust,PistonDevelopers/VisualRust,Vbif/VisualRust,cmr/VisualRust,vadimcn/VisualRust,Connorcpu/VisualRust,Stitchous/VisualRust,PistonDevelopers/VisualRust,Muraad/VisualRust,drewet/VisualRust,cmr/VisualRust,Muraad/VisualRust,Boddlnagg/VisualRust,vadimcn/VisualRust,dlsteuer/VisualRust,Connorcpu/VisualRust | VisualRust.Project/DefaultRustLauncher.cs | VisualRust.Project/DefaultRustLauncher.cs | using System;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
namespace VisualRust.Project
{
sealed class DefaultRustLauncher : IProjectLauncher
{
private readonly RustProjectNode _project;
public DefaultRustLauncher(RustProjectNode project)
{
Utilities.ArgumentNotNull("project", project);
_project = project;
}
public int LaunchProject(bool debug)
{
if(_project.GetProjectProperty("OutputType") != "exe")
throw new InvalidOperationException("A project with an Output Type of Library cannot be started directly.");
var startupFilePath = GetProjectStartupFile();
return LaunchFile(startupFilePath, debug);
}
private string GetProjectStartupFile()
{
var startupFilePath = Path.Combine(_project.GetProjectProperty("TargetDir"), _project.GetProjectProperty("TargetFileName"));
if (string.IsNullOrEmpty(startupFilePath))
{
throw new ApplicationException("Visual Rust could not resolve path for your executable. Your installation of Visual Rust or .rsproj file might be corrupted.");
}
return startupFilePath;
}
public int LaunchFile(string file, bool debug)
{
StartWithoutDebugger(file);
return VSConstants.S_OK;
}
private void StartWithoutDebugger(string startupFile)
{
if(!File.Exists(startupFile))
_project.Build("Build");
var processStartInfo = CreateProcessStartInfoNoDebug(startupFile);
Process.Start(processStartInfo);
}
private ProcessStartInfo CreateProcessStartInfoNoDebug(string startupFile)
{
var commandLineArgs = string.Empty;
var startInfo = new ProcessStartInfo(startupFile, commandLineArgs);
startInfo.UseShellExecute = false;
return startInfo;
}
}
} | using System;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
namespace VisualRust.Project
{
/// <summary>
/// Simple realization of project launcher for executable file
/// TODO need realize for library
/// </summary>
sealed class DefaultRustLauncher : IProjectLauncher
{
private readonly RustProjectNode _project;
public DefaultRustLauncher(RustProjectNode project)
{
Utilities.ArgumentNotNull("project", project);
_project = project;
}
public int LaunchProject(bool debug)
{
var startupFilePath = GetProjectStartupFile();
return LaunchFile(startupFilePath, debug);
}
private string GetProjectStartupFile()
{
var startupFilePath = Path.Combine(_project.GetProjectProperty("TargetDir"), _project.GetProjectProperty("TargetFileName"));
//var startupFilePath = _project.GetStartupFile();
if (string.IsNullOrEmpty(startupFilePath))
{
throw new ApplicationException("Startup file is not defined in project");
}
return startupFilePath;
}
public int LaunchFile(string file, bool debug)
{
StartWithoutDebugger(file);
return VSConstants.S_OK;
}
private void StartWithoutDebugger(string startupFile)
{
var processStartInfo = CreateProcessStartInfoNoDebug(startupFile);
Process.Start(processStartInfo);
}
private ProcessStartInfo CreateProcessStartInfoNoDebug(string startupFile)
{
// TODO add command line arguments
var commandLineArgs = string.Empty;
var startInfo = new ProcessStartInfo(startupFile, commandLineArgs);
startInfo.UseShellExecute = false;
return startInfo;
}
}
} | mit | C# |
d0cbc5ce286697ad2e873e2e07e15b72a2e3d921 | change 'spam' to have same casing than elsewhere | ScottShingler/NuGetGallery,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,KuduApps/NugetGallery16Fx45-DeleteMe,mtian/SiteExtensionGallery,KuduApps/NugetGallery21Fx45-DeleteMe,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,JetBrains/ReSharperGallery,JetBrains/ReSharperGallery,kudustress/NuGetGallery2,KuduApps/NuGetGallery,skbkontur/NuGetGallery,KuduApps/NuGetGallery,projectkudu/SiteExtensionGallery,KuduApps/NuGetGallery,kudustress/NuGetGallery,ScottShingler/NuGetGallery,ScottShingler/NuGetGallery,kudustress/NuGetGallery2,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,kudustress/NuGetGalleryOptmized,KuduApps/NuGetGallery,KuduApps/NugetGallery16Fx45-DeleteMe,KuduApps/NugetGallery21Fx45-DeleteMe,KuduApps/NuGetGallery,kudustress/NuGetGallery,JetBrains/ReSharperGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,projectkudu/SiteExtensionGallery,kudustress/NuGetGalleryOptmized | Website/Views/Authentication/LogOn.cshtml | Website/Views/Authentication/LogOn.cshtml | @using NuGetGallery;
@model SignInRequest
<h1>Log On</h1>
<p>
Don't have an account yet? <a href="@Url.Action(MVC.Users.Register())">Register now.</a>
</p>
@using (Html.BeginForm()) {
<fieldset class="form">
<legend>Log On Form</legend>
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@if (ViewBag.ConfirmationRequired != null && ViewBag.ConfirmationRequired) {
<p class="validation-summary-errors">
Before you can log on, you’ll need to confirm your account. When you registered,
we sent you an email with a URL you can click to confirm your account.
Please check your spam folder if you did not receive the confirmation email.
</p>
}
@Html.EditorForModel()
<img src="@Url.Content("~/content/images/required.png")" alt="Blue border on left means required." />
<input type="submit" value="Log On" title="Log On" />
@Html.ActionLink("Lost your Password?", "ForgotPassword", "Users")
</fieldset>
}
@section BottomScripts {
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
} | @using NuGetGallery;
@model SignInRequest
<h1>Log On</h1>
<p>
Don't have an account yet? <a href="@Url.Action(MVC.Users.Register())">Register now.</a>
</p>
@using (Html.BeginForm()) {
<fieldset class="form">
<legend>Log On Form</legend>
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@if (ViewBag.ConfirmationRequired != null && ViewBag.ConfirmationRequired) {
<p class="validation-summary-errors">
Before you can log on, you’ll need to confirm your account. When you registered,
we sent you an email with a URL you can click to confirm your account.
Please check your SPAM folder if you did not receive the confirmation email.
</p>
}
@Html.EditorForModel()
<img src="@Url.Content("~/content/images/required.png")" alt="Blue border on left means required." />
<input type="submit" value="Log On" title="Log On" />
@Html.ActionLink("Lost your Password?", "ForgotPassword", "Users")
</fieldset>
}
@section BottomScripts {
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
} | apache-2.0 | C# |
60ba0abebd66bedcee128bbe428851c1869d44b7 | Revert "[MapperTests]: Refactor CacheMiss test" | vanashimko/MPP.Mapper | MapperTests/DtoMapperTests.cs | MapperTests/DtoMapperTests.cs | using System;
using Xunit;
using Mapper;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
namespace Mapper.Tests
{
public class DtoMapperTests
{
[Fact]
public void Map_NullPassed_ExceptionThrown()
{
IMapper mapper = new DtoMapper();
Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null));
}
[Fact]
public void Map_TwoCompatibleFields_TwoFieldsAssigned()
{
IMapper mapper = new DtoMapper();
var source = new Source
{
FirstProperty = 1,
SecondProperty = "a",
ThirdProperty = 3.14,
FourthProperty = 2
};
var expected = new Destination
{
FirstProperty = source.FirstProperty,
SecondProperty = source.SecondProperty,
};
Destination actual = mapper.Map<Source, Destination>(source);
Assert.Equal(expected, actual);
}
[Fact]
public void Map_CacheMiss_GetCacheForDidNotCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never);
}
[Fact]
public void Map_CacheHit_GetCacheForCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
mockCache.Setup(mock => mock.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(true);
mockCache.Setup(mock => mock.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>())).Returns(x => x);
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Once);
}
}
} | using System;
using Xunit;
using Mapper;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
namespace Mapper.Tests
{
public class DtoMapperTests
{
[Fact]
public void Map_NullPassed_ExceptionThrown()
{
IMapper mapper = new DtoMapper();
Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null));
}
[Fact]
public void Map_TwoCompatibleFields_TwoFieldsAssigned()
{
IMapper mapper = new DtoMapper();
var source = new Source
{
FirstProperty = 1,
SecondProperty = "a",
ThirdProperty = 3.14,
FourthProperty = 2
};
var expected = new Destination
{
FirstProperty = source.FirstProperty,
SecondProperty = source.SecondProperty,
};
Destination actual = mapper.Map<Source, Destination>(source);
Assert.Equal(expected, actual);
}
[Fact]
public void Map_CacheMiss_GetCacheForDidNotCalled()
{
var mockCache = Mock.Of<IMappingFunctionsCache>();
IMapper mapper = new DtoMapper(mockCache);
mapper.Map<object, object>(new object());
Mock.Get(mockCache).Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never);
}
[Fact]
public void Map_CacheHit_GetCacheForCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
mockCache.Setup(mock => mock.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(true);
mockCache.Setup(mock => mock.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>())).Returns(x => x);
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Once);
}
}
} | mit | C# |
2261cfc20226ccdeb8857caea1931695ebdbfff7 | Implement some LLVMAssembly methods | jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm | Flame.LLVM/LLVMAssembly.cs | Flame.LLVM/LLVMAssembly.cs | using System;
using System.IO;
using System.Runtime.InteropServices;
using Flame.Compiler.Build;
using LLVMSharp;
using static LLVMSharp.LLVM;
namespace Flame.LLVM
{
/// <summary>
/// An assembly builder implementation that creates an LLVM module.
/// </summary>
public sealed class LLVMAssembly : IAssemblyBuilder
{
public LLVMAssembly(
UnqualifiedName Name,
Version AssemblyVersion,
AttributeMap Attributes)
{
this.Name = Name;
this.AssemblyVersion = AssemblyVersion;
this.Attributes = Attributes;
this.Module = ModuleCreateWithName(Name.ToString());
}
public Version AssemblyVersion { get; private set; }
public AttributeMap Attributes { get; private set; }
/// <summary>
/// Gets the assembly's name.
/// </summary>
/// <returns>The assembly's name.</returns>
public UnqualifiedName Name { get; private set; }
/// <summary>
/// Gets the LLVM module that is managed by this LLVM assembly.
/// </summary>
/// <returns>The LLVM module.</returns>
public LLVMModuleRef Module { get; private set; }
public QualifiedName FullName => Name.Qualify();
public IAssembly Build()
{
IntPtr error;
VerifyModule(Module, LLVMVerifierFailureAction.LLVMAbortProcessAction, out error);
DisposeMessage(error);
return this;
}
public IBinder CreateBinder()
{
throw new NotImplementedException();
}
public INamespaceBuilder DeclareNamespace(string Name)
{
throw new NotImplementedException();
}
public IMethod GetEntryPoint()
{
throw new NotImplementedException();
}
public void Initialize()
{
}
public void Save(IOutputProvider OutputProvider)
{
var file = OutputProvider.Create();
IntPtr moduleOutput = PrintModuleToString(Module);
var ir = Marshal.PtrToStringAnsi(moduleOutput);
using (var writer = new StreamWriter(file.OpenOutput()))
{
writer.Write(ir);
}
LLVMSharp.LLVM.DisposeMessage(moduleOutput);
}
public void SetEntryPoint(IMethod Method)
{
throw new NotImplementedException();
}
}
}
| using System;
using Flame.Compiler.Build;
namespace Flame.LLVM
{
/// <summary>
/// An assembly builder implementation that creates an LLVM module.
/// </summary>
public sealed class LLVMAssembly : IAssemblyBuilder
{
public LLVMAssembly(
UnqualifiedName Name,
Version AssemblyVersion,
AttributeMap Attributes)
{
this.Name = Name;
this.AssemblyVersion = AssemblyVersion;
this.Attributes = Attributes;
}
public Version AssemblyVersion { get; private set; }
public AttributeMap Attributes { get; private set; }
public UnqualifiedName Name { get; private set; }
public QualifiedName FullName => Name.Qualify();
public IAssembly Build()
{
throw new NotImplementedException();
}
public IBinder CreateBinder()
{
throw new NotImplementedException();
}
public INamespaceBuilder DeclareNamespace(string Name)
{
throw new NotImplementedException();
}
public IMethod GetEntryPoint()
{
throw new NotImplementedException();
}
public void Initialize()
{
throw new NotImplementedException();
}
public void Save(IOutputProvider OutputProvider)
{
throw new NotImplementedException();
}
public void SetEntryPoint(IMethod Method)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
319dd424322fe7fa31cfbbe9c63122c3b58a3cac | Update Program.cs | WojcikMike/docs.particular.net,eclaus/docs.particular.net,yuxuac/docs.particular.net,pedroreys/docs.particular.net | samples/unit-of-work/using-childcontainers/Version_5/Sample/Program.cs | samples/unit-of-work/using-childcontainers/Version_5/Sample/Program.cs | using System;
using NServiceBus;
using Raven.Client;
using Raven.Client.Document;
using StructureMap;
static class Program
{
static void Main()
{
BusConfiguration configuration = new BusConfiguration();
configuration.EndpointName("Samples.UoWWithChildContainers");
#region ContainerConfiguration
Container container = new Container(x =>
{
x.For<IDocumentStore>().Use(new DocumentStore
{
Url = "http://localhost:32076",
DefaultDatabase = "Samples.UoWWithChildContainers"
}
.Initialize());
x.For<IDocumentSession>().Use(c => c.GetInstance<IDocumentStore>().OpenSession());
});
configuration.UseContainer<StructureMapBuilder>(c => c.ExistingContainer(container));
#endregion
#region PipelineRegistration
configuration.Pipeline.Register<RavenUnitOfWork.Registration>();
#endregion
configuration.UsePersistence<InMemoryPersistence>();
configuration.EnableInstallers();
int orderNumber = 1;
using (IStartableBus bus = Bus.Create(configuration))
{
bus.Start();
Console.Out.WriteLine("Press any key to send a message. Press `q` to quit");
Console.Out.WriteLine("After storing a few orders you can open a browser and view them at http://localhost:32076/studio/index.html#databases/documents?collection=Orders&database=Samples.UoWWithChildContainers");
while (Console.ReadKey().ToString() != "q")
{
bus.SendLocal(new PlaceOrder
{
OrderNumber = string.Format("Order-{0}", orderNumber),
OrderValue = 100
});
orderNumber++;
}
}
}
}
| using System;
using NServiceBus;
using Raven.Client;
using Raven.Client.Document;
using StructureMap;
static class Program
{
static void Main()
{
BusConfiguration configuration = new BusConfiguration();
configuration.EndpointName("Samples.UoWWithChildContainers");
#region ContainerConfiguration
Container container = new Container(x =>
{
x.For<IDocumentStore>().Use(new DocumentStore
{
Url = "http://localhost:32076",
DefaultDatabase = "Samples.UoWWithChildContainers"
}
.Initialize());
x.For<IDocumentSession>().Use(c => c.GetInstance<IDocumentStore>().OpenSession());
});
configuration.UseContainer<StructureMapBuilder>(c => c.ExistingContainer(container));
#endregion
#region PipelineRegistration
configuration.Pipeline.Register<RavenUnitOfWork.Registration>();
#endregion
configuration.UsePersistence<InMemoryPersistence>();
configuration.EnableInstallers();
int orderNumber = 1;
using (IStartableBus bus = Bus.Create(configuration))
{
bus.Start();
Console.Out.WriteLine("Press any key to send a message. Press `q` to quit");
Console.Out.WriteLine("After storing a few orders you can open a browser and view them at http://localhost:32076/studio/index.html#databases/documents?collection=Orders&database=Samples.UoWWithChildContainers");
while (Console.ReadKey().ToString() != "q")
{
bus.SendLocal(new PlaceOrder
{
OrderNumber = string.Format("Order-{0}", orderNumber),
OrderValue = 100
});
orderNumber++;
}
}
}
} | apache-2.0 | C# |
62d4704d69b0e15675ec6a088b7e22dc09779bd0 | Make identity-test API easier to consume | vflorusso/nether,stuartleeks/nether,navalev/nether,brentstineman/nether,ankodu/nether,vflorusso/nether,stuartleeks/nether,vflorusso/nether,navalev/nether,krist00fer/nether,MicrosoftDX/nether,ankodu/nether,brentstineman/nether,navalev/nether,ankodu/nether,brentstineman/nether,vflorusso/nether,brentstineman/nether,oliviak/nether,stuartleeks/nether,ankodu/nether,navalev/nether,stuartleeks/nether,brentstineman/nether,stuartleeks/nether,vflorusso/nether | src/Nether.Web/Features/Identity/Controllers/IdentityTestController.cs | src/Nether.Web/Features/Identity/Controllers/IdentityTestController.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace Nether.Web.Features.Identity
{
[Route("identity-test")]
[Authorize]
public class IdentityTestController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
// Convert claim type, value pairs into a dictionary for easier consumption as JSON
// Need to group as there can be multiple claims of the same type (e.g. 'scope')
var result = User.Claims
.GroupBy(c => c.Type)
.ToDictionary(
keySelector: g => g.Key,
elementSelector: g => g.Count() == 1 ? (object)g.First().Value : g.Select(t => t.Value).ToArray()
);
return new JsonResult(result);
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace Nether.Web.Features.Identity
{
[Route("identity-test")]
[Authorize]
public class IdentityTestController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}
| mit | C# |
efe4bf67dfb5775d4bcc55b030b2101e2ee1500a | return back | askeip/tasks | Eval/EvalProgram.cs | Eval/EvalProgram.cs | using System;
using System.Linq.Expressions;
namespace EvalTask
{
class EvalProgram
{
static void Main(string[] args)
{
string input = Console.In.ReadToEnd();
var calc = new Sprache.Calc.XtensibleCalculator();
calc.RegisterFunction("sqrt", Math.Sqrt);
input = input.Replace("%", "* 0.01");
// using expressions
var expr = calc.ParseExpression(input);
var func = expr.Compile();
Console.WriteLine(func().ToString().Replace(",", ".").Replace("бесконечность","Infinity"));
}
}
}
| using System;
using System.Linq.Expressions;
namespace EvalTask
{
class EvalProgram
{
static void Main(string[] args)
{
string input = Console.In.ReadToEnd();
var calc = new Sprache.Calc.XtensibleCalculator();
calc.RegisterFunction("sqrt", Math.Sqrt);
input = input.Replace("%", "* 0.01");
// using expressions
var expr = calc.ParseExpression(input);
var func = expr.Compile();
if (input.Contains("."))
Console.WriteLine(func().ToString().Replace(",", ".").Replace("бесконечность","Infinity"));
else
{
Console.WriteLine(((int)func()).ToString().Replace(",", ".").Replace("бесконечность", "Infinity"));
}
}
}
}
| mit | C# |
607638abc609c3a64a436c3e27620725875a7b57 | Update SharedSlotType.cs | stoiveyp/Alexa.NET.Management | Alexa.NET.Management/SlotType/SharedSlotType.cs | Alexa.NET.Management/SlotType/SharedSlotType.cs | using Newtonsoft.Json;
namespace Alexa.NET.Management.SlotType
{
public class SharedSlotType
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description",NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
}
}
| using Newtonsoft.Json;
namespace Alexa.NET.Management.SlotType
{
public class SharedSlotType
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description",NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
}
} | mit | C# |
59b65197f5fa35904f3cf047c482241ae7aa94fc | Fix Alpaca error message deserialization | jameschch/Lean,JKarathiya/Lean,StefanoRaggi/Lean,jameschch/Lean,AlexCatarino/Lean,QuantConnect/Lean,QuantConnect/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,AlexCatarino/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,StefanoRaggi/Lean,JKarathiya/Lean,StefanoRaggi/Lean,QuantConnect/Lean,JKarathiya/Lean,JKarathiya/Lean,jameschch/Lean,jameschch/Lean,jameschch/Lean,QuantConnect/Lean | Brokerages/Alpaca/Markets/Messages/JsonError.cs | Brokerages/Alpaca/Markets/Messages/JsonError.cs | /*
* The official C# API client for alpaca brokerage
* Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2
*/
using System;
using Newtonsoft.Json;
namespace QuantConnect.Brokerages.Alpaca.Markets
{
internal sealed class JsonError
{
[JsonProperty(PropertyName = "code", Required = Required.Default)]
public Int32 Code { get; set; }
[JsonProperty(PropertyName = "message", Required = Required.Always)]
public String Message { get; set; }
}
}
| /*
* The official C# API client for alpaca brokerage
* Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2
*/
using System;
using Newtonsoft.Json;
namespace QuantConnect.Brokerages.Alpaca.Markets
{
internal sealed class JsonError
{
[JsonProperty(PropertyName = "code", Required = Required.Always)]
public Int32 Code { get; set; }
[JsonProperty(PropertyName = "message", Required = Required.Always)]
public String Message { get; set; }
}
}
| apache-2.0 | C# |
17ffd175ca659e2bef1b871e28d57e3782bb485d | add ability to set a local default dialect, just like row fields provider | volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity | src/Serenity.Net.Data/SqlHelpers/SqlSettings.cs | src/Serenity.Net.Data/SqlHelpers/SqlSettings.cs |
using System;
using System.Threading;
namespace Serenity.Data
{
/// <summary>
/// Global SQL settings
/// </summary>
public static class SqlSettings
{
private static ISqlDialect defaultDialect;
private static readonly AsyncLocal<ISqlDialect> localDialect;
static SqlSettings()
{
defaultDialect = new SqlServer2012Dialect();
localDialect = new AsyncLocal<ISqlDialect>();
}
/// <summary>
/// Gets or sets a value indicating whether to automatically quote identifiers.
/// </summary>
/// <value>
/// <c>true</c> if should automatically quote identifiers; otherwise, <c>false</c>.
/// </value>
public static bool AutoQuotedIdentifiers { get; set; }
/// <summary>
/// Gets or sets the default command timeout.
/// </summary>
/// <value>
/// The default command timeout.
/// </value>
public static int? DefaultCommandTimeout { get; set; }
/// <summary>
/// The default dialect, returns the local dialect if any set through
/// SetLocal, the default dialect otherwise.
/// This should be only set on application start.
/// Local dialect should be used for unit tests.
/// </summary>
public static ISqlDialect DefaultDialect
{
get => localDialect.Value ?? defaultDialect;
set => defaultDialect = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Sets local dialect for current thread and async context.
/// Useful for background tasks, async methods, and testing to
/// set dialect locally and for auto spawned threads.
/// </summary>
/// <param name="dialect">Dialect. Can be null.</param>
/// <returns>Old local dialect if any.</returns>
public static ISqlDialect SetLocalDialect(ISqlDialect dialect)
{
var old = localDialect.Value;
localDialect.Value = dialect;
return old;
}
}
} |
using System;
namespace Serenity.Data
{
/// <summary>
/// Global SQL settings
/// </summary>
public static class SqlSettings
{
private static ISqlDialect defaultDialect = new SqlServer2012Dialect();
/// <summary>
/// Gets or sets a value indicating whether to automatically quote identifiers.
/// </summary>
/// <value>
/// <c>true</c> if should automatically quote identifiers; otherwise, <c>false</c>.
/// </value>
public static bool AutoQuotedIdentifiers { get; set; }
/// <summary>
/// Gets or sets the default command timeout.
/// </summary>
/// <value>
/// The default command timeout.
/// </value>
public static int? DefaultCommandTimeout { get; set; }
/// <summary>
/// The default dialect
/// </summary>
public static ISqlDialect DefaultDialect
{
get => defaultDialect;
set => defaultDialect = value ?? throw new ArgumentNullException(nameof(value));
}
}
} | mit | C# |
f0783207e57b7551e4be400e90f360f3252d6653 | Fix PreGeneratedSerializerGenerator does not generate async methods. | msgpack/msgpack-cli,msgpack/msgpack-cli | test/MsgPack.UnitTest/Serialization/PreGeneratedSerializerGenerator.cs | test/MsgPack.UnitTest/Serialization/PreGeneratedSerializerGenerator.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2014 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using NUnit.Framework;
namespace MsgPack.Serialization
{
[TestFixture]
internal class PreGeneratedSerializerGenerator
{
// To test generated serializers, enable this test and run, then copy bin/Debug/MsgPack contents to project's Serialization/GeneratedSerializers/ directory.
//[Test]
public void GenerateFiles()
{
// Note: if you face to PathTooLongException here, specify OutputDirectory of bellow object initializers.
SerializerGenerator.GenerateCode(
new SerializerCodeGenerationConfiguration
{
Namespace = "MsgPack.Serialization.GeneratedSerializers",
#if NETFX_35
OutputDirectory = "\\temp-gen35",
#else
OutputDirectory = "\\temp-gen",
WithAsync = true,
#endif
IsInternalToMsgPackLibrary = true // because of InternalsVisibleTo
},
PreGeneratedSerializerActivator.KnownTypes
);
}
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2014 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using NUnit.Framework;
namespace MsgPack.Serialization
{
[TestFixture]
internal class PreGeneratedSerializerGenerator
{
// To test generated serializers, enable this test and run, then copy bin/Debug/MsgPack contents to project's Serialization/GeneratedSerializers/ directory.
//[Test]
public void GenerateFiles()
{
// Note: if you face to PathTooLongException here, specify OutputDirectory of bellow object initializers.
SerializerGenerator.GenerateCode(
new SerializerCodeGenerationConfiguration
{
Namespace = "MsgPack.Serialization.GeneratedSerializers",
#if NETFX_35
OutputDirectory = "\\temp-gen35",
#else
OutputDirectory = "\\temp-gen",
#endif
IsInternalToMsgPackLibrary = true // because of InternalsVisibleTo
},
PreGeneratedSerializerActivator.KnownTypes
);
}
}
}
| apache-2.0 | C# |
43b59204d3e85c2ef7169f753f4d1ce66e805f29 | Fix AggregationResult error | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.Core/Index/AggregationResult.cs | InfinniPlatform.Core/Index/AggregationResult.cs | using System.Collections.Generic;
using InfinniPlatform.Sdk.Registers;
namespace InfinniPlatform.Core.Index
{
/// <summary>
/// Результат выполнения агрегации по одному измерению
/// </summary>
public class AggregationResult
{
private readonly List<AggregationResult> _backets;
public AggregationResult()
{
_backets = new List<AggregationResult>();
}
/// <summary>
/// Gets an aggregation name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets measure type of aggregation
/// </summary>
public AggregationType[] MeasureTypes { get; set; }
/// <summary>
/// Measured aggregation values
/// </summary>
public double[] Values { get; set; }
/// <summary>
/// Count of documents in the aggregation
/// </summary>
public long? DocCount { get; set; }
/// <summary>
/// Gets the inner aggregation result
/// </summary>
public List<AggregationResult> Buckets
{
get { return _backets; }
}
//TODO Избавиться в процессе рефакторинга регистров.
/// <remarks>
/// Раньше появлялось только в динамическом контексте. Поведение до конца не изучено.
/// </remarks>
public List<AggregationResult> DenormalizationResult { get; set; }
}
} | using System.Collections.Generic;
using InfinniPlatform.Sdk.Registers;
namespace InfinniPlatform.Core.Index
{
/// <summary>
/// Результат выполнения агрегации по одному измерению
/// </summary>
public class AggregationResult
{
private readonly List<AggregationResult> _backets;
public AggregationResult()
{
_backets = new List<AggregationResult>();
}
/// <summary>
/// Gets an aggregation name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets measure type of aggregation
/// </summary>
public AggregationType[] MeasureTypes { get; set; }
/// <summary>
/// Measured aggregation values
/// </summary>
public double[] Values { get; set; }
/// <summary>
/// Count of documents in the aggregation
/// </summary>
public long? DocCount { get; set; }
/// <summary>
/// Gets the inner aggregation result
/// </summary>
public List<AggregationResult> Buckets
{
get { return _backets; }
}
}
} | agpl-3.0 | C# |
91af4cc2ab78c55839fa5cf08782c7c25a348b59 | Whitelist RuntimeWrappedException constructor need by System.Linq.Expressions. (#3499) | tijoytom/corert,shrah/corert,shrah/corert,krytarowski/corert,tijoytom/corert,gregkalapos/corert,shrah/corert,tijoytom/corert,shrah/corert,krytarowski/corert,yizhang82/corert,krytarowski/corert,gregkalapos/corert,krytarowski/corert,yizhang82/corert,yizhang82/corert,gregkalapos/corert,yizhang82/corert,gregkalapos/corert,tijoytom/corert | src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs | src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeWrappedException.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.
/*=============================================================================
**
**
**
** Purpose: The exception class uses to wrap all non-CLS compliant exceptions.
**
**
=============================================================================*/
using System;
using System.Runtime.Serialization;
namespace System.Runtime.CompilerServices
{
[Serializable]
public sealed class RuntimeWrappedException : Exception
{
private Object _wrappedException;
// Not an api but has to be public as System.Linq.Expression invokes this through Reflection when an expression
// throws an object that doesn't derive from Exception.
public RuntimeWrappedException(Object thrownObject)
: base(SR.RuntimeWrappedException)
{
HResult = __HResults.COR_E_RUNTIMEWRAPPED;
_wrappedException = thrownObject;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("WrappedException", _wrappedException, typeof(Object));
}
internal RuntimeWrappedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_wrappedException = info.GetValue("WrappedException", typeof(Object));
}
public Object WrappedException
{
get { return _wrappedException; }
}
}
}
| // 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.
/*=============================================================================
**
**
**
** Purpose: The exception class uses to wrap all non-CLS compliant exceptions.
**
**
=============================================================================*/
using System;
using System.Runtime.Serialization;
namespace System.Runtime.CompilerServices
{
[Serializable]
public sealed class RuntimeWrappedException : Exception
{
private Object _wrappedException;
private RuntimeWrappedException(Object thrownObject)
: base(SR.RuntimeWrappedException)
{
HResult = __HResults.COR_E_RUNTIMEWRAPPED;
_wrappedException = thrownObject;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("WrappedException", _wrappedException, typeof(Object));
}
internal RuntimeWrappedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_wrappedException = info.GetValue("WrappedException", typeof(Object));
}
public Object WrappedException
{
get { return _wrappedException; }
}
}
}
| mit | C# |
d17212f6e845eae4f8796ea09a0561f9816c92f9 | allow many config files | kreeben/resin,kreeben/resin | src/Sir/IniConfiguration.cs | src/Sir/IniConfiguration.cs | using System.Collections.Generic;
using System.IO;
namespace Sir
{
public class IniConfiguration : IConfigurationProvider
{
private IDictionary<string, string> _doc;
private readonly string _fileName;
public IniConfiguration(string fileName)
{
_doc = new Dictionary<string, string>();
_fileName = Path.Combine(Directory.GetCurrentDirectory(), fileName);
OnFileChanged(null, null);
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Directory.GetCurrentDirectory();
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = $"*{Path.GetExtension(fileName)}";
watcher.Changed += new FileSystemEventHandler(OnFileChanged);
watcher.EnableRaisingEvents = true;
}
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
if (e != null && e.FullPath != _fileName)
{
return;
}
var dic = new Dictionary<string, string>();
string text;
using (var fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var r = new StreamReader(fs))
{
text = r.ReadToEnd();
}
foreach (var line in text.Split('\n'))
{
var segs = line.Split('=');
dic.Add(segs[0].Trim(), segs[1].Trim());
}
_doc = dic;
}
public string Get(string key)
{
string val;
if (!_doc.TryGetValue(key, out val))
{
return null;
}
return val;
}
}
}
| using System.Collections.Generic;
using System.IO;
namespace Sir
{
public class IniConfiguration : IConfigurationProvider
{
private IDictionary<string, string> _doc;
private readonly string _fileName;
public IniConfiguration(string fileName)
{
_doc = new Dictionary<string, string>();
_fileName = Path.Combine(Directory.GetCurrentDirectory(), "sir.ini");
OnFileChanged(null, null);
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Directory.GetCurrentDirectory();
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.ini";
watcher.Changed += new FileSystemEventHandler(OnFileChanged);
watcher.EnableRaisingEvents = true;
}
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
var dic = new Dictionary<string, string>();
string text;
using (var fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var r = new StreamReader(fs))
{
text = r.ReadToEnd();
}
foreach (var line in text.Split('\n'))
{
var segs = line.Split('=');
dic.Add(segs[0].Trim(), segs[1].Trim());
}
_doc = dic;
}
public string Get(string key)
{
string val;
if (!_doc.TryGetValue(key, out val))
{
return null;
}
return val;
}
}
}
| mit | C# |
1013749a83365c54d7585e1a4289c54113754e52 | Change user id type to int | peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu-new,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu | osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomUser.cs | osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomUser.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using osu.Game.Users;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser>
{
public readonly int UserID;
public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle;
public User? User { get; set; }
public MultiplayerRoomUser(in int userId)
{
UserID = userId;
}
public bool Equals(MultiplayerRoomUser other)
{
if (ReferenceEquals(this, other)) return true;
return UserID == other.UserID;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((MultiplayerRoomUser)obj);
}
public override int GetHashCode() => UserID.GetHashCode();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using osu.Game.Users;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser>
{
public readonly long UserID;
public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle;
public User? User { get; set; }
public MultiplayerRoomUser(in int userId)
{
UserID = userId;
}
public bool Equals(MultiplayerRoomUser other)
{
if (ReferenceEquals(this, other)) return true;
return UserID == other.UserID;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((MultiplayerRoomUser)obj);
}
public override int GetHashCode() => UserID.GetHashCode();
}
}
| mit | C# |
c7db3be1af72e04aa1f258d6813e10783a9a439f | Implement Icon saving | Davipb/BluwolfIcons | BluwolfIcons/Icon.cs | BluwolfIcons/Icon.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
namespace BluwolfIcons
{
/// <summary>
/// Represents an icon image file.
/// </summary>
public class Icon
{
public IList<IIconImage> Images { get; } = new List<IIconImage>();
/// <summary>
/// Saves this icon to a specified file.
/// </summary>
/// <param name="filename">The file to save this icon to.</param>
public void Save(string filename)
{
using (var stream = File.Open(filename, FileMode.Create))
{
Save(stream);
}
}
/// <summary>
/// Saves this icon to a specified stream.
/// </summary>
/// <param name="stream">The stream to save this icon to.</param>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanSeek)
throw new ArgumentException("Stream must support seeking.", nameof(stream));
using (var writer = new BinaryWriter(stream))
{
// Reserved, always 0.
writer.Write((ushort)0);
// 1 for ICO, 2 for CUR
writer.Write((ushort)1);
writer.Write((ushort)Images.Count);
// We'll store images here with a stream position indicating where to write specific image data later
var pendingImages = new Dictionary<long, IIconImage>();
foreach (var image in Images)
{
writer.Write((byte)image.Image.Width);
writer.Write((byte)image.Image.Height);
// Number of colors in the palette. Since we always save the image ourselves (with no palette), hardcode this to 0 (No palette).
writer.Write((byte)0);
// Reserved, always 0.
writer.Write((byte)0);
// Color planes. Since we save the images ourselves, this is 1.
writer.Write((ushort)1);
writer.Write((ushort)Image.GetPixelFormatSize(image.Image.PixelFormat));
pendingImages.Add(writer.BaseStream.Position, image);
// Image size in bytes. Since we can't know this yet, fill it with zeros.
writer.Write(0u);
// Image data offset from the start of the file. Since we can't know this yet, fill it with zeros.
writer.Write(0u);
}
foreach (var image in pendingImages)
{
var data = image.Value.GetData();
var offset = (uint)writer.BaseStream.Position;
// We need to write specific image data now.
writer.BaseStream.Seek(image.Key, SeekOrigin.Begin);
writer.Write((uint)data.Length);
writer.Write(offset);
// Return to the proper stream location and write the image data.
writer.BaseStream.Seek(offset, SeekOrigin.Begin);
writer.Write(data);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
namespace BluwolfIcons
{
/// <summary>
/// Represents an icon image file.
/// </summary>
public class Icon
{
public IList<IIconImage> Images { get; } = new List<IIconImage>();
/// <summary>
/// Saves this icon to a specified file.
/// </summary>
/// <param name="filename">The file to save this icon to.</param>
public void Save(string filename)
{
throw new NotImplementedException();
}
/// <summary>
/// Saves this icon to a specified stream.
/// </summary>
/// <param name="stream">The stream to save this icon to.</param>
public void Save(Stream stream)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
ad53ababe89f49a2650a4bcd4eb5368052f9413f | Fix wrong default | NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu | osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyCursor.cs | osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyCursor.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
public class LegacyCursor : OsuCursorSprite
{
private bool spin;
public LegacyCursor()
{
Size = new Vector2(50);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
bool centre = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.CursorCentre)?.Value ?? true;
spin = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.CursorRotate)?.Value ?? true;
InternalChildren = new[]
{
ExpandTarget = new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursor"),
Anchor = Anchor.Centre,
Origin = centre ? Anchor.Centre : Anchor.TopLeft,
},
new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursormiddle"),
Anchor = Anchor.Centre,
Origin = centre ? Anchor.Centre : Anchor.TopLeft,
},
};
}
protected override void LoadComplete()
{
if (spin)
ExpandTarget.Spin(10000, RotationDirection.Clockwise);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
public class LegacyCursor : OsuCursorSprite
{
private bool spin;
public LegacyCursor()
{
Size = new Vector2(50);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
bool centre = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.CursorCentre)?.Value ?? false;
spin = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.CursorRotate)?.Value ?? true;
InternalChildren = new[]
{
ExpandTarget = new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursor"),
Anchor = Anchor.Centre,
Origin = centre ? Anchor.Centre : Anchor.TopLeft,
},
new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursormiddle"),
Anchor = Anchor.Centre,
Origin = centre ? Anchor.Centre : Anchor.TopLeft,
},
};
}
protected override void LoadComplete()
{
if (spin)
ExpandTarget.Spin(10000, RotationDirection.Clockwise);
}
}
}
| mit | C# |
414c59c54a00bcf8cc1ab6b6dfebbce04dbd6b4d | Raise priority to reduce benchmarking noise | EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an | PerfTest/Program.cs | PerfTest/Program.cs | using System;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Threading;
using AvsAnLib;
using AvsAnDemo;
namespace PerfTest
{
static class Program
{
static void Main() {
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
var benchdict = Dictionaries.LoadEnglishDictionary();
var borkedWords = benchdict.Select(w => new string(w.Reverse().ToArray())).ToArray();
long sum = 0;
var sw = Stopwatch.StartNew();
var _ = AvsAn.Query("example").Article;
var init = sw.Elapsed;
Console.WriteLine("initialization took " + init.TotalMilliseconds);
sw.Restart();
const int iters = 500;
for (var k = 0; k < iters; k++) {
foreach (var word in benchdict) {
sum += AvsAn.Query(word).Article == "an" ? 1 : 0;
}
foreach (var word in borkedWords) {
sum += AvsAn.Query(word).Article == "an" ? 1 : 0;
}
}
var duration = sw.Elapsed.TotalMilliseconds;
var clockrateMHz =
new ManagementObjectSearcher(new ObjectQuery("SELECT CurrentClockSpeed FROM Win32_Processor")).Get()
.Cast<ManagementObject>()
.Select(mo => Convert.ToDouble(mo["CurrentClockSpeed"]))
.Max();
Console.WriteLine(sum + " / " + benchdict.Length + " (" + (double)sum / benchdict.Length / iters / 2 + ") an rate.");
var microseconds = duration / (benchdict.Length + borkedWords.Length) / iters * 1000.0;
Console.WriteLine(microseconds * 1000.0 + " nanoseconds per lookup");
Console.WriteLine(clockrateMHz * microseconds + " cycles per lookup @ " + clockrateMHz + "MHz");
Console.WriteLine("took " + duration + "ms");
}
}
}
| using System;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Threading;
using AvsAnLib;
using AvsAnDemo;
namespace PerfTest
{
static class Program
{
static void Main() {
var benchdict = Dictionaries.LoadEnglishDictionary();
var borkedWords = benchdict.Select(w => new string(w.Reverse().ToArray())).ToArray();
long sum = 0;
var sw = Stopwatch.StartNew();
var _ = AvsAn.Query("example").Article;
var init = sw.Elapsed;
Console.WriteLine("initialization took " + init.TotalMilliseconds);
sw.Restart();
const int iters = 500;
for (var k = 0; k < iters; k++) {
foreach (var word in benchdict) {
sum += AvsAn.Query(word).Article == "an" ? 1 : 0;
}
foreach (var word in borkedWords) {
sum += AvsAn.Query(word).Article == "an" ? 1 : 0;
}
}
var duration = sw.Elapsed.TotalMilliseconds;
var clockrateMHz =
new ManagementObjectSearcher(new ObjectQuery("SELECT CurrentClockSpeed FROM Win32_Processor")).Get()
.Cast<ManagementObject>()
.Select(mo => Convert.ToDouble(mo["CurrentClockSpeed"]))
.Max();
Console.WriteLine(sum + " / " + benchdict.Length + " (" + (double)sum / benchdict.Length / iters / 2 + ") an rate.");
var microseconds = duration / (benchdict.Length + borkedWords.Length) / iters * 1000.0;
Console.WriteLine(microseconds * 1000.0 + " nanoseconds per lookup");
Console.WriteLine(clockrateMHz * microseconds + " cycles per lookup @ " + clockrateMHz + "MHz");
Console.WriteLine("took " + duration + "ms");
}
}
}
| apache-2.0 | C# |
cffb1a7352fcb934db7ca7785e34dd4474713856 | バージョンアップ (1.1.0) | cube-soft/Cube.Core,cube-soft/Cube.Core | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("Cube.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CubeSoft, Inc.")]
[assembly: AssemblyProduct("Cube.Core")]
[assembly: AssemblyCopyright("Copyright © 2010 CubeSoft, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("832ebcbe-dfa5-41e9-915e-9085c0dfd744")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [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;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("Cube.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CubeSoft, Inc.")]
[assembly: AssemblyProduct("Cube.Core")]
[assembly: AssemblyCopyright("Copyright © 2010 CubeSoft, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("832ebcbe-dfa5-41e9-915e-9085c0dfd744")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| apache-2.0 | C# |
3b3b9ee31bcef4cdda6cd5b7417d4117f8257f32 | Bump version | o11c/WebMConverter,Yuisbean/WebMConverter,nixxquality/WebMConverter | 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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.1.0")]
[assembly: AssemblyFileVersion("2.0.1.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("WebMConverter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebMConverter")]
[assembly: AssemblyCopyright("Copyright © 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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// 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# |
3b83b8b0fc568399999fba97bf5fe04c6ce70048 | Update version number for nuget | rlittletht/TCore.Settings | 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("TCore.Settings")]
[assembly: AssemblyDescription("Read and write settings, registry persisted")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TCore.Settings")]
[assembly: AssemblyCopyright("Copyright © 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("40e51aca-696f-46d0-bd22-344bd198d639")]
// 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("TCore.Settings")]
[assembly: AssemblyDescription("Read and write settings, registry persisted")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TCore.Settings")]
[assembly: AssemblyCopyright("Copyright © 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("40e51aca-696f-46d0-bd22-344bd198d639")]
// 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# |
88c15f9fd8519794a9b71d1a54a72ca5c65517e9 | add exists method | Mart-Bogdan/pubsub,upta/pubsub,ortrails/pubsub | PubSub/PubSubExtensions.cs | PubSub/PubSubExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PubSub
{
static public class PubSubExtensions
{
static private readonly Hub hub = new Hub();
static public bool Exists<T>( this object obj )
{
foreach ( var h in hub.handlers )
{
if ( h.Sender.Target.ToString() == obj.ToString() &&
typeof(T) == h.Type )
{
return true;
}
}
return false;
}
static public void Publish<T>( this object obj )
{
hub.Publish( obj, default( T ) );
}
static public void Publish<T>( this object obj, T data )
{
hub.Publish( obj, data );
}
static public void Subscribe<T>( this object obj, Action<T> handler )
{
hub.Subscribe( obj, handler );
}
static public void Unsubscribe( this object obj )
{
hub.Unsubscribe( obj );
}
static public void Unsubscribe<T>( this object obj )
{
hub.Unsubscribe( obj, (Action<T>) null );
}
static public void Unsubscribe<T>( this object obj, Action<T> handler )
{
hub.Unsubscribe( obj, handler );
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PubSub
{
static public class PubSubExtensions
{
static private readonly Hub hub = new Hub();
static public void Publish<T>( this object obj )
{
hub.Publish( obj, default( T ) );
}
static public void Publish<T>( this object obj, T data )
{
hub.Publish( obj, data );
}
static public void Subscribe<T>( this object obj, Action<T> handler )
{
hub.Subscribe( obj, handler );
}
static public void Unsubscribe( this object obj )
{
hub.Unsubscribe( obj );
}
static public void Unsubscribe<T>( this object obj )
{
hub.Unsubscribe( obj, (Action<T>) null );
}
static public void Unsubscribe<T>( this object obj, Action<T> handler )
{
hub.Unsubscribe( obj, handler );
}
}
}
| apache-2.0 | C# |
876e18c597a58320060b2020df0f89a2112de306 | Mark AccessDenied and UsedUp properties as obsolete - they're not used anywhere | TDaphneB/XeroAPI.Net,XeroAPI/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,jcvandan/XeroAPI.Net | source/XeroApi/OAuth/Utility/Storage/Basic/RequestToken.cs | source/XeroApi/OAuth/Utility/Storage/Basic/RequestToken.cs | #region License
// The MIT License
//
// Copyright (c) 2006-2008 DevDefined Limited.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using DevDefined.OAuth.Framework;
namespace DevDefined.OAuth.Storage.Basic
{
/// <summary>
/// Simple request token model, this provides information about a request token which has been issued, including
/// who it was issued to, if the token has been used up (a request token should only be presented once), and
/// the associated access token (if a user has granted access to a consumer i.e. given them access).
/// </summary>
public class RequestToken : TokenBase
{
[Obsolete]
public bool AccessDenied { get; set; }
[Obsolete]
public bool UsedUp { get; set; }
public AccessToken AccessToken { get; set; }
public string CallbackUrl { get; set; }
public string Verifier { get; set; }
public override string ToString()
{
string formattedToken = base.ToString();
formattedToken += "&" + Parameters.OAuth_Callback_Confirmed + "=true";
return formattedToken;
}
}
} | #region License
// The MIT License
//
// Copyright (c) 2006-2008 DevDefined Limited.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using DevDefined.OAuth.Framework;
namespace DevDefined.OAuth.Storage.Basic
{
/// <summary>
/// Simple request token model, this provides information about a request token which has been issued, including
/// who it was issued to, if the token has been used up (a request token should only be presented once), and
/// the associated access token (if a user has granted access to a consumer i.e. given them access).
/// </summary>
public class RequestToken : TokenBase
{
public bool AccessDenied { get; set; }
public bool UsedUp { get; set; }
public AccessToken AccessToken { get; set; }
public string CallbackUrl { get; set; }
public string Verifier { get; set; }
public override string ToString()
{
string formattedToken = base.ToString();
formattedToken += "&" + Parameters.OAuth_Callback_Confirmed + "=true";
return formattedToken;
}
}
} | mit | C# |
66d270fc28a9b7ff70452576819af9f9b05295ae | Remove locking code and make it possible to have a dummy history, by calling the parameterless constructor. | IvionSauce/MeidoBot | IvionSoft/History.cs | IvionSoft/History.cs | using System;
using System.Collections.Generic;
namespace IvionSoft
{
public class History<T>
{
public int Length { get; private set; }
HashSet<T> hashes;
Queue<T> queue;
public History()
{
Length = 0;
}
public History(int length) : this(length, null)
{}
public History(int length, IEqualityComparer<T> comparer)
{
if (length < 1)
throw new ArgumentException("Cannot be less than or equal to 0.", "length");
Length = length;
queue = new Queue<T>(length + 1);
if (comparer != null)
hashes = new HashSet<T>(comparer);
else
hashes = new HashSet<T>();
}
public bool Contains(T item)
{
if (Length > 0)
return hashes.Contains(item);
else
return false;
}
public bool Add(T item)
{
if (Length == 0)
return false;
bool added;
added = hashes.Add(item);
if (added)
{
queue.Enqueue(item);
if (queue.Count > Length)
{
T toRemove = queue.Dequeue();
hashes.Remove(toRemove);
}
}
return added;
}
}
} | using System;
using System.Collections.Generic;
namespace IvionSoft
{
public class History<T>
{
public int Length { get; private set; }
HashSet<T> hashes;
Queue<T> queue;
object _locker = new object();
public History(int length) : this(length, null)
{}
public History(int length, IEqualityComparer<T> comparer)
{
if (length < 1)
throw new ArgumentException("Must be 1 or larger", "length");
Length = length;
queue = new Queue<T>(length + 1);
if (comparer != null)
hashes = new HashSet<T>(comparer);
else
hashes = new HashSet<T>();
}
public bool Contains(T item)
{
return hashes.Contains(item);
}
public bool Add(T item)
{
bool added;
lock (_locker)
{
added = hashes.Add(item);
if (added)
{
queue.Enqueue(item);
if (queue.Count > Length)
{
T toRemove = queue.Dequeue();
hashes.Remove(toRemove);
}
}
}
return added;
}
}
} | bsd-2-clause | C# |
d8375e5fff5691c6fd4f871900d9094842d3738e | Remove Twitchie property | JokkeeZ/Twitchie | TwitchIrcChannel.cs | TwitchIrcChannel.cs | using System;
using System.Threading.Tasks;
namespace Twitchie2
{
public class TwitchIrcChannel
{
public string Name { get; }
public bool Joined { get; private set; }
public TwitchIrcChannel(string channel)
{
if (string.IsNullOrWhiteSpace(channel))
throw new ArgumentException("Invalid channel! Channel can not be null or whitespace.");
Name = channel[0] == '#' ? channel : '#' + channel;
}
public async Task SendMessageAsync(string message)
=> await Twitchie.Instance.ChatAsync(Name, message);
public async Task SendActionAsync(string action)
=> await Twitchie.Instance.ActionAsync(Name, action);
public async Task SendMentionAsync(string user, string message)
=> await Twitchie.Instance.MentionAsync(Name, user, message);
public async Task SendWhisperAsync(string user, string message)
=> await Twitchie.Instance.WhisperAsync(Name, user, message);
public async Task JoinAsync()
{
if (!Joined)
{
await Twitchie.Instance.SendAsync($"JOIN {Name}");
Joined = true;
}
}
public async Task PartAsync()
{
if (Joined)
{
await Twitchie.Instance.SendAsync($"PART {Name}");
Joined = false;
}
}
}
}
| using System;
using System.Threading.Tasks;
namespace Twitchie2
{
public class TwitchIrcChannel
{
public string Name { get; }
public bool Joined { get; private set; }
public Twitchie Instance => Twitchie.Instance;
public TwitchIrcChannel(string channel)
{
if (string.IsNullOrWhiteSpace(channel))
throw new ArgumentException("Invalid channel! Channel can not be null or whitespace.");
Name = channel[0] == '#' ? channel : '#' + channel;
}
public async Task SendMessageAsync(string message)
=> await Instance.ChatAsync(Name, message);
public async Task SendActionAsync(string action)
=> await Instance.ActionAsync(Name, action);
public async Task SendMentionAsync(string user, string message)
=> await Instance.MentionAsync(Name, user, message);
public async Task SendWhisperAsync(string user, string message)
=> await Instance.WhisperAsync(Name, user, message);
public async Task JoinAsync()
{
if (!Joined)
{
await Instance.SendAsync($"JOIN {Name}");
Joined = true;
}
}
public async Task PartAsync()
{
if (Joined)
{
await Instance.SendAsync($"PART {Name}");
Joined = false;
}
}
}
}
| mit | C# |
5f4a79cbef3ab021d5f9e5e06b1acd711a3a6e30 | Use proper highlighting. | jesterret/ReClass.NET,jesterret/ReClass.NET,KN4CK3R/ReClass.NET,KN4CK3R/ReClass.NET,KN4CK3R/ReClass.NET,jesterret/ReClass.NET | Nodes/BaseHexNode.cs | Nodes/BaseHexNode.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using ReClassNET.UI;
using ReClassNET.Util;
namespace ReClassNET.Nodes
{
public abstract class BaseHexNode : BaseNode
{
public static DateTime CurrentHighlightTime;
public static readonly TimeSpan HightlightDuration = TimeSpan.FromSeconds(1);
private static readonly Dictionary<IntPtr, ValueTypeWrapper<DateTime>> highlight = new Dictionary<IntPtr, ValueTypeWrapper<DateTime>>();
private readonly byte[] buffer;
protected BaseHexNode()
{
Contract.Ensures(buffer != null);
buffer = new byte[MemorySize];
}
protected int Draw(ViewInfo view, int x, int y, string text, int length)
{
Contract.Requires(view != null);
Contract.Requires(text != null);
if (IsHidden)
{
return DrawHidden(view, x, y);
}
AddSelection(view, x, y, view.Font.Height);
AddDelete(view, x, y);
AddTypeDrop(view, x, y);
x += TextPadding + 16;
x = AddAddressOffset(view, x, y);
if (view.Settings.ShowNodeText)
{
x = AddText(view, x, y, view.Settings.TextColor, HotSpot.NoneId, text);
}
view.Memory.ReadBytes(Offset, buffer);
var color = view.Settings.HexColor;
if (view.Settings.HighlightChangedValues)
{
var address = view.Address.Add(Offset);
ValueTypeWrapper<DateTime> until;
if (highlight.TryGetValue(address, out until))
{
if (until.Value >= CurrentHighlightTime)
{
color = view.Settings.HighlightColor;
if (view.Memory.HasChanged(Offset, MemorySize))
{
until.Value = CurrentHighlightTime.Add(HightlightDuration);
}
}
else
{
highlight.Remove(address);
}
}
else if (view.Memory.HasChanged(Offset, MemorySize))
{
highlight.Add(address, CurrentHighlightTime.Add(HightlightDuration));
color = view.Settings.HighlightColor;
}
}
for (var i = 0; i < length; ++i)
{
x = AddText(view, x, y, color, i, $"{buffer[i]:X02}") + view.Font.Width;
}
AddComment(view, x, y);
return y + view.Font.Height;
}
public override int CalculateHeight(ViewInfo view)
{
return IsHidden ? HiddenHeight : view.Font.Height;
}
/// <summary>Updates the node from the given spot. Sets the value of the selected byte.</summary>
/// <param name="spot">The spot.</param>
/// <param name="maxId">The highest spot id.</param>
public void Update(HotSpot spot, int maxId)
{
Contract.Requires(spot != null);
base.Update(spot);
if (spot.Id >= 0 && spot.Id < maxId)
{
byte val;
if (byte.TryParse(spot.Text, NumberStyles.HexNumber, null, out val))
{
spot.Memory.Process.WriteRemoteMemory(spot.Address + spot.Id, val);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using ReClassNET.UI;
namespace ReClassNET.Nodes
{
public abstract class BaseHexNode : BaseNode
{
private readonly byte[] buffer;
private DateTime highlightUntil;
private readonly Dictionary<IntPtr, Tuple<byte[], DateTime>> highlightHistory;
public static DateTime CurrentHighlightTime;
public static readonly TimeSpan HightlightDuration = TimeSpan.FromSeconds(1);
protected BaseHexNode()
{
Contract.Ensures(buffer != null);
buffer = new byte[MemorySize];
highlightHistory = new Dictionary<IntPtr, Tuple<byte[], DateTime>>();
}
protected int Draw(ViewInfo view, int x, int y, string text, int length)
{
Contract.Requires(view != null);
Contract.Requires(text != null);
if (IsHidden)
{
return DrawHidden(view, x, y);
}
AddSelection(view, x, y, view.Font.Height);
AddDelete(view, x, y);
AddTypeDrop(view, x, y);
x += TextPadding + 16;
x = AddAddressOffset(view, x, y);
if (view.Settings.ShowNodeText)
{
x = AddText(view, x, y, view.Settings.TextColor, HotSpot.NoneId, text);
}
view.Memory.ReadBytes(Offset, buffer);
var color = view.Settings.HighlightChangedValues && view.Memory.HasChanged(Offset, MemorySize)
? view.Settings.HighlightColor
: view.Settings.HexColor;
for (var i = 0; i < length; ++i)
{
x = AddText(view, x, y, color, i, $"{buffer[i]:X02}") + view.Font.Width;
}
AddComment(view, x, y);
return y + view.Font.Height;
}
public override int CalculateHeight(ViewInfo view)
{
return IsHidden ? HiddenHeight : view.Font.Height;
}
/// <summary>Updates the node from the given spot. Sets the value of the selected byte.</summary>
/// <param name="spot">The spot.</param>
/// <param name="maxId">The highest spot id.</param>
public void Update(HotSpot spot, int maxId)
{
Contract.Requires(spot != null);
base.Update(spot);
if (spot.Id >= 0 && spot.Id < maxId)
{
byte val;
if (byte.TryParse(spot.Text, NumberStyles.HexNumber, null, out val))
{
spot.Memory.Process.WriteRemoteMemory(spot.Address + spot.Id, val);
}
}
}
}
}
| mit | C# |
acbb6e7cfd8a63f23befe3b05605bf0cbb5cf63c | Add catch for ArgumentException | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web/Authentication/IdsContext.cs | src/SFA.DAS.EmployerUsers.Web/Authentication/IdsContext.cs | using System;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using NLog;
namespace SFA.DAS.EmployerUsers.Web.Authentication
{
public class IdsContext
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public static string CookieName => "IDS";
public static IdsContext ReadFrom(string data)
{
try
{
var unEncData = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(data)));
return JsonConvert.DeserializeObject<IdsContext>(unEncData);
}
catch (ArgumentException ex)
{
LogManager.GetCurrentClassLogger().Info(ex, ex.Message);
return new IdsContext();
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
return new IdsContext();
}
}
}
} | using System;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using NLog;
namespace SFA.DAS.EmployerUsers.Web.Authentication
{
public class IdsContext
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public static string CookieName => "IDS";
public static IdsContext ReadFrom(string data)
{
try
{
var unEncData = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(data)));
return JsonConvert.DeserializeObject<IdsContext>(unEncData);
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error(ex, ex.Message); ;
return new IdsContext();
}
}
}
} | mit | C# |
e43d98b98df5ae91e376c673c1a1355f32576fc7 | Fix RunDocker command | Sitecore/Sitecore-Instance-Manager | src/SIM.Pipelines/Install/Containers/RunDockerProcessor.cs | src/SIM.Pipelines/Install/Containers/RunDockerProcessor.cs | using JetBrains.Annotations;
using SIM.Pipelines.Processors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SIM.Pipelines.Install.Containers
{
public class RunDockerProcessor : Processor
{
protected virtual string Command => "docker-compose.exe up -d";
protected override void Process([NotNull] ProcessorArgs arguments)
{
InstallContainerArgs args = (InstallContainerArgs)arguments;
string strCmdText = $"/C cd \"{args.Destination}\"&{this.Command}";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.Arguments = strCmdText;
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.WaitForExit();
if (proc.ExitCode != 0)
{
throw new AggregateException($"Failed to run '{this.Command}'\n{proc.StandardError.ReadToEnd()}");
}
}
}
}
| using JetBrains.Annotations;
using SIM.Pipelines.Processors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SIM.Pipelines.Install.Containers
{
public class RunDockerProcessor : Processor
{
protected override void Process([NotNull] ProcessorArgs arguments)
{
InstallContainerArgs args = (InstallContainerArgs)arguments;
string strCmdText = $"/C cd \"{args.Destination}\"&docker.exe -detach";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.Arguments = strCmdText;
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.WaitForExit();
if (proc.ExitCode != 0)
{
throw new AggregateException($"Failed to run docker -detach\n{proc.StandardError.ReadToEnd()}");
}
}
}
}
| mit | C# |
fc48b69296aa56aec121416c6413249196dbf71f | add procedure status peck | ASOS/woodpecker | src/Woodpecker.Core/Sql/AzureSqlDmvGeoReplicationPecker.cs | src/Woodpecker.Core/Sql/AzureSqlDmvGeoReplicationPecker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Woodpecker.Core.Sql
{
public class AzureSqlDmvGeoReplicationPecker : AzureSqlDmvPeckerBase
{
private const string _query = @"
select @@servername [collection_server_name]
, db_name() [collection_database_name]
, getutcdate() [collection_time_utc]
, [partner_server] [secondary_server_name]
, [partner_database] [secondary_database_name]
, convert(datetime, [last_replication]) [last_replication]
, [last_replication]
, [replication_lag_sec]
, [replication_state_desc]
, [role_desc]
, [secondary_allow_connections_desc]
from sys.dm_geo_replication_link_status";
protected override string GetQuery()
{
return _query;
}
protected override IEnumerable<string> GetRowKeyFieldNames()
{
return new[] {"collection_server_name", "collection_database_name", "partner_server", "partner_database" };
}
protected override string GetUtcTimestampFieldName()
{
return "collection_time_utc";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Woodpecker.Core.Sql
{
public class AzureSqlDmvGeoReplicationPecker : AzureSqlDmvPeckerBase
{
private const string DatabaseGeoReplicationInlineSqlNotSoBad = @"
SELECT
GETUTCDATE() as collection_time_utc, -- datetime
@@SERVERNAME as server_name, -- string
DB_NAME() as database_name, -- string
CONCAT(@@SERVERNAME,'/',DB_NAME()) AS [full_name], -- string
partner_server AS sqldb_geo_partner_server, -- string
partner_database AS sqldb_geo_partner_database, -- string
CONCAT(partner_server,'/',partner_database) AS sqldb_geo_partner_full_name, -- string
replication_lag_sec AS sqldb_geo_lag_sec, -- int32
role_desc AS sqldb_geo_role_desc -- string
FROM sys.dm_geo_replication_link_status
";
protected override string GetQuery()
{
return DatabaseGeoReplicationInlineSqlNotSoBad;
}
protected override IEnumerable<string> GetRowKeyFieldNames()
{
return new string[0];
}
protected override string GetUtcTimestampFieldName()
{
return "collection_time_utc";
}
}
}
| mit | C# |
ff6a0d325de86183f102bfb10f6e203381e6d87c | Move assignment to initialiser | mmanela/diffplex,mmanela/diffplex,mmanela/diffplex,mmanela/diffplex | DiffPlex/DiffBuilder/Model/DiffPiece.cs | DiffPlex/DiffBuilder/Model/DiffPiece.cs | using System.Collections.Generic;
namespace DiffPlex.DiffBuilder.Model
{
public enum ChangeType
{
Unchanged,
Deleted,
Inserted,
Imaginary,
Modified
}
public class DiffPiece
{
public ChangeType Type { get; set; }
public int? Position { get; set; }
public string Text { get; set; }
public List<DiffPiece> SubPieces { get; set; } = new List<DiffPiece>();
public DiffPiece(string text, ChangeType type, int? position = null)
{
Text = text;
Position = position;
Type = type;
}
public DiffPiece()
: this(null, ChangeType.Imaginary)
{
}
}
} | using System.Collections.Generic;
namespace DiffPlex.DiffBuilder.Model
{
public enum ChangeType
{
Unchanged,
Deleted,
Inserted,
Imaginary,
Modified
}
public class DiffPiece
{
public ChangeType Type { get; set; }
public int? Position { get; set; }
public string Text { get; set; }
public List<DiffPiece> SubPieces { get; set; }
public DiffPiece(string text, ChangeType type, int? position = null)
{
Text = text;
Position = position;
Type = type;
SubPieces = new List<DiffPiece>();
}
public DiffPiece()
: this(null, ChangeType.Imaginary)
{
}
}
} | apache-2.0 | C# |
90161e43fdef433a9fbbaa9a95f4772bf21b693e | add dcterms as a builtin simple type | Colectica/cogs | Cogs.Common/CogsTypes.cs | Cogs.Common/CogsTypes.cs | // Copyright (c) 2017 Colectica. All rights reserved
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
namespace Cogs.Common
{
public static class CogsTypes
{
public static readonly string[] SimpleTypeNames =
{
"boolean",
"string",
"boolean",
"decimal",
"float",
"double",
"duration",
"dateTime",
"time",
"date",
"gYearMonth",
"gYear",
"gMonthDay",
"gDay",
"gMonth",
"anyURI",
"language",
"nonPositiveInteger",
"negativeInteger",
"long",
"int",
"nonNegativeInteger",
"unsignedLong",
"positiveInteger",
"cogsDate",
"dcTerms"
};
public static readonly string CogsDate = "cogsDate";
public static readonly string[] BuiltinTypeNames =
{
"This",
"Any"
};
public static readonly string[] BuiltinPropertyNames =
{
"Language",
"DcTerms"
};
}
}
| // Copyright (c) 2017 Colectica. All rights reserved
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
namespace Cogs.Common
{
public static class CogsTypes
{
public static readonly string[] SimpleTypeNames =
{
"boolean",
"string",
"boolean",
"decimal",
"float",
"double",
"duration",
"dateTime",
"time",
"date",
"gYearMonth",
"gYear",
"gMonthDay",
"gDay",
"gMonth",
"anyURI",
"language",
"int",
"nonPositiveInteger",
"negativeInteger",
"long",
"int",
"nonNegativeInteger",
"unsignedLong",
"positiveInteger",
"cogsDate"
};
public static readonly string CogsDate = "cogsDate";
public static readonly string[] BuiltinTypeNames =
{
"This",
"Any"
};
public static readonly string[] BuiltinPropertyNames =
{
"Language",
"DcTerms"
};
}
}
| mit | C# |
d6d18d189ba6ebc9b414e2504e0376daee2bc39f | Bump version to 1.1.0.0 | courtneyklatt/Mjolnir,hudl/Mjolnir | Hudl.Mjolnir/Properties/AssemblyInfo.cs | Hudl.Mjolnir/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("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Isolation library for protecting against cascading failure.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 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)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// 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: AssemblyInformationalVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyVersion("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("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Isolation library for protecting against cascading failure.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 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)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// 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: AssemblyInformationalVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
| apache-2.0 | C# |
743bdb015598a4c8be9fbf174736c942b1205227 | Update UIBlurView.cs | Clancey/iOSHelpers | iOSHelpers/UIBlurView.cs | iOSHelpers/UIBlurView.cs | using System;
using UIKit;
namespace iOSHelpers
{
public class UIBlurView : UIView
{
UIView blurView;
public UIBlurView()
{
var blur = UIBlurEffect.FromStyle(UIBlurEffectStyle.Dark);
blurView = new UIVisualEffectView(blur);
Add(blurView);
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (blurView != null)
blurView.Frame = Bounds;
}
}
}
| using System;
using UIKit;
namespace iOSHelpers
{
public class UIBlurView : UIView
{
UIToolbar toolbar;
public UIBlurView ()
{
BackgroundColor = UIColor.Clear;
Add(toolbar = new UIToolbar {
Translucent =true,
});
}
public UIBarStyle Style
{
get{ return toolbar.BarStyle; }
set{ toolbar.BarStyle = value; }
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
toolbar.Frame = Bounds;
}
}
}
| apache-2.0 | C# |
76327d6dc8d6c7155fbc5ecd4d5eb562828e02cb | add ac replace test function | tupunco/Tup.AhoCorasick | Tup.AhoCorasick/Program.cs | Tup.AhoCorasick/Program.cs | using System;
using System.Text;
namespace Tup.AhoCorasick
{
class Program
{
static void Main(string[] args)
{
var search = new AhoCorasickSearch();
var keywords = new string[] { "he", "she", "his", "hers" };
search.Build(keywords);
searchTest(search);
searchTest(search);
replaceTest2();
replaceTest3();
Console.Read();
}
private static void searchTest(AhoCorasickSearch search)
{
var res = search.SearchAll("ushers");
Console.WriteLine(res);
}
private static void replaceTest(AhoCorasickSearch search)
{
var text = "ushers";
var res = search.Replace(text, "-");
Console.WriteLine(res);
text = "shersx";
res = search.Replace(text, "-");
Console.WriteLine(res);
text = "her";
res = search.Replace(text, "-");
Console.WriteLine(res);
text = "she";
res = search.Replace(text, "-");
Console.WriteLine(res);
}
private static void replaceTest2()
{
var search = new AhoCorasickSearch();
var keywords = new string[] { "伟大","特色主义","公园" };
search.Build(keywords);
var text = "从这里建设伟大的特色主义主题公园";
var res = search.Replace(text, "-");
Console.WriteLine(res);
text = "主题公园";
res = search.Replace(text, "-");
Console.WriteLine(res);
text = "伟大的特色主义主题公园";
res = search.Replace(text, "-");
Console.WriteLine(res);
text = "伟大特色主义公园";
res = search.Replace(text, "-");
Console.WriteLine(res);
}
private static void replaceTest3()
{
var search = new AhoCorasickSearch();
var keywords = new string[] { "一边", "刀锋", "烽火" };
search.Build(keywords);
var text = "一边烽火, 一边烽火天";
var res = search.Replace(text, "-");
Console.WriteLine(res);
text = "一边刀锋很犀利";
res = search.Replace(text, "-");
Console.WriteLine(res);
}
}
}
| using System;
namespace Tup.AhoCorasick
{
class Program
{
static void Main(string[] args)
{
var search = new AhoCorasickSearch();
var keywords = new string[] { "he", "she", "his", "hers" };
search.Build(keywords);
var res = search.SearchAll("ushers" );
Console.Write(res);
Console.Read();
}
}
}
| mit | C# |
44501952c29fdb0733ff19ce7da4bf063ddb19c8 | Add Default static to b2FixtureDef | TukekeSoft/CocosSharp,netonjm/CocosSharp,MSylvia/CocosSharp,mono/CocosSharp,haithemaraissia/CocosSharp,TukekeSoft/CocosSharp,mono/CocosSharp,mono/cocos2d-xna,MSylvia/CocosSharp,zmaruo/CocosSharp,zmaruo/CocosSharp,netonjm/CocosSharp,hig-ag/CocosSharp,mono/cocos2d-xna,hig-ag/CocosSharp,haithemaraissia/CocosSharp | box2d/Dynamics/b2FixtureDef.cs | box2d/Dynamics/b2FixtureDef.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Box2D.Collision.Shapes;
using Box2D.Collision;
namespace Box2D.Dynamics
{
/// This proxy is used internally to connect fixtures to the broad-phase.
public class b2FixtureProxy
{
public b2AABB aabb;
public b2Fixture fixture;
public int childIndex;
public int proxyId;
}
/// <summary>
/// A fixture definition is used to create a fixture. This class defines an
/// abstract fixture definition. You can reuse fixture definitions safely.
/// </summary>
public struct b2FixtureDef
{
public static b2FixtureDef Default = b2FixtureDef.Create();
public void Defaults()
{
shape = null;
userData = null;
friction = 0.2f;
restitution = 0.0f;
density = 0.0f;
isSensor = false;
}
public static b2FixtureDef Create()
{
b2FixtureDef d = new b2FixtureDef();
d.Defaults();
return (d);
}
/// The shape, this must be set. The shape will be cloned, so you
/// can create the shape on the stack.
public b2Shape shape;
/// Use this to store application specific fixture data.
public object userData;
/// The friction coefficient, usually in the range [0,1].
public float friction;
/// The restitution (elasticity) usually in the range [0,1].
public float restitution;
/// The density, usually in kg/m^2.
public float density;
/// A sensor shape collects contact information but never generates a collision
/// response.
public bool isSensor;
/// Contact filtering data.
public b2Filter filter;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Box2D.Collision.Shapes;
using Box2D.Collision;
namespace Box2D.Dynamics
{
/// This proxy is used internally to connect fixtures to the broad-phase.
public class b2FixtureProxy
{
public b2AABB aabb;
public b2Fixture fixture;
public int childIndex;
public int proxyId;
}
/// <summary>
/// A fixture definition is used to create a fixture. This class defines an
/// abstract fixture definition. You can reuse fixture definitions safely.
/// </summary>
public struct b2FixtureDef
{
public void Defaults()
{
shape = null;
userData = null;
friction = 0.2f;
restitution = 0.0f;
density = 0.0f;
isSensor = false;
}
public static b2FixtureDef Create()
{
b2FixtureDef d = new b2FixtureDef();
d.Defaults();
return (d);
}
/// The shape, this must be set. The shape will be cloned, so you
/// can create the shape on the stack.
public b2Shape shape;
/// Use this to store application specific fixture data.
public object userData;
/// The friction coefficient, usually in the range [0,1].
public float friction;
/// The restitution (elasticity) usually in the range [0,1].
public float restitution;
/// The density, usually in kg/m^2.
public float density;
/// A sensor shape collects contact information but never generates a collision
/// response.
public bool isSensor;
/// Contact filtering data.
public b2Filter filter;
}
}
| mit | C# |
c441c2cebfca44007e370561a521b485bb8d95ac | Implement ObjectPool object getter. | dimixar/audio-controller-unity | AudioController/Assets/Source/ObjectPool.cs | AudioController/Assets/Source/ObjectPool.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
#region Public fields
public List<PrefabBasedPool> pools;
#endregion
#region Public methods and properties
public GameObject GetFreeObject(GameObject prefab = null)
{
if (prefab == null)
return null;
PrefabBasedPool pool = pools.Find((x) => {
return x.prefab == prefab;
});
if (pool != null)
return pool.GetFreeObject();
pool = new PrefabBasedPool(prefab);
GameObject parent = new GameObject();
parent.transform.parent = this.gameObject.transform;
pool.parent = parent.transform;
pools.Add(pool);
return pool.GetFreeObject();
}
#endregion
#region Monobehaviour methods
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
void Awake()
{
pools = new List<PrefabBasedPool>();
}
#endregion
}
[System.Serializable]
public class PrefabBasedPool
{
public PrefabBasedPool(GameObject prefab)
{
pool = new List<GameObject>();
this.prefab = prefab;
}
public GameObject prefab;
public List<GameObject> pool;
/// <summary>
/// Where pooled objects will reside.
/// </summary>
public Transform parent;
public GameObject GetFreeObject()
{
GameObject freeObj = pool.Find((x) => {
var poolable = x.GetComponent<IPoolable>();
return poolable.IsFree();
});
if (freeObj != null)
return freeObj;
var obj = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity, parent);
pool.Add(obj);
return obj;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
#region Public fields
public List<PrefabBasedPool> pools;
#endregion
#region Public methods and properties
public AudioObject GetFreeAudioObject(GameObject prefab = null)
{
if (prefab == null)
return null;
return null;
}
#endregion
#region Monobehaviour methods
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
void Awake()
{
pools = new List<PrefabBasedPool>();
}
#endregion
}
[System.Serializable]
public class PrefabBasedPool
{
public PrefabBasedPool(GameObject prefab)
{
pool = new List<GameObject>();
this.prefab = prefab;
}
public GameObject prefab;
public List<GameObject> pool;
/// <summary>
/// Where pooled objects will reside.
/// </summary>
public Transform parent;
public GameObject GetFreeObject()
{
GameObject freeObj = pool.Find((x) => {
var poolable = x.GetComponent<IPoolable>();
return poolable.IsFree();
});
if (freeObj != null)
return freeObj;
var obj = GameObject.Instantiate(prefab, parent);
pool.Add(obj);
return obj;
}
}
| mit | C# |
53c5706259993805d903efd031d0173bfb6d7126 | bump version | vevix/DigitalOcean.API | DigitalOcean.API/Properties/AssemblyInfo.cs | DigitalOcean.API/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("DigitalOcean.API")]
[assembly: AssemblyDescription(".NET wrapper of the DigitalOcean API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Thomas McNiven")]
[assembly: AssemblyProduct("DigitalOcean.API")]
[assembly: AssemblyCopyright("Copyright © 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("7057d92f-7d8e-4221-a9c3-c13e07799fdb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1")]
[assembly: AssemblyFileVersion("0.1.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("DigitalOcean.API")]
[assembly: AssemblyDescription(".NET wrapper of the DigitalOcean API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Thomas McNiven")]
[assembly: AssemblyProduct("DigitalOcean.API")]
[assembly: AssemblyCopyright("Copyright © 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("7057d92f-7d8e-4221-a9c3-c13e07799fdb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")] | mit | C# |
08a71b4c6ffadfa711be63a5caa2e95cfa8ef498 | Clarify Address property types and removed getters/setters | goshippo/shippo-csharp-client | Shippo/Address.cs | Shippo/Address.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Shippo {
[JsonObject (MemberSerialization.OptIn)]
public class Address : ShippoId {
[JsonProperty (PropertyName = "object_state")]
public string ObjectState;
[JsonProperty (PropertyName = "object_purpose")]
public string ObjectPurpose;
[JsonProperty (PropertyName = "object_source")]
public string ObjectSource;
[JsonProperty (PropertyName = "object_created")]
public DateTime? ObjectCreated;
[JsonProperty (PropertyName = "object_updated")]
public DateTime? ObjectUpdated;
[JsonProperty (PropertyName = "object_owner")]
public string ObjectOwner;
[JsonProperty (PropertyName = "name")]
public string Name;
[JsonProperty (PropertyName = "company")]
public string Company;
[JsonProperty (PropertyName = "street1")]
public string Street1;
[JsonProperty (PropertyName = "street_no")]
public string StreetNo;
[JsonProperty (PropertyName = "street2")]
public string Street2;
[JsonProperty (PropertyName = "street3")]
public string Street3;
[JsonProperty (PropertyName = "city")]
public string City;
[JsonProperty (PropertyName = "state")]
public string State;
[JsonProperty (PropertyName = "zip")]
public string Zip;
[JsonProperty (PropertyName = "country")]
public string Country;
[JsonProperty (PropertyName = "phone")]
public string Phone;
[JsonProperty (PropertyName = "email")]
public string Email;
[JsonProperty (PropertyName = "is_residential")]
public bool? IsResidential;
[JsonProperty (PropertyName = "validate")]
public bool? Validate;
[JsonProperty (PropertyName = "metadata")]
public string Metadata;
[JsonProperty (PropertyName = "test")]
public bool Test;
[JsonProperty (PropertyName = "messages")]
public List<string> Messages;
}
}
| using System;
using Newtonsoft.Json;
namespace Shippo {
[JsonObject (MemberSerialization.OptIn)]
public class Address : ShippoId {
[JsonProperty (PropertyName = "object_state")]
public object ObjectState { get; set; }
[JsonProperty (PropertyName = "object_purpose")]
public object ObjectPurpose { get; set; }
[JsonProperty (PropertyName = "object_source")]
public object ObjectSource { get; set; }
[JsonProperty (PropertyName = "object_created")]
public object ObjectCreated { get; set; }
[JsonProperty (PropertyName = "object_updated")]
public object ObjectUpdated { get; set; }
[JsonProperty (PropertyName = "object_owner")]
public object ObjectOwner { get; set; }
[JsonProperty (PropertyName = "name")]
public object Name { get; set; }
[JsonProperty (PropertyName = "company")]
public object Company { get; set; }
[JsonProperty (PropertyName = "street1")]
public object Street1 { get; set; }
[JsonProperty (PropertyName = "street_no")]
public object StreetNo { get; set; }
[JsonProperty (PropertyName = "street2")]
public object Street2 { get; set; }
[JsonProperty (PropertyName = "city")]
public object City { get; set; }
[JsonProperty (PropertyName = "state")]
public object State { get; set; }
[JsonProperty (PropertyName = "zip")]
public object Zip { get; set; }
[JsonProperty (PropertyName = "country")]
public object Country { get; set; }
[JsonProperty (PropertyName = "phone")]
public object Phone { get; set; }
[JsonProperty (PropertyName = "email")]
public object Email { get; set; }
[JsonProperty (PropertyName = "ip")]
public object IP { get; set; }
[JsonProperty (PropertyName = "metadata")]
public object Metadata { get; set; }
[JsonProperty (PropertyName = "is_residential")]
public object IsResidential { get; set; }
}
}
| apache-2.0 | C# |
23f5e042836287501ae8752b0217119f95f0a369 | Add test | sakapon/Samples-2017 | DrawingSample/BitmapScaleConsole/Program.cs | DrawingSample/BitmapScaleConsole/Program.cs | using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
namespace BitmapScaleConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press [Enter] key to start.");
Console.ReadLine();
ResizeImageTest_Drawing();
ResizeImageTest_Windows();
}
static void ResizeImageTest_Drawing()
{
var now = $"{DateTime.Now:yyyyMMdd-HHmmss}";
Directory.CreateDirectory(now);
using (var bitmap = BitmapHelper.GetScreenBitmap(200, 100, 1080, 720))
{
bitmap.Save($@"{now}\Original.png", ImageFormat.Png);
bitmap.Save($@"{now}\Original.jpg", ImageFormat.Jpeg);
var modes = Enum.GetValues(typeof(InterpolationMode))
.Cast<InterpolationMode>()
.Where(m => m != InterpolationMode.Invalid);
foreach (var mode in modes)
{
using (var resized = BitmapHelper.ResizeImage(bitmap, bitmap.Width / 2, bitmap.Height / 2, mode))
{
resized.Save($@"{now}\{mode}.jpg", ImageFormat.Jpeg);
}
}
}
}
static void ResizeImageTest_Windows()
{
var now = $"{DateTime.Now:yyyyMMdd-HHmmss}";
Directory.CreateDirectory(now);
using (var bitmap = BitmapHelper.GetScreenBitmap(200, 100, 1080, 720))
using (var memory = BitmapHelper.ToStream(bitmap))
{
bitmap.Save($@"{now}\Original.png", ImageFormat.Png);
bitmap.Save($@"{now}\Original.jpg", ImageFormat.Jpeg);
var source = System.Windows.Media.Imaging.BitmapFrame.Create(memory);
var resized = BitmapHelper2.ResizeImage(source, bitmap.Width / 2, bitmap.Height / 2);
BitmapHelper2.SaveImage($@"{now}\Resized.png", resized);
BitmapHelper2.SaveImage($@"{now}\Resized.jpg", resized);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
namespace BitmapScaleConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press [Enter] key to start.");
Console.ReadLine();
var now = $"{DateTime.Now:yyyyMMdd-HHmmss}";
Directory.CreateDirectory(now);
using (var bitmap = BitmapHelper.GetScreenBitmap(200, 100, 1080, 720))
{
bitmap.Save($@"{now}\Original.png", ImageFormat.Png);
bitmap.Save($@"{now}\Original.jpg", ImageFormat.Jpeg);
var modes = Enum.GetValues(typeof(InterpolationMode))
.Cast<InterpolationMode>()
.Where(m => m != InterpolationMode.Invalid);
foreach (var mode in modes)
{
using (var resized = BitmapHelper.ResizeImage(bitmap, bitmap.Width / 2, bitmap.Height / 2, mode))
{
resized.Save($@"{now}\{mode}.jpg", ImageFormat.Jpeg);
}
}
}
}
}
}
| mit | C# |
6d5d48e95b4853efeb5ee30beb1805860fd5e3e7 | Add check constraint and method to output constraint name with no schema for use by rename operations | RivetDB/Rivet,RivetDB/Rivet,RivetDB/Rivet | Source/ConstraintName.cs | Source/ConstraintName.cs | using System;
using System.Collections.Generic;
namespace Rivet
{
public enum ConstraintType
{
Default,
PrimaryKey,
ForeignKey,
Check,
Index,
Unique
}
public class ConstraintName
{
public ConstraintName(string schemaName, string tableName, string[] columnName, ConstraintType type)
{
SchemaName = schemaName;
TableName = tableName;
ColumnName = new List<string>(columnName ?? new string[0]);
Type = type;
Name = ToString();
}
public string SchemaName { get; private set; }
public string TableName { get; private set; }
public List<string> ColumnName { get; private set; }
public ConstraintType Type { get; private set; }
public string Name { get; private set; }
public new string ToString()
{
string keyname;
switch(Type)
{
case ConstraintType.Default:
keyname = "DF";
break;
case ConstraintType.PrimaryKey:
keyname = "PK";
break;
case ConstraintType.Check:
keyname = "CK";
break;
case ConstraintType.Index:
keyname = "IX";
break;
case ConstraintType.Unique:
keyname = "UQ";
break;
default:
keyname = "DF";
break;
}
var columnClause = string.Join("_", ColumnName.ToArray());
var name = string.Format("{0}_{1}_{2}_{3}", keyname, SchemaName, TableName, columnClause);
if (string.Equals(SchemaName, "dbo", StringComparison.InvariantCultureIgnoreCase))
{
name = string.Format("{0}_{1}_{2}", keyname, TableName, columnClause);
}
return name;
}
public string ToNoSchemaString()
{
string keyname;
switch (Type)
{
case ConstraintType.Default:
keyname = "DF";
break;
case ConstraintType.PrimaryKey:
keyname = "PK";
break;
case ConstraintType.Check:
keyname = "CK";
break;
case ConstraintType.Index:
keyname = "IX";
break;
case ConstraintType.Unique:
keyname = "UQ";
break;
default:
keyname = "DF";
break;
}
var columnClause = string.Join("_", ColumnName.ToArray());
var name = string.Format("{0}_{1}_{2}", keyname, TableName, columnClause);
return name;
}
}
} | using System;
using System.Collections.Generic;
namespace Rivet
{
public enum ConstraintType
{
Default,
PrimaryKey,
ForeignKey,
Index,
Unique
}
public class ConstraintName
{
public ConstraintName(string schemaName, string tableName, string[] columnName, ConstraintType type)
{
SchemaName = schemaName;
TableName = tableName;
ColumnName = new List<string>(columnName ?? new string[0]);
Type = type;
Name = ToString();
}
public string SchemaName { get; private set; }
public string TableName { get; private set; }
public List<string> ColumnName { get; private set; }
public ConstraintType Type { get; private set; }
public string Name { get; private set; }
public new string ToString()
{
string keyname;
switch(Type)
{
case ConstraintType.Default:
keyname = "DF";
break;
case ConstraintType.PrimaryKey:
keyname = "PK";
break;
case ConstraintType.Index:
keyname = "IX";
break;
case ConstraintType.Unique:
keyname = "UQ";
break;
default:
keyname = "DF";
break;
}
var columnClause = string.Join("_", ColumnName.ToArray());
var name = string.Format("{0}_{1}_{2}_{3}", keyname, SchemaName, TableName, columnClause);
if (string.Equals(SchemaName, "dbo", StringComparison.InvariantCultureIgnoreCase))
{
name = string.Format("{0}_{1}_{2}", keyname, TableName, columnClause);
}
return name;
}
}
} | apache-2.0 | C# |
30b27522cba792f96ebfcd26dd6ee05d3f3fba1f | change name!! | pekarb103/blog- | MvcApplication1/MvcApplication1/Views/Shared/_Layout.cshtml | MvcApplication1/MvcApplication1/Views/Shared/_Layout.cshtml | <!doctype html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="~/Content/css/reset.css">
<link rel="stylesheet" href="~/Content/css/style.css">
</head>
<body>
<div class="wrap">
<div class="left-column">
<div class="wrap-avatar">
<img src="~/Content/images/avatar.png" alt="" />
<h2>Hilko Andrey!!</h2>
</div>
<div class="menu">
<ul>
<li><a href="#">Latest Post</a></li>
<li><a href="#">Archive</a></li>
<li><a href="#">About Me</a></li>
</ul>
</div>
<div class="search-form">
<input type="text" />
<button></button>
</div>
@Html.Action("Recent", "Article")
@Html.Action("Recent", "Comment")
</div>
<div class="right-column">
@RenderBody()
</div>
</div>
</body>
</html> | <!doctype html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="~/Content/css/reset.css">
<link rel="stylesheet" href="~/Content/css/style.css">
</head>
<body>
<div class="wrap">
<div class="left-column">
<div class="wrap-avatar">
<img src="~/Content/images/avatar.png" alt="" />
<h2>Hilko Andrey</h2>
</div>
<div class="menu">
<ul>
<li><a href="#">Latest Post</a></li>
<li><a href="#">Archive</a></li>
<li><a href="#">About Me</a></li>
</ul>
</div>
<div class="search-form">
<input type="text" />
<button></button>
</div>
@Html.Action("Recent", "Article")
@Html.Action("Recent", "Comment")
</div>
<div class="right-column">
@RenderBody()
</div>
</div>
</body>
</html> | mit | C# |
147656cacc52c9d6c6c6b2553098de15594ecd40 | Fix assembly version | andyshao/Hangfire.Ninject,HangfireIO/Hangfire.Ninject | HangFire.Ninject/Properties/AssemblyInfo.cs | HangFire.Ninject/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("HangFire.Ninject")]
[assembly: AssemblyDescription("Ninject IoC Container support for HangFire (background job system for ASP.NET applications).")]
[assembly: AssemblyProduct("HangFire")]
[assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")]
// 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("91f25a4e-65e7-4d9c-886e-33a6c82b14c4")]
[assembly: AssemblyInformationalVersion("1.0.0-alpha1")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HangFire.Ninject")]
[assembly: AssemblyDescription("Ninject IoC Container support for HangFire (background job system for ASP.NET applications).")]
[assembly: AssemblyProduct("HangFire")]
[assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")]
// 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("91f25a4e-65e7-4d9c-886e-33a6c82b14c4")]
[assembly: AssemblyVersion("1.0.0-alpha1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
e6746b4de4a89b2cc89708d3bab9883eb5a4ca12 | Fix admin menu in integrations test | mgmccarthy/allReady,gitChuckD/allReady,GProulx/allReady,bcbeatty/allReady,jonatwabash/allReady,HTBox/allReady,jonatwabash/allReady,jonatwabash/allReady,c0g1t8/allReady,GProulx/allReady,HamidMosalla/allReady,VishalMadhvani/allReady,MisterJames/allReady,BillWagner/allReady,BillWagner/allReady,binaryjanitor/allReady,dpaquette/allReady,MisterJames/allReady,binaryjanitor/allReady,anobleperson/allReady,binaryjanitor/allReady,binaryjanitor/allReady,VishalMadhvani/allReady,dpaquette/allReady,dpaquette/allReady,HTBox/allReady,mgmccarthy/allReady,GProulx/allReady,mgmccarthy/allReady,MisterJames/allReady,mgmccarthy/allReady,bcbeatty/allReady,VishalMadhvani/allReady,jonatwabash/allReady,dpaquette/allReady,MisterJames/allReady,gitChuckD/allReady,bcbeatty/allReady,gitChuckD/allReady,stevejgordon/allReady,stevejgordon/allReady,anobleperson/allReady,c0g1t8/allReady,anobleperson/allReady,BillWagner/allReady,c0g1t8/allReady,stevejgordon/allReady,gitChuckD/allReady,VishalMadhvani/allReady,BillWagner/allReady,stevejgordon/allReady,anobleperson/allReady,HTBox/allReady,GProulx/allReady,HTBox/allReady,c0g1t8/allReady,HamidMosalla/allReady,bcbeatty/allReady,HamidMosalla/allReady,HamidMosalla/allReady | AllReadyApp/Web-App/AllReady/Views/Shared/_AdminNavigationPartial.cshtml | AllReadyApp/Web-App/AllReady/Views/Shared/_AdminNavigationPartial.cshtml | @using AllReady.Security
@if (User.IsUserType(UserType.SiteAdmin) || User.IsUserType(UserType.OrgAdmin))
{
var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)ViewContext.ActionDescriptor;
var areaName = descriptor.RouteValues["area"]; // there must be a better way to get the area name!
var controllerName = descriptor.ControllerName;
var isAdmin = areaName == "Admin";
<li class="dropdown dropdown-admin @(isAdmin? "active":"")">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Admin <span class="caret"></span>
</a>
<ul class="dropdown-menu">
@if (User.IsUserType(UserType.SiteAdmin))
{
<li @(isAdmin && controllerName == "Organization" ? " class=active" : "")><a asp-area="Admin" asp-controller="Organization" asp-action="Index">Organizations</a></li>
}
<li @(isAdmin && controllerName == "Campaign" ? " class=active" : "")><a asp-area="Admin" asp-controller="Campaign" asp-action="Index">Campaigns</a></li>
@if (User.IsUserType(UserType.OrgAdmin))
{
<li @(isAdmin && controllerName == "UnlinkedRequest" ? " class=active" : "")><a asp-area="Admin" asp-controller="UnlinkedRequest" asp-action="List">Unlinked Requests</a></li>
}
<li @(isAdmin && controllerName == "Skill" ? " class=active" : "")><a asp-area="Admin" asp-controller="Skill" asp-action="Index">Skills</a></li>
@if (User.IsUserType(UserType.SiteAdmin))
{
<li @(isAdmin && controllerName == "Site" ? " class=active" : "")><a asp-area="Admin" asp-controller="Site" asp-action="Index">Site Admin</a></li>
}
<li @(isAdmin && controllerName == "Import" ? " class=active" : "")><a asp-area="Admin" asp-controller="Import" asp-action="Index">Import Data</a></li>
</ul>
</li>
} | @using AllReady.Security
@if (User.IsUserType(UserType.SiteAdmin) || User.IsUserType(UserType.OrgAdmin))
{
var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)ViewContext.ActionDescriptor;
var areaName = descriptor.RouteValues["area"]; // there must be a better way to get the area name!
var controllerName = descriptor.ControllerName;
var isAdmin = areaName == "Admin";
<li class="dropdown @(isAdmin? "active":"")">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
Admin <span class="caret"></span>
</a>
<ul class="dropdown-menu">
@if (User.IsUserType(UserType.SiteAdmin))
{
<li @(isAdmin && controllerName == "Organization" ? " class=active" : "")><a asp-area="Admin" asp-controller="Organization" asp-action="Index">Organizations</a></li>
}
<li @(isAdmin && controllerName == "Campaign" ? " class=active" : "")><a asp-area="Admin" asp-controller="Campaign" asp-action="Index">Campaigns</a></li>
@if (User.IsUserType(UserType.OrgAdmin))
{
<li @(isAdmin && controllerName == "UnlinkedRequest" ? " class=active" : "")><a asp-area="Admin" asp-controller="UnlinkedRequest" asp-action="List">Unlinked Requests</a></li>
}
<li @(isAdmin && controllerName == "Skill" ? " class=active" : "")><a asp-area="Admin" asp-controller="Skill" asp-action="Index">Skills</a></li>
@if (User.IsUserType(UserType.SiteAdmin))
{
<li @(isAdmin && controllerName == "Site" ? " class=active" : "")><a asp-area="Admin" asp-controller="Site" asp-action="Index">Site Admin</a></li>
}
<li @(isAdmin && controllerName == "Import" ? " class=active" : "")><a asp-area="Admin" asp-controller="Import" asp-action="Index">Import Data</a></li>
</ul>
</li>
} | mit | C# |
dd925a3f0cd3d8e2462c3c82c3ad21e367521e6e | add _startingState (readability++) | miraimann/Knuth-Morris-Pratt | KnuthMorrisPratt/KnuthMorrisPratt/Finder.cs | KnuthMorrisPratt/KnuthMorrisPratt/Finder.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace KnuthMorrisPratt
{
internal class Finder<T> : IFinder<T>
{
private readonly int[,] _dfa;
private readonly Dictionary<T, int> _abc;
private readonly int _startingState = 0;
private readonly int _finalState;
public Finder(IEnumerable<T> word)
{
var pattern = word as T[] ?? word.ToArray();
_finalState = pattern.Length;
_abc = pattern.Distinct()
.Select((v, i) => new { v, i })
.ToDictionary(o => o.v, o => o.i);
_dfa = new int[_abc.Count, pattern.Length];
_dfa[0, 0] = 1;
for (int i = 0, j = 1; j < pattern.Length; i = _dfa[_abc[pattern[j++]], i])
{
for (int c = 0; c < _abc.Count; c++)
_dfa[c, j] = _dfa[c, i];
_dfa[_abc[pattern[j]], j] = j + 1;
}
}
public int FindIn(IEnumerable<T> sequence)
{
throw new NotImplementedException();
}
public int FindLastIn(IEnumerable<T> sequence)
{
throw new NotImplementedException();
}
public IEnumerable<int> FindAllIn(IEnumerable<T> sequence)
{
throw new NotImplementedException();
}
public bool ExistsIn(IEnumerable<T> sequence)
{
using (var e = sequence.Select(c => _abc[c])
.GetEnumerator())
{
int state = _startingState;
while (e.MoveNext())
{
state = _dfa[e.Current, state];
if (state == _finalState) return true;
}
return false;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace KnuthMorrisPratt
{
internal class Finder<T> : IFinder<T>
{
private readonly int[,] _dfa;
private readonly Dictionary<T, int> _abc;
private readonly int _finalState;
public Finder(IEnumerable<T> word)
{
var pattern = word as T[] ?? word.ToArray();
_finalState = pattern.Length;
_abc = pattern.Distinct()
.Select((v, i) => new { v, i })
.ToDictionary(o => o.v, o => o.i);
_dfa = new int[_abc.Count, pattern.Length];
_dfa[0, 0] = 1;
for (int i = 0, j = 1; j < pattern.Length; i = _dfa[_abc[pattern[j++]], i])
{
for (int c = 0; c < _abc.Count; c++)
_dfa[c, j] = _dfa[c, i];
_dfa[_abc[pattern[j]], j] = j + 1;
}
}
public int FindIn(IEnumerable<T> sequence)
{
throw new NotImplementedException();
}
public int FindLastIn(IEnumerable<T> sequence)
{
throw new NotImplementedException();
}
public IEnumerable<int> FindAllIn(IEnumerable<T> sequence)
{
throw new NotImplementedException();
}
public bool ExistsIn(IEnumerable<T> sequence)
{
using (var e = sequence.Select(c => _abc[c])
.GetEnumerator())
{
int state = 0;
while (e.MoveNext())
{
state = _dfa[e.Current, state];
if (state == _finalState) return true;
}
return false;
}
}
}
}
| mit | C# |
994db55b6d542c187d96d6905552f79d2a352d6a | Simplify check conditionals | ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu | osu.Game.Rulesets.Catch/UI/DrawableCatchRuleset.cs | osu.Game.Rulesets.Catch/UI/DrawableCatchRuleset.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Input;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Input.Handlers;
using osu.Game.Replays;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.Replays;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Catch.UI
{
public class DrawableCatchRuleset : DrawableScrollingRuleset<CatchHitObject>
{
protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Constant;
protected override bool UserScrollSpeedAdjustment => false;
public DrawableCatchRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
Direction.Value = ScrollingDirection.Down;
TimeRange.Value = IBeatmapDifficultyInfo.DifficultyRange(beatmap.Difficulty.ApproachRate, 1800, 1200, 450);
}
[BackgroundDependencyLoader]
private void load()
{
// With relax mod, input maps directly to x position and left/right buttons are not used.
if (!Mods.Any(m => m is ModRelax))
KeyBindingInputManager.Add(new CatchTouchInputMapper());
}
protected override ReplayInputHandler CreateReplayInputHandler(Replay replay) => new CatchFramedReplayInputHandler(replay);
protected override ReplayRecorder CreateReplayRecorder(Score score) => new CatchReplayRecorder(score, (CatchPlayfield)Playfield);
protected override Playfield CreatePlayfield() => new CatchPlayfield(Beatmap.Difficulty);
public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new CatchPlayfieldAdjustmentContainer();
protected override PassThroughInputManager CreateInputManager() => new CatchInputManager(Ruleset.RulesetInfo);
public override DrawableHitObject<CatchHitObject> CreateDrawableRepresentation(CatchHitObject h) => null;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Input;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Input.Handlers;
using osu.Game.Replays;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.Replays;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Catch.UI
{
public class DrawableCatchRuleset : DrawableScrollingRuleset<CatchHitObject>
{
protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Constant;
protected override bool UserScrollSpeedAdjustment => false;
private readonly bool showMobileMapper = true;
public DrawableCatchRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
// Check if mods have RelaxMod instance
if (mods != null && mods.OfType<ModRelax>().Any())
showMobileMapper = false;
Direction.Value = ScrollingDirection.Down;
TimeRange.Value = IBeatmapDifficultyInfo.DifficultyRange(beatmap.Difficulty.ApproachRate, 1800, 1200, 450);
}
[BackgroundDependencyLoader]
private void load()
{
if (showMobileMapper)
KeyBindingInputManager.Add(new CatchTouchInputMapper());
}
protected override ReplayInputHandler CreateReplayInputHandler(Replay replay) => new CatchFramedReplayInputHandler(replay);
protected override ReplayRecorder CreateReplayRecorder(Score score) => new CatchReplayRecorder(score, (CatchPlayfield)Playfield);
protected override Playfield CreatePlayfield() => new CatchPlayfield(Beatmap.Difficulty);
public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new CatchPlayfieldAdjustmentContainer();
protected override PassThroughInputManager CreateInputManager() => new CatchInputManager(Ruleset.RulesetInfo);
public override DrawableHitObject<CatchHitObject> CreateDrawableRepresentation(CatchHitObject h) => null;
}
}
| mit | C# |
940409bb96247ca700739fa6999b0cc15fbc37e1 | Add BgpHeaderLength | mstrother/BmpListener | BmpListener/Constants.cs | BmpListener/Constants.cs | namespace BmpListener
{
static class Constants
{
public const int BgpHeaderLength = 19;
public const int BmpCommonHeaderLength = 6;
public const int BmpPerPeerHeaderLength = 42;
}
}
| namespace BmpListener
{
static class Constants
{
public const int BmpCommonHeaderLength = 6;
public const int BmpPerPeerHeaderLength = 42;
}
}
| mit | C# |
1ade17b0c0ab69d515b53e07ff0492a904c66a3b | put some ifs on the next line | nunit/nunit,nunit/nunit,mjedrzejek/nunit,mjedrzejek/nunit | src/NUnitFramework/framework/Internal/AwaitAdapter.cs | src/NUnitFramework/framework/Internal/AwaitAdapter.cs | // Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Adapts various styles of asynchronous waiting to a common API.
/// </summary>
internal abstract class AwaitAdapter
{
public abstract bool IsCompleted { get; }
public abstract void OnCompleted(Action action);
public abstract void BlockUntilCompleted();
public abstract object GetResult();
public static bool IsAwaitable(Type awaitableType)
{
return
CSharpPatternBasedAwaitAdapter.IsAwaitable(awaitableType)
|| FSharpAsyncAwaitAdapter.IsAwaitable(awaitableType);
}
public static Type GetResultType(Type awaitableType)
{
return
CSharpPatternBasedAwaitAdapter.GetResultType(awaitableType)
?? FSharpAsyncAwaitAdapter.GetResultType(awaitableType);
}
public static AwaitAdapter FromAwaitable(object awaitable)
{
if (awaitable == null)
throw new InvalidOperationException("A null reference cannot be awaited.");
// TaskAwaitAdapter is more efficient because it can rely on Task’s
// special quality of blocking until complete in GetResult.
// As long as the pattern-based adapters are reflection-based, this
// is much more efficient as well.
if (awaitable is System.Threading.Tasks.Task task)
return TaskAwaitAdapter.Create(task);
// Await all the (C# and F#) things
var adapter =
CSharpPatternBasedAwaitAdapter.TryCreate(awaitable)
?? FSharpAsyncAwaitAdapter.TryCreate(awaitable);
if (adapter != null)
return adapter;
throw new NotSupportedException("NUnit can only await objects which follow the C# specification for awaitable expressions.");
}
}
}
| // Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Adapts various styles of asynchronous waiting to a common API.
/// </summary>
internal abstract class AwaitAdapter
{
public abstract bool IsCompleted { get; }
public abstract void OnCompleted(Action action);
public abstract void BlockUntilCompleted();
public abstract object GetResult();
public static bool IsAwaitable(Type awaitableType)
{
return
CSharpPatternBasedAwaitAdapter.IsAwaitable(awaitableType)
|| FSharpAsyncAwaitAdapter.IsAwaitable(awaitableType);
}
public static Type GetResultType(Type awaitableType)
{
return
CSharpPatternBasedAwaitAdapter.GetResultType(awaitableType)
?? FSharpAsyncAwaitAdapter.GetResultType(awaitableType);
}
public static AwaitAdapter FromAwaitable(object awaitable)
{
if (awaitable == null)
throw new InvalidOperationException("A null reference cannot be awaited.");
// TaskAwaitAdapter is more efficient because it can rely on Task’s
// special quality of blocking until complete in GetResult.
// As long as the pattern-based adapters are reflection-based, this
// is much more efficient as well.
if (awaitable is System.Threading.Tasks.Task task) return TaskAwaitAdapter.Create(task);
// Await all the (C# and F#) things
var adapter =
CSharpPatternBasedAwaitAdapter.TryCreate(awaitable)
?? FSharpAsyncAwaitAdapter.TryCreate(awaitable);
if (adapter != null) return adapter;
throw new NotSupportedException("NUnit can only await objects which follow the C# specification for awaitable expressions.");
}
}
}
| mit | C# |
d4b35d236c240ca3e90fcb6c4ff31531a4930497 | Support module def in module function | Desolath/Confuserex,Desolath/ConfuserEx3,timnboys/ConfuserEx,yeaicc/ConfuserEx,engdata/ConfuserEx | Confuser.Core/Project/Patterns/ModuleFunction.cs | Confuser.Core/Project/Patterns/ModuleFunction.cs | using System;
using dnlib.DotNet;
namespace Confuser.Core.Project.Patterns {
/// <summary>
/// A function that compare the module of definition.
/// </summary>
public class ModuleFunction : PatternFunction {
internal const string FnName = "module";
/// <inheritdoc />
public override string Name {
get { return FnName; }
}
/// <inheritdoc />
public override int ArgumentCount {
get { return 1; }
}
/// <inheritdoc />
public override object Evaluate(IDnlibDef definition) {
if (!(definition is IOwnerModule) && !(definition is IModule))
return false;
object name = Arguments[0].Evaluate(definition);
if (definition is IModule)
return ((IModule)definition).Name == name.ToString();
return ((IOwnerModule)definition).Module.Name == name.ToString();
}
}
} | using System;
using dnlib.DotNet;
namespace Confuser.Core.Project.Patterns {
/// <summary>
/// A function that compare the module of definition.
/// </summary>
public class ModuleFunction : PatternFunction {
internal const string FnName = "module";
/// <inheritdoc />
public override string Name {
get { return FnName; }
}
/// <inheritdoc />
public override int ArgumentCount {
get { return 1; }
}
/// <inheritdoc />
public override object Evaluate(IDnlibDef definition) {
if (!(definition is IOwnerModule))
return false;
object name = Arguments[0].Evaluate(definition);
return ((IOwnerModule)definition).Module.Name == name.ToString();
}
}
} | mit | C# |
eb34fb5e38adbdeea486e4cfcbb7655234074de9 | fix multiply wind | fanmingfei/HitTMBigTree | Assets/Scripts/EnemyMovement.cs | Assets/Scripts/EnemyMovement.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class EnemyMovement : MonoBehaviour {
GameObject[] players;
UnityEngine.AI.NavMeshAgent nav;
public float maxDistance = 20f;
public float frozenTime = 5f;
public bool isFrozen = false;
public GameObject windPrefab;
private float frozenDuration = 0;
private GameObject wind;
void Awake ()
{
nav = GetComponent <UnityEngine.AI.NavMeshAgent> ();
GetComponent<Animator>().SetFloat("Speed", 1.0f);
}
void Update ()
{
if (frozenDuration > 0.2)
frozenDuration -= Time.deltaTime;
else
isFrozen = false;
players = GameObject.FindGameObjectsWithTag ("Player");
GameObject player = players[0];
float minValue = 1000000f;;
for(int i = 0; i < players.Length; i++)
{
Vector3 diff = players [i].transform.position - transform.position;
if(diff.sqrMagnitude < minValue)
{
minValue = diff.sqrMagnitude;
player = players [i];
}
}
nav.SetDestination (player.transform.position);
if (minValue > Mathf.Pow(maxDistance, 2))
{
GetComponent<Animator>().SetFloat("Speed", 0.0f);
nav.Stop ();
return;
}
if(isFrozen == false)
nav.Resume ();
if(Input.GetKeyDown(KeyCode.M))
{
StopAnimator ();
}
}
public void StopAnimator()
{
GetComponent<Animator> ().speed = 0;
nav.Stop ();
if(isFrozen == false)
{
wind = Instantiate (windPrefab, transform);
wind.transform.localPosition = Vector3.zero;
}
frozenDuration = 5f;
isFrozen = true;
Invoke ("ResumeAnimator", frozenTime);
}
public void ResumeAnimator()
{
if (isFrozen)
return;
Destroy (wind);
GetComponent<Animator> ().speed = 1f;
nav.Resume ();
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class EnemyMovement : MonoBehaviour {
GameObject[] players;
UnityEngine.AI.NavMeshAgent nav;
public float maxDistance = 20f;
public float frozenTime = 5f;
public bool isFrozen = false;
public GameObject windPrefab;
private float frozenDuration = 0;
private GameObject wind;
void Awake ()
{
nav = GetComponent <UnityEngine.AI.NavMeshAgent> ();
GetComponent<Animator>().SetFloat("Speed", 1.0f);
}
void Update ()
{
if (frozenDuration > 0.2)
frozenDuration -= Time.deltaTime;
else
isFrozen = false;
players = GameObject.FindGameObjectsWithTag ("Player");
GameObject player = players[0];
float minValue = 1000000f;;
for(int i = 0; i < players.Length; i++)
{
Vector3 diff = players [i].transform.position - transform.position;
if(diff.sqrMagnitude < minValue)
{
minValue = diff.sqrMagnitude;
player = players [i];
}
}
nav.SetDestination (player.transform.position);
if (minValue > Mathf.Pow(maxDistance, 2))
{
GetComponent<Animator>().SetFloat("Speed", 0.0f);
nav.Stop ();
return;
}
if(isFrozen == false)
nav.Resume ();
if(Input.GetKeyDown(KeyCode.M))
{
StopAnimator ();
}
}
public void StopAnimator()
{
GetComponent<Animator> ().speed = 0;
nav.Stop ();
wind = Instantiate (windPrefab, transform);
wind.transform.localPosition = Vector3.zero;
frozenDuration = 5f;
isFrozen = true;
Invoke ("ResumeAnimator", frozenTime);
}
public void ResumeAnimator()
{
if (isFrozen)
return;
Destroy (wind);
GetComponent<Animator> ().speed = 1f;
nav.Resume ();
}
}
| mpl-2.0 | C# |
52d747cf410cecf9dcbbc1b7884a4044b453d72e | convert UIViewAnimationCurve to UIViewAnimationOptions | nervevau2/monotouch-samples,W3SS/monotouch-samples,andypaul/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,nelzomal/monotouch-samples,hongnguyenpro/monotouch-samples,kingyond/monotouch-samples,haithemaraissia/monotouch-samples,haithemaraissia/monotouch-samples,kingyond/monotouch-samples,YOTOV-LIMITED/monotouch-samples,iFreedive/monotouch-samples,kingyond/monotouch-samples,iFreedive/monotouch-samples,YOTOV-LIMITED/monotouch-samples,YOTOV-LIMITED/monotouch-samples,xamarin/monotouch-samples,a9upam/monotouch-samples,W3SS/monotouch-samples,peteryule/monotouch-samples,albertoms/monotouch-samples,robinlaide/monotouch-samples,markradacz/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,albertoms/monotouch-samples,nervevau2/monotouch-samples,xamarin/monotouch-samples,nelzomal/monotouch-samples,albertoms/monotouch-samples,davidrynn/monotouch-samples,nervevau2/monotouch-samples,davidrynn/monotouch-samples,sakthivelnagarajan/monotouch-samples,haithemaraissia/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,peteryule/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,labdogg1003/monotouch-samples,robinlaide/monotouch-samples,hongnguyenpro/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,markradacz/monotouch-samples,robinlaide/monotouch-samples,hongnguyenpro/monotouch-samples,hongnguyenpro/monotouch-samples,markradacz/monotouch-samples,W3SS/monotouch-samples,robinlaide/monotouch-samples,a9upam/monotouch-samples,iFreedive/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,davidrynn/monotouch-samples,sakthivelnagarajan/monotouch-samples,sakthivelnagarajan/monotouch-samples | Chat/Chat/ChatViewController.cs | Chat/Chat/ChatViewController.cs | using System;
using System.Drawing;
using UIKit;
using Foundation;
using CoreGraphics;
namespace Chat
{
public partial class ChatViewController : UIViewController
{
NSObject willShowToken;
NSObject willHideToken;
public ChatViewController (IntPtr handle)
: base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
willShowToken = UIKeyboard.Notifications.ObserveWillShow (KeyboardWillShowHandler);
willHideToken = UIKeyboard.Notifications.ObserveWillHide (KeyboardWillHideHandler);
}
void KeyboardWillShowHandler (object sender, UIKeyboardEventArgs e)
{
UpdateButtomLayoutConstraint (e);
}
void KeyboardWillHideHandler (object sender, UIKeyboardEventArgs e)
{
UpdateButtomLayoutConstraint (e);
}
void UpdateButtomLayoutConstraint(UIKeyboardEventArgs e)
{
BottomConstraint.Constant = View.Bounds.GetMaxY () - e.FrameEnd.GetMinY ();
UIViewAnimationCurve curve = e.AnimationCurve;
UIView.Animate (e.AnimationDuration, 0, ConvertToAnimationOptions(e.AnimationCurve), ()=> {
View.LayoutIfNeeded ();
}, null);
}
UIViewAnimationOptions ConvertToAnimationOptions(UIViewAnimationCurve curve)
{
// Looks like a hack. But it is correct.
// UIViewAnimationCurve and UIViewAnimationOptions are shifted by 16 bits
return (UIViewAnimationOptions)((int)curve << 16);
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
willShowToken.Dispose ();
willHideToken.Dispose ();
}
}
} | using System;
using System.Drawing;
using UIKit;
using Foundation;
using CoreGraphics;
namespace Chat
{
public partial class ChatViewController : UIViewController
{
NSObject willShowToken;
NSObject willHideToken;
public ChatViewController (IntPtr handle)
: base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
willShowToken = UIKeyboard.Notifications.ObserveWillShow (KeyboardWillShowHandler);
willHideToken = UIKeyboard.Notifications.ObserveWillHide (KeyboardWillHideHandler);
}
void KeyboardWillShowHandler (object sender, UIKeyboardEventArgs e)
{
UpdateButtomLayoutConstraint (e);
}
void KeyboardWillHideHandler (object sender, UIKeyboardEventArgs e)
{
UpdateButtomLayoutConstraint (e);
}
void UpdateButtomLayoutConstraint(UIKeyboardEventArgs e)
{
BottomConstraint.Constant = View.Bounds.GetMaxY () - e.FrameEnd.GetMinY ();
View.LayoutIfNeeded ();
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
willShowToken.Dispose ();
willHideToken.Dispose ();
}
}
} | mit | C# |
e0ba1ddf58b73f8b6bfd86d01e1929352d1a904a | Add helpers for saving in Library and Library/Caches | stampsy/Stampsy.ImageSource | Destinations/FileDestination.cs | Destinations/FileDestination.cs | using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Stampsy.ImageSource
{
public class FileDestination : IDestination<FileRequest>
{
public static FileDestination InLibrary (params string [] folders)
{
var folder = Path.Combine (new [] { "..", "Library" }.Concat (folders).ToArray ());
Directory.CreateDirectory (folder);
return new FileDestination (folder);
}
public static FileDestination InLibraryCaches (params string [] folders)
{
return InLibrary (new [] { "Caches" }.Concat (folders).ToArray ());
}
public string Folder { get; private set; }
public FileDestination (string folder)
{
Folder = folder;
}
public FileRequest CreateRequest (IDescription description)
{
var url = description.Url;
var filename = ComputeHash (url) + description.Extension;
return new FileRequest (description) {
Filename = Path.Combine (Folder, filename)
};
}
static string ComputeHash (Uri url)
{
string hash;
using (var sha1 = new SHA1CryptoServiceProvider ()) {
var bytes = Encoding.ASCII.GetBytes (url.ToString ());
hash = BitConverter.ToString (sha1.ComputeHash (bytes));
}
return hash.Replace ("-", string.Empty).ToLower ();
}
}
}
| using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Stampsy.ImageSource
{
public class FileDestination : IDestination<FileRequest>
{
public string Folder { get; private set; }
public FileDestination (string folder)
{
Folder = folder;
}
public FileRequest CreateRequest (IDescription description)
{
var url = description.Url;
var filename = ComputeHash (url) + description.Extension;
return new FileRequest (description) {
Filename = Path.Combine (Folder, filename)
};
}
static string ComputeHash (Uri url)
{
string hash;
using (var sha1 = new SHA1CryptoServiceProvider ()) {
var bytes = Encoding.ASCII.GetBytes (url.ToString ());
hash = BitConverter.ToString (sha1.ComputeHash (bytes));
}
return hash.Replace ("-", string.Empty).ToLower ();
}
}
}
| mit | C# |
227ec96f569c50d37eeb7496a9edf86b1d2b8e0e | Enable editing of ImageTextCell | l8s/Eto,PowerOfCode/Eto,l8s/Eto,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1 | Source/Eto.Platform.Gtk/Forms/Cells/ImageTextCellHandler.cs | Source/Eto.Platform.Gtk/Forms/Cells/ImageTextCellHandler.cs | using System;
using Eto.Forms;
using Eto.Drawing;
using Eto.Platform.GtkSharp.Drawing;
namespace Eto.Platform.GtkSharp.Forms.Controls
{
public class ImageTextCellHandler : CellHandler<Gtk.CellRendererText, ImageTextCell>, IImageTextCell
{
Gtk.CellRendererPixbuf imageCell;
int imageDataIndex;
int textDataIndex;
public ImageTextCellHandler ()
{
imageCell = new Gtk.CellRendererPixbuf ();
Control = new Gtk.CellRendererText ();
this.Control.Edited += delegate(object o, Gtk.EditedArgs args) {
SetValue (args.Path, args.NewText);
};
}
public override void AddCells (Gtk.TreeViewColumn column)
{
column.PackStart (imageCell, false);
column.PackStart (Control, true);
}
protected override void BindCell (ref int dataIndex)
{
Column.ClearAttributes (Control);
SetColumnMap (dataIndex);
imageDataIndex = dataIndex;
Column.AddAttribute (imageCell, "pixbuf", dataIndex++);
SetColumnMap (dataIndex);
textDataIndex = dataIndex;
Column.AddAttribute (Control, "text", dataIndex++);
}
public override void SetEditable (Gtk.TreeViewColumn column, bool editable)
{
this.Control.Editable = editable;
}
public override void SetValue (object dataItem, object value)
{
if (Widget.TextBinding != null) {
Widget.TextBinding.SetValue (dataItem, value as string);
}
}
public override GLib.Value GetValue (object item, int column)
{
if (column == imageDataIndex) {
if (Widget.ImageBinding != null) {
var ret = Widget.ImageBinding.GetValue (item);
var image = ret as Image;
if (image != null)
return new GLib.Value (((IGtkPixbuf)image.Handler).GetPixbuf (new Size (16, 16)));
}
return new GLib.Value ((Gdk.Pixbuf)null);
} else if (column == textDataIndex) {
var ret = Widget.TextBinding.GetValue (item);
if (ret != null)
return new GLib.Value (Convert.ToString (ret));
}
return new GLib.Value ((string)null);
}
public override void AttachEvent (string handler)
{
switch (handler) {
case GridView.EndCellEditEvent:
Control.Edited += (sender, e) => {
Source.EndCellEditing (new Gtk.TreePath (e.Path), this.ColumnIndex);
};
break;
default:
base.AttachEvent (handler);
break;
}
}
}
}
| using System;
using Eto.Forms;
using Eto.Drawing;
using Eto.Platform.GtkSharp.Drawing;
namespace Eto.Platform.GtkSharp.Forms.Controls
{
public class ImageTextCellHandler : CellHandler<Gtk.CellRendererText, ImageTextCell>, IImageTextCell
{
Gtk.CellRendererPixbuf imageCell;
int imageDataIndex;
int textDataIndex;
public ImageTextCellHandler ()
{
imageCell = new Gtk.CellRendererPixbuf ();
Control = new Gtk.CellRendererText ();
}
public override void AddCells (Gtk.TreeViewColumn column)
{
column.PackStart (imageCell, false);
column.PackStart (Control, true);
}
protected override void BindCell (ref int dataIndex)
{
Column.ClearAttributes (Control);
SetColumnMap (dataIndex);
imageDataIndex = dataIndex;
Column.AddAttribute (imageCell, "pixbuf", dataIndex++);
SetColumnMap (dataIndex);
textDataIndex = dataIndex;
Column.AddAttribute (Control, "text", dataIndex++);
}
public override void SetEditable (Gtk.TreeViewColumn column, bool editable)
{
}
public override void SetValue (object dataItem, object value)
{
// can't set
}
public override GLib.Value GetValue (object item, int column)
{
if (column == imageDataIndex) {
if (Widget.ImageBinding != null) {
var ret = Widget.ImageBinding.GetValue (item);
var image = ret as Image;
if (image != null)
return new GLib.Value(((IGtkPixbuf)image.Handler).GetPixbuf (new Size (16, 16)));
}
return new GLib.Value((Gdk.Pixbuf)null);
}
else if (column == textDataIndex) {
var ret = Widget.TextBinding.GetValue (item);
if (ret != null)
return new GLib.Value (Convert.ToString (ret));
}
return new GLib.Value((string)null);
}
public override void AttachEvent (string handler)
{
switch (handler) {
case GridView.EndCellEditEvent:
// no editing here
break;
default:
base.AttachEvent (handler);
break;
}
}
}
}
| bsd-3-clause | C# |
d69558fcbb2261bd74b0d6bd71bd07b87f4701fd | Add missing properties to CustomsInfo.cs | EasyPost/easypost-csharp,dmmatson/easypost-csharp,EasyPost/easypost-csharp,jmalatia/easypost-csharp,kendallb/easypost-async-csharp | EasyPost/CustomsInfo.cs | EasyPost/CustomsInfo.cs | using EasyPost;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyPost {
public class CustomsInfo : IResource {
public string id { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string contents_type { get; set; }
public string contents_explanation { get; set; }
public string customs_certify { get; set; }
public string customs_signer { get; set; }
public string eel_pfc { get; set; }
public string non_delivery_option { get; set; }
public string restriction_type { get; set; }
public string restriction_comments { get; set; }
public List<CustomsItem> customs_items { get; set; }
public string mode { get; set; }
private static Client client = new Client();
/// <summary>
/// Retrieve a CustomsInfo from its id.
/// </summary>
/// <param name="id">String representing a CustomsInfo. Starts with "cstinfo_".</param>
/// <returns>EasyPost.CustomsInfo instance.</returns>
public static CustomsInfo Retrieve(string id) {
Request request = new Request("customs_infos/{id}");
request.AddUrlSegment("id", id);
return client.Execute<CustomsInfo>(request);
}
/// <summary>
/// Create a CustomsInfo.
/// </summary>
/// <param name="parameters">
/// Dictionary containing parameters to create the customs info with. Valid pairs:
/// * {"customs_certify", bool}
/// * {"customs_signer", string}
/// * {"contents_type", string}
/// * {"contents_explanation", string}
/// * {"restriction_type", string}
/// * {"eel_pfc", string}
/// * {"custom_items", Dictionary<string, object>} -- Can contain the key "id" or all keys required to create a CustomsItem.
/// All invalid keys will be ignored.
/// </param>
/// <returns>EasyPost.CustomsInfo instance.</returns>
public static CustomsInfo Create(IDictionary<string, object> parameters) {
Request request = new Request("customs_infos", Method.POST);
request.addBody(parameters, "customs_info");
return client.Execute<CustomsInfo>(request);
}
}
}
| using EasyPost;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyPost {
public class CustomsInfo : IResource {
public string id { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string contents_explanation { get; set; }
public string customs_certify { get; set; }
public string customs_signer { get; set; }
public string eel_pfc { get; set; }
public string non_delivery_option { get; set; }
public string restriction_type { get; set; }
public List<CustomsItem> customs_items { get; set; }
public string mode { get; set; }
private static Client client = new Client();
/// <summary>
/// Retrieve a CustomsInfo from its id.
/// </summary>
/// <param name="id">String representing a CustomsInfo. Starts with "cstinfo_".</param>
/// <returns>EasyPost.CustomsInfo instance.</returns>
public static CustomsInfo Retrieve(string id) {
Request request = new Request("customs_infos/{id}");
request.AddUrlSegment("id", id);
return client.Execute<CustomsInfo>(request);
}
/// <summary>
/// Create a CustomsInfo.
/// </summary>
/// <param name="parameters">
/// Dictionary containing parameters to create the customs info with. Valid pairs:
/// * {"customs_certify", bool}
/// * {"customs_signer", string}
/// * {"contents_type", string}
/// * {"contents_explanation", string}
/// * {"restriction_type", string}
/// * {"eel_pfc", string}
/// * {"custom_items", Dictionary<string, object>} -- Can contain the key "id" or all keys required to create a CustomsItem.
/// All invalid keys will be ignored.
/// </param>
/// <returns>EasyPost.CustomsInfo instance.</returns>
public static CustomsInfo Create(IDictionary<string, object> parameters) {
Request request = new Request("customs_infos", Method.POST);
request.addBody(parameters, "customs_info");
return client.Execute<CustomsInfo>(request);
}
}
}
| mit | C# |
cac11af516356dcc97b73299c7340e150bf96cb0 | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.OpenSavePidlMRU/ValuesOut.cs | RegistryPlugin.OpenSavePidlMRU/ValuesOut.cs | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.OpenSavePidlMRU
{
public class ValuesOut:IValueOut
{
public ValuesOut(string ext, string absolutePath, string details, string valueName, int mruPosition,
DateTimeOffset? openedOn)
{
Extension = ext;
AbsolutePath = absolutePath;
Details = details;
ValueName = valueName;
MruPosition = mruPosition;
OpenedOn = openedOn?.UtcDateTime;
}
public string Extension { get; }
public string ValueName { get; }
public int MruPosition { get; }
public string AbsolutePath { get; }
public DateTime? OpenedOn { get; }
public string Details { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Extension: {Extension} Absolute path: {AbsolutePath}";
public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})";
public string BatchValueData3 => $"MRU: {MruPosition} Details: {Details}" ;
}
} | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.OpenSavePidlMRU
{
public class ValuesOut:IValueOut
{
public ValuesOut(string ext, string absolutePath, string details, string valueName, int mruPosition,
DateTimeOffset? openedOn)
{
Extension = ext;
AbsolutePath = absolutePath;
Details = details;
ValueName = valueName;
MruPosition = mruPosition;
OpenedOn = openedOn?.UtcDateTime;
}
public string Extension { get; }
public string ValueName { get; }
public int MruPosition { get; }
public string AbsolutePath { get; }
public DateTime? OpenedOn { get; }
public string Details { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Extension: {Extension} Absolute path: {AbsolutePath}";
public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})";
public string BatchValueData3 => $"Mru: {MruPosition} Details: {Details}" ;
}
} | mit | C# |
51957277afb767062f282d5fd7c659f75e00b0f6 | Add missing EnableNotificationAPI flag to DokanOptions enum | dokan-dev/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,dokan-dev/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,dokan-dev/dokan-dotnet | DokanNet/DokanOptions.cs | DokanNet/DokanOptions.cs | using System;
using DokanNet.Native;
namespace DokanNet
{
/// <summary>
/// Dokan mount options used to describe dokan device behavior.
/// </summary>
/// \if PRIVATE
/// <seealso cref="DOKAN_OPTIONS.Options"/>
/// \endif
[Flags]
public enum DokanOptions : long
{
/// <summary>Fixed Drive.</summary>
FixedDrive = 0,
/// <summary>Enable output debug message.</summary>
DebugMode = 1,
/// <summary>Enable output debug message to stderr.</summary>
StderrOutput = 2,
/// <summary>Use alternate stream.</summary>
AltStream = 4,
/// <summary>Enable mount drive as write-protected.</summary>
WriteProtection = 8,
/// <summary>Use network drive - Dokan network provider need to be installed.</summary>
NetworkDrive = 16,
/// <summary>Use removable drive.</summary>
RemovableDrive = 32,
/// <summary>Use mount manager.</summary>
MountManager = 64,
/// <summary>Mount the drive on current session only.</summary>
CurrentSession = 128,
/// <summary>Enable Lockfile/Unlockfile operations.</summary>
UserModeLock = 256,
/// <summary>
/// Whether DokanNotifyXXX functions should be enabled, which requires this
/// library to maintain a special handle while the file system is mounted.
/// Without this flag, the functions always return FALSE if invoked.
/// </summary>
EnableNotificationAPI = 512,
}
}
| using System;
using DokanNet.Native;
namespace DokanNet
{
/// <summary>
/// Dokan mount options used to describe dokan device behavior.
/// </summary>
/// \if PRIVATE
/// <seealso cref="DOKAN_OPTIONS.Options"/>
/// \endif
[Flags]
public enum DokanOptions : long
{
/// <summary>Fixed Drive.</summary>
FixedDrive = 0,
/// <summary>Enable output debug message.</summary>
DebugMode = 1,
/// <summary>Enable output debug message to stderr.</summary>
StderrOutput = 2,
/// <summary>Use alternate stream.</summary>
AltStream = 4,
/// <summary>Enable mount drive as write-protected.</summary>
WriteProtection = 8,
/// <summary>Use network drive - Dokan network provider need to be installed.</summary>
NetworkDrive = 16,
/// <summary>Use removable drive.</summary>
RemovableDrive = 32,
/// <summary>Use mount manager.</summary>
MountManager = 64,
/// <summary>Mount the drive on current session only.</summary>
CurrentSession = 128,
/// <summary>Enable Lockfile/Unlockfile operations.</summary>
UserModeLock = 256
}
}
| mit | C# |
1f3d43d92b1f061a6b5c869a98f4f89cb0d7fe70 | Update RuleUpdater.cs | win120a/ACClassRoomUtil,win120a/ACClassRoomUtil | ProcessBlockUtil/RuleUpdater.cs | ProcessBlockUtil/RuleUpdater.cs | /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Version message.
*/
Console.WriteLine("AC PBU RuleUpdater V1.0.1");
Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung");
Console.WriteLine(" ");
Console.WriteLine("The process is starting, please make sure the program running.");
/*
Stop The Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Stop();
pbuSC.WaitForStatus(ServiceControllerStatus.Stopped);
/*
Obtain some path.
*/
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete Exist file.
*/
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Start();
pbuSC.WaitForStatus(ServiceControllerStatus.Running);
}
}
}
| /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Stop The Service.
*/
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.stop();
/*
Obtain some path.
*/
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete Exist file.
*/
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Process.Start(systemRoot + "\\System32\\sc.exe", "start pbuService");
}
}
}
| apache-2.0 | C# |
1084b943b4fb4679ca6e2f5d3a69ba4528ba1584 | test fix | argeset/set-web,argeset/set-web | sources/set.web.test/Interface/FormTests.cs | sources/set.web.test/Interface/FormTests.cs | using System;
using System.Drawing.Imaging;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using set.web.test.Shared;
namespace set.web.test.Interface
{
[TestFixture]
public class FormTests : BaseInterfaceTest
{
[Test]
public void should_save_new_feedback_via_popup_form()
{
var homeUrl = string.Format("{0}{1}", BASE_URL, ACTION_HOME);
GoTo(homeUrl);
Browser.FindElementById("btnOpenFeedBack").Click();
WaitHack();
Browser.FindElementById("FeedbackMessage").SendKeys("test feedback");
Browser.FindElementById("btnSaveFeedback").Click();
CloseBrowser();
}
private void WaitHack()
{
Browser.GetScreenshot().SaveAsFile(string.Format("{0}.png", Guid.NewGuid()), ImageFormat.Png);
}
[Test]
public void should_save_domainobject_and_new_one_after()
{
LoginAsUser();
var url = string.Format("{0}{1}", BASE_URL, ACTION_NEW_DOMAIN_OBJECT);
GoTo(url);
Browser.FindElementById("Name").SendKeys("test domain obj with save and new");
Browser.FindElementById("btnSaveAndNew").Click();
Assert.IsNotNull(Browser);
Assert.AreEqual(Browser.Url, url);
CloseBrowser();
}
[Test]
public void should_save_domainobject_and_redirect_to_list()
{
LoginAsUser();
var url = string.Format("{0}{1}", BASE_URL, ACTION_NEW_DOMAIN_OBJECT);
var domainObjListUrl = string.Format("{0}{1}", BASE_URL, ACTION_LIST_DOMAIN_OBJECTS);
GoTo(url);
Browser.FindElementById("Name").SendKeys("test domain obj");
Browser.FindElementById("btnSave").Click();
Assert.IsNotNull(Browser);
Assert.AreEqual(Browser.Url, domainObjListUrl);
CloseBrowser();
}
}
} | using System;
using NUnit.Framework;
using set.web.test.Shared;
namespace set.web.test.Interface
{
[TestFixture]
public class FormTests : BaseInterfaceTest
{
[Test]
public void should_save_new_feedback_via_popup_form()
{
var homeUrl = string.Format("{0}{1}", BASE_URL, ACTION_HOME);
GoTo(homeUrl);
Browser.FindElementById("btnOpenFeedBack").Click();
Browser.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
Browser.FindElementById("FeedbackMessage").SendKeys("test feedback");
Browser.FindElementById("btnSaveFeedback").Click();
Browser.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
Assert.IsFalse(Browser.FindElementById("modalFeedback").Displayed);
CloseBrowser();
}
[Test]
public void should_save_domainobject_and_new_one_after()
{
LoginAsUser();
var url = string.Format("{0}{1}", BASE_URL, ACTION_NEW_DOMAIN_OBJECT);
GoTo(url);
Browser.FindElementById("Name").SendKeys("test domain obj with save and new");
Browser.FindElementById("btnSaveAndNew").Click();
Assert.IsNotNull(Browser);
Assert.AreEqual(Browser.Url, url);
CloseBrowser();
}
[Test]
public void should_save_domainobject_and_redirect_to_list()
{
LoginAsUser();
var url = string.Format("{0}{1}", BASE_URL, ACTION_NEW_DOMAIN_OBJECT);
var domainObjListUrl = string.Format("{0}{1}", BASE_URL, ACTION_LIST_DOMAIN_OBJECTS);
GoTo(url);
Browser.FindElementById("Name").SendKeys("test domain obj");
Browser.FindElementById("btnSave").Click();
Assert.IsNotNull(Browser);
Assert.AreEqual(Browser.Url, domainObjListUrl);
CloseBrowser();
}
}
} | mit | C# |
e64860ad45b44dfe27d36c1389d30af79e498e17 | Fix test case not working as expected | naoey/osu,Nabile-Rahmani/osu,smoogipoo/osu,NeoAdonis/osu,naoey/osu,naoey/osu,johnneijzen/osu,2yangk23/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,Frontear/osuKyzer,UselessToucan/osu,DrabWeb/osu,ZLima12/osu,ppy/osu,peppy/osu,UselessToucan/osu,Drezi126/osu,smoogipooo/osu,ppy/osu,2yangk23/osu,ppy/osu,peppy/osu,peppy/osu-new,DrabWeb/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,DrabWeb/osu,ZLima12/osu | osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/TimelinePart.cs | osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/TimelinePart.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using OpenTK;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// Represents a part of the summary timeline..
/// </summary>
internal abstract class TimelinePart : CompositeDrawable
{
public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
private readonly Container timeline;
protected TimelinePart()
{
AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both });
Beatmap.ValueChanged += b =>
{
updateRelativeChildSize();
LoadBeatmap(b);
};
}
private void updateRelativeChildSize()
{
// the track may not be loaded completely (only has a length once it is).
if (!Beatmap.Value.Track.IsLoaded)
{
timeline.RelativeChildSize = Vector2.One;
Schedule(updateRelativeChildSize);
return;
}
timeline.RelativeChildSize = new Vector2((float)Math.Max(1, Beatmap.Value.Track.Length), 1);
}
protected void Add(Drawable visualisation) => timeline.Add(visualisation);
protected virtual void LoadBeatmap(WorkingBeatmap beatmap)
{
timeline.Clear();
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using OpenTK;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// Represents a part of the summary timeline..
/// </summary>
internal abstract class TimelinePart : CompositeDrawable
{
public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
private readonly Container timeline;
protected TimelinePart()
{
AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both });
Beatmap.ValueChanged += b =>
{
updateRelativeChildSize();
LoadBeatmap(b);
};
}
private void updateRelativeChildSize()
{
if (!Beatmap.Value.TrackLoaded)
{
timeline.RelativeChildSize = Vector2.One;
return;
}
var track = Beatmap.Value.Track;
if (!track.IsLoaded)
{
// the track may not be loaded completely (only has a length once it is).
Schedule(updateRelativeChildSize);
return;
}
timeline.RelativeChildSize = new Vector2((float)Math.Max(1, track.Length), 1);
}
protected void Add(Drawable visualisation) => timeline.Add(visualisation);
protected virtual void LoadBeatmap(WorkingBeatmap beatmap)
{
timeline.Clear();
}
}
}
| mit | C# |
6cc4566effc8d333bb12eb52062954e85e4889f6 | Support InitAccessorDeclaration in UseExpressionBodyForAccessors | KevinRansom/roslyn,diryboy/roslyn,sharwell/roslyn,eriawan/roslyn,sharwell/roslyn,physhi/roslyn,AmadeusW/roslyn,mavasani/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,sharwell/roslyn,eriawan/roslyn,wvdd007/roslyn,dotnet/roslyn,bartdesmet/roslyn,weltkante/roslyn,dotnet/roslyn,bartdesmet/roslyn,diryboy/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,physhi/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,wvdd007/roslyn,KevinRansom/roslyn,weltkante/roslyn,physhi/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn | src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs | src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForAccessorsHelper :
UseExpressionBodyHelper<AccessorDeclarationSyntax>
{
public static readonly UseExpressionBodyForAccessorsHelper Instance = new();
private UseExpressionBodyForAccessorsHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForAccessorsDiagnosticId,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedAccessors,
ImmutableArray.Create(SyntaxKind.GetAccessorDeclaration, SyntaxKind.SetAccessorDeclaration, SyntaxKind.InitAccessorDeclaration))
{
}
protected override BlockSyntax GetBody(AccessorDeclarationSyntax declaration)
=> declaration.Body;
protected override ArrowExpressionClauseSyntax GetExpressionBody(AccessorDeclarationSyntax declaration)
=> declaration.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(AccessorDeclarationSyntax declaration)
=> declaration.SemicolonToken;
protected override AccessorDeclarationSyntax WithSemicolonToken(AccessorDeclarationSyntax declaration, SyntaxToken token)
=> declaration.WithSemicolonToken(token);
protected override AccessorDeclarationSyntax WithExpressionBody(AccessorDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody)
=> declaration.WithExpressionBody(expressionBody);
protected override AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax declaration, BlockSyntax body)
=> declaration.WithBody(body);
protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, AccessorDeclarationSyntax declaration)
=> declaration.IsKind(SyntaxKind.GetAccessorDeclaration);
}
}
| // 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.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForAccessorsHelper :
UseExpressionBodyHelper<AccessorDeclarationSyntax>
{
public static readonly UseExpressionBodyForAccessorsHelper Instance = new();
private UseExpressionBodyForAccessorsHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForAccessorsDiagnosticId,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedAccessors,
ImmutableArray.Create(SyntaxKind.GetAccessorDeclaration, SyntaxKind.SetAccessorDeclaration))
{
}
protected override BlockSyntax GetBody(AccessorDeclarationSyntax declaration)
=> declaration.Body;
protected override ArrowExpressionClauseSyntax GetExpressionBody(AccessorDeclarationSyntax declaration)
=> declaration.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(AccessorDeclarationSyntax declaration)
=> declaration.SemicolonToken;
protected override AccessorDeclarationSyntax WithSemicolonToken(AccessorDeclarationSyntax declaration, SyntaxToken token)
=> declaration.WithSemicolonToken(token);
protected override AccessorDeclarationSyntax WithExpressionBody(AccessorDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody)
=> declaration.WithExpressionBody(expressionBody);
protected override AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax declaration, BlockSyntax body)
=> declaration.WithBody(body);
protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, AccessorDeclarationSyntax declaration)
=> declaration.IsKind(SyntaxKind.GetAccessorDeclaration);
}
}
| mit | C# |
997aaafb6dde10379403cbaab6ee83ea7b561702 | Allow custom message in ValidationException ctor | IRlyDontKnow/FluentValidation,olcayseker/FluentValidation,GDoronin/FluentValidation,ruisebastiao/FluentValidation,robv8r/FluentValidation,glorylee/FluentValidation,deluxetiky/FluentValidation,cecilphillip/FluentValidation,mgmoody42/FluentValidation,regisbsb/FluentValidation | src/FluentValidation/ValidationException.cs | src/FluentValidation/ValidationException.cs | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation {
using System;
using System.Collections.Generic;
using Results;
using System.Linq;
public class ValidationException : Exception {
public IEnumerable<ValidationFailure> Errors { get; private set; }
public ValidationException(string message, IEnumerable<ValidationFailure> errors) : base(message) {
Errors = errors;
}
public ValidationException(IEnumerable<ValidationFailure> errors) : base(BuildErrorMesage(errors)) {
Errors = errors;
}
private static string BuildErrorMesage(IEnumerable<ValidationFailure> errors) {
var arr = errors.Select(x => "\r\n -- " + x.ErrorMessage).ToArray();
return "Validation failed: " + string.Join("", arr);
}
}
} | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation {
using System;
using System.Collections.Generic;
using Results;
using System.Linq;
public class ValidationException : Exception {
public IEnumerable<ValidationFailure> Errors { get; private set; }
public ValidationException(IEnumerable<ValidationFailure> errors) : base(BuildErrorMesage(errors)) {
Errors = errors;
}
private static string BuildErrorMesage(IEnumerable<ValidationFailure> errors) {
var arr = errors.Select(x => "\r\n -- " + x.ErrorMessage).ToArray();
return "Validation failed: " + string.Join("", arr);
}
}
} | apache-2.0 | C# |
410d0b4ee1b23e48032a340d4abd571aaad504cb | Add ability to change the extension of downloaded files (#5017) | ZLima12/osu,peppy/osu,johnneijzen/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,peppy/osu-new,ppy/osu,ZLima12/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,peppy/osu,peppy/osu,EVAST9919/osu | osu.Game/Online/API/APIDownloadRequest.cs | osu.Game/Online/API/APIDownloadRequest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.IO.Network;
namespace osu.Game.Online.API
{
public abstract class APIDownloadRequest : APIRequest
{
private string filename;
/// <summary>
/// Used to set the extension of the file returned by this request.
/// </summary>
protected virtual string FileExtension { get; } = @".tmp";
protected override WebRequest CreateWebRequest()
{
var file = Path.GetTempFileName();
File.Move(file, filename = Path.ChangeExtension(file, FileExtension));
var request = new FileWebRequest(filename, Uri);
request.DownloadProgress += request_Progress;
return request;
}
private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total));
protected APIDownloadRequest()
{
base.Success += onSuccess;
}
private void onSuccess()
{
Success?.Invoke(filename);
}
public event APIProgressHandler Progressed;
public new event APISuccessHandler<string> Success;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.IO.Network;
namespace osu.Game.Online.API
{
public abstract class APIDownloadRequest : APIRequest
{
private string filename;
protected override WebRequest CreateWebRequest()
{
var request = new FileWebRequest(filename = Path.GetTempFileName(), Uri);
request.DownloadProgress += request_Progress;
return request;
}
private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total));
protected APIDownloadRequest()
{
base.Success += onSuccess;
}
private void onSuccess()
{
Success?.Invoke(filename);
}
public event APIProgressHandler Progressed;
public new event APISuccessHandler<string> Success;
}
}
| mit | C# |
127786cf02e2449abd3da6f9181f18d8a7d9e0a2 | Fix Bacs network_status deserialization | stripe/stripe-dotnet | src/Stripe.net/Entities/Mandates/MandatePaymentMethodDetailsBacsDebit.cs | src/Stripe.net/Entities/Mandates/MandatePaymentMethodDetailsBacsDebit.cs | namespace Stripe
{
using Newtonsoft.Json;
public class MandatePaymentMethodDetailsBacsDebit : StripeEntity<MandatePaymentMethodDetailsBacsDebit>
{
/// <summary>
/// The status of the mandate on the network and whether it's been accepted or revoked.
/// </summary>
[JsonProperty("network_status")]
public string NetworkStatus { get; set; }
/// <summary>
/// The reference associated with the mandate.
/// </summary>
[JsonProperty("reference")]
public string Reference { get; set; }
/// <summary>
/// The URL to view the mandate.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
public class MandatePaymentMethodDetailsBacsDebit : StripeEntity<MandatePaymentMethodDetailsBacsDebit>
{
/// <summary>
/// The status of the mandate on the network and whether it's been accepted or revoked.
/// </summary>
[JsonProperty("network_status")]
public long NetworkStatus { get; set; }
/// <summary>
/// The reference associated with the mandate.
/// </summary>
[JsonProperty("reference")]
public string Reference { get; set; }
/// <summary>
/// The URL to view the mandate.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
}
}
| apache-2.0 | C# |
994d4bfe1260e8684e33b606ec359a7ce868a302 | change menu text | s093294/Thinktecture.AuthorizationServer,s093294/Thinktecture.AuthorizationServer,IdentityModel/AuthorizationServer,yfann/AuthorizationServer,yfann/AuthorizationServer,IdentityModel/AuthorizationServer | source/WebHost/Views/Shared/_LayoutWithMenu.cshtml | source/WebHost/Views/Shared/_LayoutWithMenu.cshtml | @{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<section class="row">
<nav class="span2">
<ul class="nav nav-pills nav-stacked">
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Configure", "Index", "Home", new { area="Admin" }, null)</li>
</ul>
</nav>
<section class="span9 offset1">
@RenderBody()
</section>
</section> | @{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<section class="row">
<nav class="span2">
<ul class="nav nav-pills nav-stacked">
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Admin", "Index", "Home", new { area="Admin" }, null)</li>
</ul>
</nav>
<section class="span9 offset1">
@RenderBody()
</section>
</section> | bsd-3-clause | C# |
6e4adb0ac0cea844198a94802628629ca92228c5 | Rename parser factory methods. | ZoolWay/DbNanites | DbNanites.Core/ParserFactory.cs | DbNanites.Core/ParserFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DbNanites.Core
{
public static class ParserFactory
{
/// <summary>
/// Creates a model parser based on the provided file.
/// Currently supported files: Yaml
/// </summary>
/// <param name="filename">File which is used for parser detection.</param>
/// <returns>>A model parser which fits to the provided file.
/// If the file isn't supported this method returns null.</returns>
public static IModelParser Provide(string filename)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a yaml file parser.
/// </summary>
/// <returns>The yaml.</returns>
public static IModelParser ProvideYaml()
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DbNanites.Core
{
public static class ParserFactory
{
public static IModelParser Factory(string filename)
{
throw new NotImplementedException();
}
public static IModelParser ProvideYamlParser()
{
throw new NotImplementedException();
}
}
}
| bsd-3-clause | C# |
cd09499bbe4017e3fe29f7798177a8264836bec5 | Update to use new User | csengineer13/Simple.MVC,csengineer13/Simple.MVC,csengineer13/Simple.MVC | Simple.Domain/Model/Organization/Organization.cs | Simple.Domain/Model/Organization/Organization.cs | using System;
using System.Collections.Generic;
using Simple.Domain.Entities;
namespace Simple.Domain.Model
{
public class Organization
{
public Guid Id { get; set; }
public string Name { get; set; }
public string CatchPhrase { get; set; }
public string BSPhrase { get; set; }
// Ref
public User Owner { get; set; }
// List Ref
public List<Address> Addresses { get; set; }
public List<User> Employees { get; set; }
}
} | using System;
using System.Collections.Generic;
namespace Simple.Domain.Model
{
public class Organization
{
public Guid Id { get; set; }
public string Name { get; set; }
public string CatchPhrase { get; set; }
public string BSPhrase { get; set; }
// Ref
public DomainUser Owner { get; set; }
// List Ref
public List<Address> Addresses { get; set; }
public List<DomainUser> Employees { get; set; }
}
} | mit | C# |
0a80b701bc04311cf20b4cfd9a05eb3cff7ec304 | Update LegendaryDroppedPopup.cs | prrovoss/THUD | plugins/Prrovoss/LegendaryDroppedPopup.cs | plugins/Prrovoss/LegendaryDroppedPopup.cs | using Turbo.Plugins.Default;
namespace Turbo.Plugins.Prrovoss
{
public class LegendaryDroppedPopup : BasePlugin, ILootGeneratedHandler
{
public void OnLootGenerated(IItem item, bool gambled)
{
if (item.Quality >= ItemQuality.Legendary)
Hud.RunOnPlugin<PopupNotifications>(plugin =>
{
plugin.Show(item.SnoItem.NameLocalized + (item.AncientRank == 1 ? " (A)" : ""), "Legendary dropped", 10000, "Hurray");
});
}
public LegendaryDroppedPopup()
{
Enabled = true;
}
}
}
| using Turbo.Plugins.Default;
namespace Turbo.Plugins.Prrovoss
{
public class LegendaryDroppedPopup : BasePlugin, ILootGeneratedHandler
{
public void OnLootGenerated(IItem item, bool gambled)
{
if (item.Quality >= ItemQuality.Legendary)
Hud.GetPlugin<PopupNotifications>().Show(item.SnoItem.NameLocalized + (item.AncientRank == 1 ? " (A)" : ""), "Legendary dropped", 10000, "Hurray");
}
public LegendaryDroppedPopup()
{
Enabled = true;
}
}
}
| mit | C# |
174f12adbeffc3ff7e521725fb1cf48b3b6311e5 | Fix for Pos in PString<T> that could throw an IndexOutOfRangeException | louthy/language-ext,StanJav/language-ext | LanguageExt.Parsec/PStringIO.cs | LanguageExt.Parsec/PStringIO.cs | using System;
using System.Linq;
using static LanguageExt.Prelude;
namespace LanguageExt.Parsec
{
/// <summary>
/// Represents the parser source string and the parser's
/// positional state.
/// </summary>
public class PString<T>
{
public readonly T[] Value;
public readonly int Index;
public readonly int EndIndex;
public readonly Option<object> UserState;
public readonly Func<T, Pos> TokenPos;
public PString(T[] value, int index, int endIndex, Option<object> userState, Func<T, Pos> tokenPos)
{
Value = value;
Index = index;
EndIndex = endIndex;
UserState = userState;
TokenPos = tokenPos;
}
public Pos Pos =>
Value?.Length ?? 0 == 0
? Pos.Zero
: Index < Value.Length
? TokenPos(Value[Index])
: TokenPos(Value[Value.Length - 1]);
public PString<T> SetValue(T[] value) =>
new PString<T>(value, Index, value.Length, UserState, TokenPos);
public PString<T> SetIndex(int index) =>
new PString<T>(Value, index, EndIndex, UserState, TokenPos);
public PString<T> SetUserState(object state) =>
new PString<T>(Value, Index, EndIndex, state, TokenPos);
public PString<T> SetEndIndex(int endIndex) =>
new PString<T>(Value, Index, endIndex, UserState, TokenPos);
public override string ToString() =>
$"{typeof(T).Name}({Index}, {EndIndex})";
public static PString<T> Zero(Func<T, Pos> tokenPos) =>
new PString<T>(new T[0], 0, 0, None, tokenPos);
public PString<U> Cast<U>() where U : T =>
new PString<U>(Value.Cast<U>().ToArray(), Index, EndIndex, UserState, u => TokenPos((T)u));
}
}
| using System;
using System.Linq;
using static LanguageExt.Prelude;
namespace LanguageExt.Parsec
{
/// <summary>
/// Represents the parser source string and the parser's
/// positional state.
/// </summary>
public class PString<T>
{
public readonly T[] Value;
public readonly int Index;
public readonly int EndIndex;
public readonly Option<object> UserState;
public readonly Func<T, Pos> TokenPos;
public PString(T[] value, int index, int endIndex, Option<object> userState, Func<T, Pos> tokenPos)
{
Value = value;
Index = index;
EndIndex = endIndex;
UserState = userState;
TokenPos = tokenPos;
}
public Pos Pos =>
Index < Value.Length
? TokenPos(Value[Index])
: TokenPos(Value[Value.Length - 1]);
public PString<T> SetValue(T[] value) =>
new PString<T>(value, Index, value.Length, UserState, TokenPos);
public PString<T> SetIndex(int index) =>
new PString<T>(Value, index, EndIndex, UserState, TokenPos);
public PString<T> SetUserState(object state) =>
new PString<T>(Value, Index, EndIndex, state, TokenPos);
public PString<T> SetEndIndex(int endIndex) =>
new PString<T>(Value, Index, endIndex, UserState, TokenPos);
public override string ToString() =>
$"{typeof(T).Name}({Index}, {EndIndex})";
public static PString<T> Zero(Func<T, Pos> tokenPos) =>
new PString<T>(new T[0], 0, 0, None, tokenPos);
public PString<U> Cast<U>() where U : T =>
new PString<U>(Value.Cast<U>().ToArray(), Index, EndIndex, UserState, u => TokenPos((T)u));
}
}
| mit | C# |
ef3db9d71a9bac1f1747a35e3ff098feef5c736a | use string.Join to build the input | benjamin-hodgson/Pidgin | Pidgin.Bench/ExpressionBench.cs | Pidgin.Bench/ExpressionBench.cs | using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using Pidgin.Expression;
using static Pidgin.Parser;
using static Pidgin.Parser<char>;
namespace Pidgin.Bench
{
[Config(typeof(Config))]
public class ExpressionBench
{
private string _bigExpression;
private Parser<char, int> _leftAssoc;
private Parser<char, int> _rightAssoc;
[Setup]
public void Setup()
{
_bigExpression = string.Join("+", Enumerable.Range(1, 1000));
var term = Parser.Digit.Many().Select(cs => int.Parse(string.Concat(cs)));
var infixL = Operator.InfixL(Parser.Char('+').Then(Return<Func<int, int, int>>((x, y) => x + y)));
_leftAssoc = ExpressionParser.Build(
term,
new[] { new[] { infixL } }
);
var infixR = Operator.InfixR(Parser.Char('+').Then(Return<Func<int, int, int>>((x, y) => x + y)));
_rightAssoc = ExpressionParser.Build(
term,
new[] { new[] { infixR } }
);
}
[Benchmark]
public void InfixL_Pidgin()
{
_leftAssoc.ParseOrThrow(_bigExpression);
}
[Benchmark]
public void InfixR_Pidgin()
{
_rightAssoc.ParseOrThrow(_bigExpression);
}
[Benchmark]
public void InfixL_FParsec()
{
Pidgin.Bench.FParsec.ExpressionParser.parseL(_bigExpression);
}
[Benchmark]
public void InfixR_FParsec()
{
Pidgin.Bench.FParsec.ExpressionParser.parseR(_bigExpression);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using Pidgin.Expression;
using static Pidgin.Parser;
using static Pidgin.Parser<char>;
namespace Pidgin.Bench
{
[Config(typeof(Config))]
public class ExpressionBench
{
private string _bigExpression;
private Parser<char, int> _leftAssoc;
private Parser<char, int> _rightAssoc;
[Setup]
public void Setup()
{
var numbers = Enumerable.Range(1, 1000);
_bigExpression = "0" + numbers.Aggregate("", (x, y) => x + "+" + y);
var term = Parser.Digit.Many().Select(cs => int.Parse(string.Concat(cs)));
var infixL = Operator.InfixL(Parser.Char('+').Then(Return<Func<int, int, int>>((x, y) => x + y)));
_leftAssoc = ExpressionParser.Build(
term,
new[] { new[] { infixL } }
);
var infixR = Operator.InfixR(Parser.Char('+').Then(Return<Func<int, int, int>>((x, y) => x + y)));
_rightAssoc = ExpressionParser.Build(
term,
new[] { new[] { infixR } }
);
}
[Benchmark]
public void InfixL_Pidgin()
{
_leftAssoc.ParseOrThrow(_bigExpression);
}
[Benchmark]
public void InfixR_Pidgin()
{
_rightAssoc.ParseOrThrow(_bigExpression);
}
[Benchmark]
public void InfixL_FParsec()
{
Pidgin.Bench.FParsec.ExpressionParser.parseL(_bigExpression);
}
[Benchmark]
public void InfixR_FParsec()
{
Pidgin.Bench.FParsec.ExpressionParser.parseR(_bigExpression);
}
}
} | mit | C# |
32394b2315741cdff6c151c97deb94de292dcffb | Make an enum internal | mdesalvo/RDFSharp | RDFSharp/Store/RDFStoreEnums.cs | RDFSharp/Store/RDFStoreEnums.cs | /*
Copyright 2012-2019 Marco De Salvo
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.
*/
namespace RDFSharp.Store
{
/// <summary>
/// RDFStoreEnums represents a collector for all the enumerations used by the "RDFSharp.Store" namespace
/// </summary>
public static class RDFStoreEnums {
/// <summary>
/// RDFStoreSQLErrors represents an enumeration for situations which can be found on a SQL-backing store
/// </summary>
internal enum RDFStoreSQLErrors {
/// <summary>
/// Indicates that diagnostics on the selected database has passed
/// </summary>
NoErrors = 0,
/// <summary>
/// Indicates that diagnostics on the selected database has not passed because of a connection error
/// </summary>
InvalidDataSource = 1,
/// <summary>
/// Indicates that diagnostics on the selected database has not passed because it's not ready for use with RDFSharp
/// </summary>
QuadruplesTableNotFound = 2
};
/// <summary>
/// RDFFormats represents an enumeration for supported RDF store serialization data formats.
/// </summary>
public enum RDFFormats {
/// <summary>
/// N-Quads serialization
/// </summary>
NQuads = 1,
/// <summary>
/// TriX serialization
/// </summary>
TriX = 2
};
}
} | /*
Copyright 2012-2019 Marco De Salvo
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.
*/
namespace RDFSharp.Store
{
/// <summary>
/// RDFStoreEnums represents a collector for all the enumerations used by the "RDFSharp.Store" namespace
/// </summary>
public static class RDFStoreEnums {
/// <summary>
/// RDFStoreSQLErrors represents an enumeration for situations which can be found on a SQL-backing store
/// </summary>
public enum RDFStoreSQLErrors {
/// <summary>
/// Indicates that diagnostics on the selected database has passed
/// </summary>
NoErrors = 0,
/// <summary>
/// Indicates that diagnostics on the selected database has not passed because of a connection error
/// </summary>
InvalidDataSource = 1,
/// <summary>
/// Indicates that diagnostics on the selected database has not passed because it's not ready for use with RDFSharp
/// </summary>
QuadruplesTableNotFound = 2
};
/// <summary>
/// RDFFormats represents an enumeration for supported RDF store serialization data formats.
/// </summary>
public enum RDFFormats {
/// <summary>
/// N-Quads serialization
/// </summary>
NQuads = 1,
/// <summary>
/// TriX serialization
/// </summary>
TriX = 2
};
}
} | apache-2.0 | C# |
84b6988db41fa2cd885546ba53513c6de2a87912 | Update Time.cs | dimmpixeye/Unity3dTools | Runtime/LibTime/Time.cs | Runtime/LibTime/Time.cs | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
using UnityEngine;
namespace Pixeye.Actors
{
public class time : IKernel
{
protected const float fps = 60;
/// <summary>
/// <para> Default Framework Time. Use it for independent timing</para>
/// </summary>
public static readonly time Default = new time();
public static int frame => UnityEngine.Time.frameCount;
public static float fromStart => Time.time;
/// <summary>
/// <para> The scale at which the time is passing. This can be used for slow motion effects.</para>
/// </summary>
public float timeScale = 1.0f;
public float deltaTimeFixed;
public float deltaTime;
internal float timeScaleCached = 1.0f;
public static float scale
{
get { return Default.timeScale; }
set { Default.timeScale = value; }
}
/// <summary>
/// <para> The time in seconds it took to complete the last frame</para>
/// </summary>
public static float delta => Default.deltaTime;
/// <summary>
/// <para> 1 / 60 constant time</para>
/// </summary>
public static float deltaFixed => Default.deltaTimeFixed;
public time()
{
ProcessorUpdate.times.Add(this);
ProcessorUpdate.timesLen++;
deltaTimeFixed = 1 / fps;
deltaTime = deltaTimeFixed;
}
public void Tick()
{
deltaTime = UnityEngine.Time.deltaTime * timeScale;
deltaTimeFixed = 1 / fps * timeScale;
}
}
} | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
using UnityEngine;
namespace Pixeye.Actors
{
public class time : IKernel
{
protected const float fps = 60;
/// <summary>
/// <para> Default Framework Time. Use it for independent timing</para>
/// </summary>
internal static time Default = new time();
public static int frame => UnityEngine.Time.frameCount;
public static float fromStart => Time.time;
/// <summary>
/// <para> The scale at which the time is passing. This can be used for slow motion effects.</para>
/// </summary>
public float timeScale = 1.0f;
public float deltaTimeFixed;
public float deltaTime;
internal float timeScaleCached = 1.0f;
public static float scale
{
get { return Default.timeScale; }
set { Default.timeScale = value; }
}
/// <summary>
/// <para> The time in seconds it took to complete the last frame</para>
/// </summary>
public static float delta => Default.deltaTime;
/// <summary>
/// <para> 1 / 60 constant time</para>
/// </summary>
public static float deltaFixed => Default.deltaTimeFixed;
public time()
{
ProcessorUpdate.times.Add(this);
ProcessorUpdate.timesLen++;
deltaTimeFixed = 1 / fps;
deltaTime = deltaTimeFixed;
}
public void Tick()
{
deltaTime = UnityEngine.Time.deltaTime * timeScale;
deltaTimeFixed = 1 / fps * timeScale;
}
}
} | mit | C# |
527d27a84351801bd14f6006100551f491731e96 | Edit console app | daenetCorporation/DurableTaskMicroservices | GetTweetMention/GetTweetsMention/TweetOrchestration/TweetOrchestration.cs | GetTweetMention/GetTweetsMention/TweetOrchestration/TweetOrchestration.cs | using Daenet.DurableTask.Microservices;
using Daenet.DurableTaskMicroservices.Common.BaseClasses;
using DurableTask.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetTweetsMention
{
public class TweetOrchestration : OrchestrationBase<TweetOrchestrationInput, Null>
{
protected override async Task<Null> RunOrchestration(OrchestrationContext context, TweetOrchestrationInput input, ILogger logger)
{
var outPut = await context.ScheduleTask<GetTweetTaskOutput>(typeof(GetTweetsTask), getTweetsTaskInput());
await context.ScheduleTask<Null>(typeof(SwitchOnLightTask), switchOnLightTaskInput(input.LatestTweetId, outPut.LatestTweetId));
input.LatestTweetId = outPut.LatestTweetId;
await context.CreateTimer(context.CurrentUtcDateTime.AddMinutes(1), "");
logger.LogInformation("Orchestration will ContinueAsNew.");
context.ContinueAsNew(input);
return new Null();
}
private GetTweetsTaskInput getTweetsTaskInput()
{
return new GetTweetsTaskInput()
{
ConsumerKey = "",
ConsumerSecret = "",
AccessToken = "",
AccessTokenSecret = "",
Name = "daenet",
Count = 1
};
}
private SwitchOnLightTaskInput switchOnLightTaskInput(string oldId, string newId)
{
return new SwitchOnLightTaskInput()
{
GatewayUrl = "http://192.168.0.99",
UserName = "gusp-xLeBhYznPCkz0ZQBnuZ25f3cOwRpW3tiQ8k",
DeviceId = "4",
OldTweetId = oldId,
LatestTweetId = newId
};
}
}
}
| using Daenet.DurableTask.Microservices;
using Daenet.DurableTaskMicroservices.Common.BaseClasses;
using DurableTask.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetTweetsMention
{
public class TweetOrchestration : OrchestrationBase<TweetOrchestrationInput, Null>
{
protected override async Task<Null> RunOrchestration(OrchestrationContext context, TweetOrchestrationInput input, ILogger logger)
{
var outPut = await context.ScheduleTask<GetTweetTaskOutput>(typeof(GetTweetsTask), getTweetsTaskInput());
await context.ScheduleTask<Null>(typeof(SwitchOnLightTask), switchOnLightTaskInput(input.LatestTweetId, outPut.LatestTweetId));
input.LatestTweetId = outPut.LatestTweetId;
await context.CreateTimer(context.CurrentUtcDateTime.AddMinutes(1), "");
logger.LogInformation("Orchestration will ContinueAsNew.");
context.ContinueAsNew(input);
return new Null();
}
private GetTweetsTaskInput getTweetsTaskInput()
{
return new GetTweetsTaskInput()
{
ConsumerKey = "3fGIMVjex4rqO1dzSV7Gwie11",
ConsumerSecret = "Gkd0Gl9Z8GvZGYY4xx7UhA2sfJcRVbOb2w2SJyUFl0T6Pxdh5p",
AccessToken = "634344694-lnrzrUuNVGKCk4lOqeABPGAvtUvDZQDr1BwAJfcP",
AccessTokenSecret = "wmt1fKTQQQ2ztUIAl1bGTNhvzp8bxE7qNVDwm9ib7Inw8",
Name = "daenet",
Count = 1
};
}
private SwitchOnLightTaskInput switchOnLightTaskInput(string oldId, string newId)
{
return new SwitchOnLightTaskInput()
{
GatewayUrl = "http://192.168.0.99",
UserName = "gusp-xLeBhYznPCkz0ZQBnuZ25f3cOwRpW3tiQ8k",
DeviceId = "4",
OldTweetId = oldId,
LatestTweetId = newId
};
}
}
}
| mit | C# |
ee3562c2cd670020fc03d8a1732d75262cb5a59a | fix license header | fachexot/AMOS-SoftwareForge,fachexot/AMOS-SoftwareForge | SoftwareForge.Mvc/SoftwareForge.Mvc/Views/TeamProjects/CodePartial.cshtml | SoftwareForge.Mvc/SoftwareForge.Mvc/Views/TeamProjects/CodePartial.cshtml | <!--
- Copyright (c) 2013 by Denis Bach, Marvin Kampf, Konstantin Tsysin, Taner Tunc, Florian Wittmann
-
- This file is part of the Software Forge Overlay rating application.
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero 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 Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/>.
-->
@model List<string>
<div id="codePartial">
@if (Model.Count > 0)
{
<h5>Filecontent:</h5>
}
<code class="codeview">
@foreach (string line in Model)
{
<text>@line</text>
}
</code>
</div> | @model List<string>
<div id="codePartial">
@if (Model.Count > 0)
{
<h5>Filecontent:</h5>
}
<code class="codeview">
@foreach (string line in Model)
{
<text>@line</text>
}
</code>
</div> | agpl-3.0 | C# |
83f7e39fc2919105d6ad8423ada332ebfb2b1f34 | Update ContextTests.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | tests/Core2D.UnitTests/Data/ContextTests.cs | tests/Core2D.UnitTests/Data/ContextTests.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 Core2D.Data;
using Xunit;
namespace Core2D.UnitTests
{
public class ContextTests
{
[Fact]
[Trait("Core2D.Data", "Database")]
public void Inherits_From_ObservableObject()
{
var target = new Context();
Assert.True(target is ObservableObject);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void Properties_Not_Null()
{
var target = new Context();
Assert.False(target.Properties.IsDefault);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Null()
{
var target = new Context();
Assert.Null(target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
Assert.Equal("Value1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Sets_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
target["Name1"] = "NewValue1";
Assert.Equal("NewValue1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Creates_Property()
{
var target = new Context();
Assert.Empty(target.Properties);
target["Name1"] = "Value1";
Assert.Contains("Value1", target.Properties);
Assert.Equal(target, target.Properties[0].Owner);
}
}
}
| // 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 Core2D.Data;
using Xunit;
namespace Core2D.UnitTests
{
public class ContextTests
{
[Fact]
[Trait("Core2D.Data", "Database")]
public void Inherits_From_ObservableObject()
{
var target = new Context();
Assert.True(target is ObservableObject);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void Properties_Not_Null()
{
var target = new Context();
Assert.NotNull(target.Properties);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Null()
{
var target = new Context();
Assert.Equal(null, target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Returns_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
Assert.Equal("Value1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Sets_Property_Value()
{
var target = new Context();
target.Properties = target.Properties.Add(Property.Create(target, "Name1", "Value1"));
target["Name1"] = "NewValue1";
Assert.Equal("NewValue1", target["Name1"]);
}
[Fact]
[Trait("Core2D.Data", "Database")]
public void This_Operator_Creates_Property()
{
var target = new Context();
Assert.Equal(0, target.Properties.Length);
target["Name1"] = "Value1";
Assert.Equal(1, target.Properties.Length);
Assert.Equal(target, target.Properties[0].Owner);
}
}
}
| mit | C# |
b6a5290bb8a135368675fd1256b776426f3630eb | Remove redundant dot | Baggykiin/pass-winmenu | pass-winmenu/src/Configuration/ConfigManager.cs | pass-winmenu/src/Configuration/ConfigManager.cs | using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
namespace PassWinmenu.Configuration
{
internal class ConfigManager
{
public static Config Config { get; private set; } = new Config();
public enum LoadResult
{
Success,
NeedsUpgrade,
FileCreationFailure,
NewFileCreated
}
public static LoadResult Load(string fileName)
{
if (!File.Exists(fileName))
{
try
{
using (var defaultConfig = EmbeddedResources.DefaultConfig)
using (var configFile = File.Create(fileName))
{
defaultConfig.CopyTo(configFile);
}
}
catch (Exception e) when (e is FileNotFoundException || e is FileLoadException || e is IOException)
{
return LoadResult.FileCreationFailure;
}
return LoadResult.NewFileCreated;
}
var deserialiser = new Deserializer(namingConvention: new HyphenatedNamingConvention());
using (var reader = File.OpenText(fileName))
{
var versionCheck = deserialiser.Deserialize<Dictionary<string, object>>(reader);
if (!versionCheck.ContainsKey("config-version"))
{
return LoadResult.NeedsUpgrade;
}
if (versionCheck["config-version"] as string != Program.LastConfigVersion) return LoadResult.NeedsUpgrade;
}
using (var reader = File.OpenText(fileName))
{
Config = deserialiser.Deserialize<Config>(reader);
}
return LoadResult.Success;
}
public static void Reload(string fileName)
{
try
{
var deserialiser = new Deserializer(namingConvention: new HyphenatedNamingConvention());
using (var reader = File.OpenText(fileName))
{
var newConfig = deserialiser.Deserialize<Config>(reader);
Config = newConfig;
}
}
catch (Exception)
{
// No need to do anything, we can simply continue using the old configuration.
}
}
public static string Backup(string fileName)
{
var extension = Path.GetExtension(fileName);
var name = Path.GetFileNameWithoutExtension(fileName);
var directory = Path.GetDirectoryName(fileName);
// Find an unused name to which we can rename the old configuration file.
var root = string.IsNullOrEmpty(directory) ? name : Path.Combine(directory, name);
var newFileName = $"{root}-backup{extension}";
var counter = 2;
while (File.Exists(newFileName))
{
newFileName =$"{root}-backup-{counter}{extension}";
}
File.Move(fileName, newFileName);
using (var defaultConfig = EmbeddedResources.DefaultConfig)
using (var configFile = File.Create(fileName))
{
defaultConfig.CopyTo(configFile);
}
return newFileName;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
namespace PassWinmenu.Configuration
{
internal class ConfigManager
{
public static Config Config { get; private set; } = new Config();
public enum LoadResult
{
Success,
NeedsUpgrade,
FileCreationFailure,
NewFileCreated
}
public static LoadResult Load(string fileName)
{
if (!File.Exists(fileName))
{
try
{
using (var defaultConfig = EmbeddedResources.DefaultConfig)
using (var configFile = File.Create(fileName))
{
defaultConfig.CopyTo(configFile);
}
}
catch (Exception e) when (e is FileNotFoundException || e is FileLoadException || e is IOException)
{
return LoadResult.FileCreationFailure;
}
return LoadResult.NewFileCreated;
}
var deserialiser = new Deserializer(namingConvention: new HyphenatedNamingConvention());
using (var reader = File.OpenText(fileName))
{
var versionCheck = deserialiser.Deserialize<Dictionary<string, object>>(reader);
if (!versionCheck.ContainsKey("config-version"))
{
return LoadResult.NeedsUpgrade;
}
if (versionCheck["config-version"] as string != Program.LastConfigVersion) return LoadResult.NeedsUpgrade;
}
using (var reader = File.OpenText(fileName))
{
Config = deserialiser.Deserialize<Config>(reader);
}
return LoadResult.Success;
}
public static void Reload(string fileName)
{
try
{
var deserialiser = new Deserializer(namingConvention: new HyphenatedNamingConvention());
using (var reader = File.OpenText(fileName))
{
var newConfig = deserialiser.Deserialize<Config>(reader);
Config = newConfig;
}
}
catch (Exception)
{
// No need to do anything, we can simply continue using the old configuration.
}
}
public static string Backup(string fileName)
{
var extension = Path.GetExtension(fileName);
var name = Path.GetFileNameWithoutExtension(fileName);
var directory = Path.GetDirectoryName(fileName);
// Find an unused name to which we can rename the old configuration file.
var root = string.IsNullOrEmpty(directory) ? name : Path.Combine(directory, name);
var newFileName = $"{root}-backup.{extension}";
var counter = 2;
while (File.Exists(newFileName))
{
newFileName =$"{root}-backup-{counter}.{extension}";
}
File.Move(fileName, newFileName);
using (var defaultConfig = EmbeddedResources.DefaultConfig)
using (var configFile = File.Create(fileName))
{
defaultConfig.CopyTo(configFile);
}
return newFileName;
}
}
}
| mit | C# |
a87e25ff81dbcb1f6c9f29757fd76cf7f14f1f0b | remove aria-hidden tag | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Views/stockportgov/Shared/Semantic/GlobalAlert.cshtml | src/StockportWebapp/Views/stockportgov/Shared/Semantic/GlobalAlert.cshtml | @using StockportWebapp.Models
@using StockportWebapp.Utils
@inject ICookiesHelper CookiesHelper
@model Alert
@{
var icons = new Dictionary<string, string>()
{
{Severity.Error, "exclamation-circle"},
{Severity.Information, "info-circle"},
{Severity.Warning, "exclamation-triangle"},
{Severity.Success, "check-circle"},
};
}
<section class="alert-@Model.Severity.ToLower()-fullwidth">
<div class="alert-body">
<div class="icon">
<i class="fa fa-@icons[@Model.Severity]"></i>
</div>
<div class="content">
<p class="h2">@Model.Title</p>
<p>@Html.Raw(Model.Body)</p>
</div>
<div class="dismiss">
<a href="javascript:void(0)" aria-label="close" data-parent="alert-@Model.Severity.ToLower()-fullwidth" data-slug="@Model.Slug">
<i class="fa fa-times"></i>
</a>
</div>
</div>
</section> | @using StockportWebapp.Models
@using StockportWebapp.Utils
@inject ICookiesHelper CookiesHelper
@model Alert
@{
var icons = new Dictionary<string, string>()
{
{Severity.Error, "exclamation-circle"},
{Severity.Information, "info-circle"},
{Severity.Warning, "exclamation-triangle"},
{Severity.Success, "check-circle"},
};
}
<section class="alert-@Model.Severity.ToLower()-fullwidth">
<div class="alert-body">
<div class="icon">
<i class="fa fa-@icons[@Model.Severity]"></i>
</div>
<div class="content">
<p class="h2">@Model.Title</p>
<p>@Html.Raw(Model.Body)</p>
</div>
<div class="dismiss">
<a href="javascript:void(0)" aria-label="close" data-parent="alert-@Model.Severity.ToLower()-fullwidth" data-slug="@Model.Slug" aria-hidden="true">
<i class="fa fa-times"></i>
</a>
</div>
</div>
</section> | mit | C# |
000c021d81956b48bac83f43e9b9a5ccea2513f0 | Add some helpers and stuff | 0culus/ElectronicCash | ElectronicCash/Alice.cs | ElectronicCash/Alice.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicCash
{
/// <summary>
/// The customer
/// </summary>
public class Alice : BaseActor
{
public List<MoneyOrder> MoneyOrders { get; private set; }
public string PersonalData { get; private set; }
public byte[] PersonalDataBytes { get; private set; }
public Alice(string _name, Guid _actorGuid, string _personalData)
{
Name = _name;
ActorGuid = _actorGuid;
Money = 1000;
PersonalData = _personalData;
PersonalDataBytes = GetBytes(_personalData);
}
/// <summary>
/// Called every time the customer wants to pay for something
/// </summary>
public void CreateMoneyOrders()
{
MoneyOrders = new List<MoneyOrder>();
}
#region private methods
/// <summary>
/// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
/// <summary>
/// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
private static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicCash
{
/// <summary>
/// The customer
/// </summary>
public class Alice : BaseActor
{
}
}
| mit | C# |
a6fbb3d40e71ea00365a1ff57d026cc26e47b663 | Kill OutputWriteResult \o/ | palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent | PaletteInsightAgent/Output/OutputDrivers/IOutput.cs | PaletteInsightAgent/Output/OutputDrivers/IOutput.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaletteInsightAgent.Output
{
/// <summary>
/// A generic interface for writing data
/// NOTE: since we (possibly) need to close files and/or database connections,
/// instances of this interface has to extend IDisposable
/// </summary>
public interface IOutput : IDisposable
{
/// <summary>
/// Tries to write out the csv files, and returns the list of successfully uploaded
/// files.
/// </summary>
/// <param name="csvFile"></param>
/// <returns></returns>
void Write(string csvFile);
/// <summary>
/// Returns true if an upload is in progress for the given table.
/// files.
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
bool IsInProgress(string tableName);
}
}
| using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaletteInsightAgent.Output
{
/// <summary>
/// An output wrapper for the results of an IOutput.Write().
/// </summary>
public class OutputWriteResult
{
/// <summary>
/// Files that were successfully written to the database
/// </summary>
public IList<string> successfullyWrittenFiles = new List<string>();
/// <summary>
/// Files that failed with unrecoverable errors
/// </summary>
public IList<string> failedFiles = new List<string>();
/// <summary>
/// Combines the contents of two output results
/// </summary>
/// <param name="parts"></param>
public static OutputWriteResult Combine(params OutputWriteResult[] parts)
{
return parts.Aggregate(new OutputWriteResult(), (memo,part)=>{
memo.failedFiles.AddRange(part.failedFiles);
memo.successfullyWrittenFiles.AddRange(part.successfullyWrittenFiles);
return memo;
});
}
public static OutputWriteResult Aggregate<T>(IEnumerable<T> seq, Func<T, OutputWriteResult> fn )
{
return seq.Aggregate(new OutputWriteResult(), (memo, res) => Combine(memo, fn(res)));
}
#region quickcreate
public static OutputWriteResult Ok(params string[] files)
{
return new OutputWriteResult { successfullyWrittenFiles = new List<string>(files) };
}
public static OutputWriteResult Failed(params string[] files)
{
return new OutputWriteResult { failedFiles = new List<string>(files) };
}
#endregion
}
/// <summary>
/// A generic interface for writing to the database.
/// NOTE: since we (possibly) need to close files and/or database connections,
/// instances of this interface has to extend IDisposable
/// </summary>
public interface IOutput : IDisposable
{
/// <summary>
/// Tries to write out the csv files, and returns the list of successfully uploaded
/// files.
/// </summary>
/// <param name="csvFile"></param>
/// <returns></returns>
void Write(string csvFile);
/// <summary>
/// Returns true if an upload is in progress for the given table.
/// files.
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
bool IsInProgress(string tableName);
}
}
| mit | C# |
f78ed1c3b2987020880a853ff4b9824820bd0fb2 | Update build.cake | predictive-technology-laboratory/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins | ExternalMaps/build.cake | ExternalMaps/build.cake | #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "NuGetPack"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Build").Does (() =>
{
const string sln = "./ExternalMaps.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Build")
.Does (() =>
{
NuGetPack ("./ExternalMaps.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET);
| #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Build"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Build").Does (() =>
{
const string sln = "./ExternalMaps.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Build")
.Does (() =>
{
NuGetPack ("./ExternalMaps.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET); | mit | C# |
c827de36748478587a744727e5bc89ae31aeb71c | Update AGhost.cs | fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/UI/AdminTools/AGhost.cs | UnityProject/Assets/Scripts/UI/AdminTools/AGhost.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AGhost : MonoBehaviour
{
public void OnClick()
{
if (PlayerManager.LocalPlayerScript == null) return;
PlayerManager.LocalPlayerScript.playerNetworkActions.CmdAGhost();
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AGhost : MonoBehaviour
{
public void OnClick()
{
if (!PlayerManager.LocalPlayerScript.playerNetworkActions) return;
PlayerManager.LocalPlayerScript.playerNetworkActions.CmdAGhost();
}
}
| agpl-3.0 | C# |
d77a0efc3f3efb388e5dccd3addbda0ba473f3fa | fix build in Demo | yonglehou/WebApiThrottle,lollop-lp/WebApiThrottle,yonglehou/WebApiThrottle,yonglehou/WebApiThrottle,stefanprodan/WebApiThrottle | WebApiThrottle.Demo/Controllers/ValuesController.cs | WebApiThrottle.Demo/Controllers/ValuesController.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApiThrottle.Demo.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
namespace WebApiThrottle.Demo.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.