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 |
---|---|---|---|---|---|---|---|---|
431b5517d15cb177050b99d4dd1a456110e4526a | Add TODO for Input Requirement | StefanoFiumara/Harry-Potter-Unity | Assets/Scripts/HarryPotterUnity/Cards/PlayRequirements/InputRequirement.cs | Assets/Scripts/HarryPotterUnity/Cards/PlayRequirements/InputRequirement.cs | using HarryPotterUnity.Game;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Cards.PlayRequirements
{
public class InputRequirement : MonoBehaviour, ICardPlayRequirement
{
private BaseCard _cardInfo;
[SerializeField, UsedImplicitly]
private int _fromHandActionInputRequired;
[SerializeField, UsedImplicitly]
private int _inPlayActionInputRequired;
public int FromHandActionInputRequired { get { return _fromHandActionInputRequired; } }
public int InPlayActionInputRequired { get { return _inPlayActionInputRequired; } }
private void Awake()
{
_cardInfo = GetComponent<BaseCard>();
if (GetComponent<InputGatherer>() == null)
{
gameObject.AddComponent<InputGatherer>();
}
}
public bool MeetsRequirement()
{
//TODO: Need to check whether this needs to check the FromHandActionTargets or the InPlayActionTargets!
return _cardInfo.GetFromHandActionTargets().Count >= _fromHandActionInputRequired;
}
public void OnRequirementMet() { }
}
}
| using HarryPotterUnity.Game;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Cards.PlayRequirements
{
public class InputRequirement : MonoBehaviour, ICardPlayRequirement
{
private BaseCard _cardInfo;
[SerializeField, UsedImplicitly]
private int _fromHandActionInputRequired;
[SerializeField, UsedImplicitly]
private int _inPlayActionInputRequired;
public int FromHandActionInputRequired { get { return _fromHandActionInputRequired; } }
public int InPlayActionInputRequired { get { return _inPlayActionInputRequired; } }
private void Awake()
{
_cardInfo = GetComponent<BaseCard>();
if (GetComponent<InputGatherer>() == null)
{
gameObject.AddComponent<InputGatherer>();
}
}
public bool MeetsRequirement()
{
return _cardInfo.GetFromHandActionTargets().Count >= _fromHandActionInputRequired;
}
public void OnRequirementMet() { }
}
}
| mit | C# |
1a0e920a37d96fdf67095a65bf86a281dd290508 | Change order of events. | Cheesebaron/SGTabbedPager,Cheesebaron/SGTabbedPager | SampleMvx/Core/ViewModels/FirstViewModel.cs | SampleMvx/Core/ViewModels/FirstViewModel.cs | using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using MvvmCross.Core.ViewModels;
namespace SampleMvx.Core.ViewModels
{
public class FirstViewModel
: MvxViewModel
{
public ObservableCollection<PageViewModel> Pages = new ObservableCollection<PageViewModel>();
private MvxCommand _addPageCommand;
public ICommand AddPageCommand
{
get
{
_addPageCommand = _addPageCommand ?? new MvxCommand(DoAddPageCommand);
return _addPageCommand;
}
}
public int PageCount { get; private set; }
private void DoAddPageCommand()
{
++PageCount;
RaisePropertyChanged(() => PageCount);
Pages.Add(new PageViewModel { Hello = $"Hello SGTabbedPager {PageCount}"});
}
private MvxCommand _removePageCommand;
public ICommand RemovePageCommand
{
get
{
_removePageCommand = _removePageCommand ?? new MvxCommand(DoRemovePageCommand);
return _removePageCommand;
}
}
private void DoRemovePageCommand()
{
if (!Pages.Any()) return;
--PageCount;
RaisePropertyChanged(() => PageCount);
Pages.Remove(Pages.Last());
}
}
}
| using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using MvvmCross.Core.ViewModels;
namespace SampleMvx.Core.ViewModels
{
public class FirstViewModel
: MvxViewModel
{
public ObservableCollection<PageViewModel> Pages = new ObservableCollection<PageViewModel>();
private MvxCommand _addPageCommand;
public ICommand AddPageCommand
{
get
{
_addPageCommand = _addPageCommand ?? new MvxCommand(DoAddPageCommand);
return _addPageCommand;
}
}
public int PageCount { get; private set; }
private void DoAddPageCommand()
{
Pages.Add(new PageViewModel { Hello = $"Hello SGTabbedPager {++PageCount}"});
RaisePropertyChanged(() => PageCount);
}
private MvxCommand _removePageCommand;
public ICommand RemovePageCommand
{
get
{
_removePageCommand = _removePageCommand ?? new MvxCommand(DoRemovePageCommand);
return _removePageCommand;
}
}
private void DoRemovePageCommand()
{
if (!Pages.Any()) return;
Pages.Remove(Pages.Last());
--PageCount;
RaisePropertyChanged(() => PageCount);
}
}
}
| apache-2.0 | C# |
70e6aa0938437101f22fe7bc923ccabf6e191c43 | Fix postwriteahandler test | Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server | tests/Tgstation.Server.Host.Tests/IO/TestPostWriteHandler.cs | tests/Tgstation.Server.Host.Tests/IO/TestPostWriteHandler.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mono.Unix;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Tgstation.Server.Host.IO.Tests
{
[TestClass]
public sealed class TestPostWriteHandler
{
[TestMethod]
public void TestThrowsWithNullArg()
{
IPostWriteHandler postWriteHandler;
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWindows)
postWriteHandler = new WindowsPostWriteHandler();
else
postWriteHandler = new PosixPostWriteHandler();
Assert.ThrowsException<ArgumentNullException>(() => postWriteHandler.HandleWrite(null));
}
[TestMethod]
public void TestPostWrite()
{
IPostWriteHandler postWriteHandler;
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWindows)
postWriteHandler = new WindowsPostWriteHandler();
else
postWriteHandler = new PosixPostWriteHandler();
//test on a valid file first
var tmpFile = Path.GetTempFileName();
try
{
postWriteHandler.HandleWrite(tmpFile);
if (isWindows)
return; //you do nothing
//ensure it is now executable
File.WriteAllBytes(tmpFile, Encoding.UTF8.GetBytes("#!/bin/sh\n"));
using (var process = Process.Start(tmpFile))
{
process.WaitForExit();
Assert.AreEqual(0, process.ExitCode);
}
//run it again for the code coverage on that part where no changes are made if it's already executable
postWriteHandler.HandleWrite(tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[TestMethod]
public void TestThrowsOnUnix()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return;
var postWriteHandler = new PosixPostWriteHandler();
var tmpFile = Path.GetTempFileName();
File.Delete(tmpFile);
Assert.ThrowsException<UnixIOException>(() => postWriteHandler.HandleWrite(tmpFile));
Directory.CreateDirectory(tmpFile);
try
{
//can't +x a directory ;) (taps head)
Assert.ThrowsException<UnixIOException>(() => postWriteHandler.HandleWrite(tmpFile));
}
finally
{
Directory.Delete(tmpFile);
}
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mono.Unix;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Tgstation.Server.Host.IO.Tests
{
[TestClass]
public sealed class TestPostWriteHandler
{
[TestMethod]
public void TestThrowsWithNullArg()
{
IPostWriteHandler postWriteHandler;
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWindows)
postWriteHandler = new WindowsPostWriteHandler();
else
postWriteHandler = new PosixPostWriteHandler();
Assert.ThrowsException<ArgumentNullException>(() => postWriteHandler.HandleWrite(null));
}
[TestMethod]
public void TestPostWrite()
{
IPostWriteHandler postWriteHandler;
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWindows)
postWriteHandler = new WindowsPostWriteHandler();
else
postWriteHandler = new PosixPostWriteHandler();
//test on a valid file first
var tmpFile = Path.GetTempFileName();
try
{
postWriteHandler.HandleWrite(tmpFile);
if (isWindows)
return; //you do nothing
//ensure it is now executable
File.WriteAllBytes(tmpFile, Encoding.UTF8.GetBytes("#!/bin/sh\n"));
using (var process = Process.Start(tmpFile))
{
process.WaitForExit();
Assert.AreEqual(0, process.ExitCode);
}
//run it again for the code coverage on that part where no changes are made if it's already executable
postWriteHandler.HandleWrite(tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[TestMethod]
public void TestThrowsOnUnix()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return;
var postWriteHandler = new PosixPostWriteHandler();
var tmpFile = Path.GetTempFileName();
File.Delete(tmpFile);
Assert.ThrowsException<UnixIOException>(() => postWriteHandler.HandleWrite(tmpFile));
Directory.CreateDirectory(tmpFile);
try
{
//can't +x a directory ;) (taps head)
Assert.ThrowsException<UnixIOException>(() => postWriteHandler.HandleWrite(tmpFile));
}
finally
{
File.Delete(tmpFile);
}
}
}
}
| agpl-3.0 | C# |
deccbc2b4b1f0bffe164788fa4823579c380b8fa | fix some comments | skrusty/AsterNET,AsterNET/AsterNET | Asterisk.2013/Asterisk.NET/Manager/Event/MusicOnHoldEvent.cs | Asterisk.2013/Asterisk.NET/Manager/Event/MusicOnHoldEvent.cs | namespace AsterNET.Manager.Event
{
/// <summary>
/// The MusicOnHoldEvent event triggers when the music starts or ends playing the hold music.<br />
/// See <see target="_blank" href="LINK">LINK</see>
/// </summary>
public class MusicOnHoldEvent : ManagerEvent
{
/// <summary>
/// Creates a new empty <see cref="MusicOnHoldEvent"/> using the given <see cref="ManagerConnection"/>.
/// </summary>
public MusicOnHoldEvent(ManagerConnection source) : base(source)
{
}
/// <summary>
/// States
/// </summary>
public enum MusicOnHoldStates
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Music on hold is started.
/// </summary>
Start,
/// <summary>
/// Music on hold is stopped.
/// </summary>
Stop
}
/// <summary>
/// Get or set state
/// </summary>
public MusicOnHoldStates State { get; set; }
}
}
| namespace AsterNET.Manager.Event
{
/// <summary>
/// The MusicOnHoldEvent event triggers when the music starts or ends playing the hold music.
/// </summary>
public class MusicOnHoldEvent : ManagerEvent
{
/// <summary>
/// Creates a new instance of the class <see cref="MusicOnHoldEvent"/>.
/// </summary>
public MusicOnHoldEvent(ManagerConnection source) : base(source)
{
}
/// <summary>
/// States
/// </summary>
public enum MusicOnHoldStates
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Music on hold is started.
/// </summary>
Start,
/// <summary>
/// Music on hold is stoped.
/// </summary>
Stop
}
/// <summary>
/// Get or set state
/// </summary>
public MusicOnHoldStates State { get; set; }
}
}
| mit | C# |
6161cccd17c25c6e5f2452a3b6f2d29fef26a8ba | Fix test now. | trivalik/Cosmos,fanoI/Cosmos,fanoI/Cosmos,tgiphil/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,jp2masa/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,trivalik/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,trivalik/Cosmos,zarlo/Cosmos,tgiphil/Cosmos | Tests/Cosmos.Compiler.Tests.SimpleWriteLine.Kernel/Kernel.cs | Tests/Cosmos.Compiler.Tests.SimpleWriteLine.Kernel/Kernel.cs | using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.Debug.Kernel;
using Cosmos.TestRunner;
using Sys = Cosmos.System;
namespace Cosmos.Compiler.Tests.SimpleWriteLine.Kernel
{
public class Kernel : Sys.Kernel
{
protected override void BeforeRun()
{
var xMessage = "Cosmos booted successfully. Type a line of text to get it echoed back.";
Console.WriteLine(xMessage);
Debugger.DoSend("After writeline");
}
protected override void Run()
{
Debugger.DoSend("In Run");
try
{
Console.WriteLine("Started correctly!");
object x = 42;
Console.WriteLine(x.ToString());
Console.WriteLine("Done doing tests");
Assert.IsTrue(true, "Dummy assertion, to test the system");
Debugger.DoSend("Test TryFinally now");
TestTryFinally.Execute();
Assert.IsTrue(InterruptsEnabled, "Interrupts are not enabled!");
var xTempString = new String('a', 4);
Assert.AreEqual(4, xTempString.Length, "Dynamic string has wrong length!");
Assert.AreEqual(97, (int)xTempString[0], "First character of dynamic string is wrong!");
TestController.Completed();
}
catch (Exception E)
{
Console.WriteLine("Exception");
Console.WriteLine(E.ToString());
}
}
private static void DoPrint(int i)
{
Console.WriteLine(i.ToString());
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.Debug.Kernel;
using Cosmos.TestRunner;
using Sys = Cosmos.System;
namespace Cosmos.Compiler.Tests.SimpleWriteLine.Kernel
{
public class Kernel : Sys.Kernel
{
protected override void BeforeRun()
{
var xMessage = "Cosmos booted successfully. Type a line of text to get it echoed back.";
Console.WriteLine(xMessage);
Debugger.DoSend("After writeline");
}
protected override void Run()
{
Debugger.DoSend("In Run");
try
{
Console.WriteLine("Started correctly!");
object x = 42;
Console.WriteLine(x.ToString());
Console.WriteLine("Done doing tests");
Assert.IsTrue(true, "Dummy assertion, to test the system");
Debugger.DoSend("Test TryFinally now");
TestTryFinally.Execute();
Assert.IsTrue(InterruptsEnabled, "Interrupts are not enabled!");
var xTempString = new String('a', 4);
Assert.AreEqual(4, xTempString.Length, "Dynamic string has wrong length!");
Assert.AreEqual(97, (int)xTempString[0], "First character of dynamic string is wrong!");
Console.WriteLine(42);
DoPrint(42);
while (true)
;
//
//TestController.Completed();
}
catch (Exception E)
{
Console.WriteLine("Exception");
Console.WriteLine(E.ToString());
}
}
private static void DoPrint(int i)
{
Console.WriteLine(i.ToString());
}
}
}
| bsd-3-clause | C# |
5c346e339e4efc7ef619e9701cdcb3c53f616ab1 | Fix build | shana/handy-things | TrackingCollection/TrackingCollection/ITrackingCollection.cs | TrackingCollection/TrackingCollection/ITrackingCollection.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace GitHub.Collections
{
/// <summary>
/// TrackingCollection is a specialization of ObservableCollection that gets items from
/// an observable sequence and updates its contents in such a way that two updates to
/// the same object (as defined by an Equals call) will result in one object on
/// the list being updated (as opposed to having two different instances of the object
/// added to the list).
/// It is always sorted, either via the supplied comparer or using the default comparer
/// for T
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ITrackingCollection<T> : IDisposable, IList<T> where T : ICopyable<T>
{
/// <summary>
/// Sets up an observable as source for the collection.
/// </summary>
/// <param name="obs"></param>
/// <returns>An observable that will return all the items that are
/// fed via the original observer, for further processing by user code
/// if desired</returns>
IObservable<T> Listen(IObservable<T> obs);
IDisposable Subscribe();
IDisposable Subscribe(Action<T> onNext, Action onCompleted);
/// <summary>
/// Set a new comparer for the existing data. This will cause the
/// collection to be resorted and refiltered.
/// </summary>
/// <param name="theComparer">The comparer method for sorting, or null if not sorting</param>
void SetComparer(Func<T, T, int> comparer);
/// <summary>
/// Set a new filter. This will cause the collection to be filtered
/// </summary>
/// <param name="theFilter">The new filter, or null to not have any filtering</param>
void SetFilter(Func<T, int, IList<T>, bool> filter);
void AddItem(T item);
T RemoveItem(T item);
event NotifyCollectionChangedEventHandler CollectionChanged;
}
} | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace GitHub.Collections
{
/// <summary>
/// TrackingCollection is a specialization of ObservableCollection that gets items from
/// an observable sequence and updates its contents in such a way that two updates to
/// the same object (as defined by an Equals call) will result in one object on
/// the list being updated (as opposed to having two different instances of the object
/// added to the list).
/// It is always sorted, either via the supplied comparer or using the default comparer
/// for T
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ITrackingCollection<T> : IDisposable, IList<T> where T : ICopyable<T>
{
/// <summary>
/// Sets up an observable as source for the collection.
/// </summary>
/// <param name="obs"></param>
/// <returns>An observable that will return all the items that are
/// fed via the original observer, for further processing by user code
/// if desired</returns>
IObservable<T> Listen(IObservable<T> obs);
IDisposable Subscribe();
IDisposable Subscribe(Action<T> onNext, Action onCompleted);
/// <summary>
/// Set a new comparer for the existing data. This will cause the
/// collection to be resorted and refiltered.
/// </summary>
/// <param name="theComparer">The comparer method for sorting, or null if not sorting</param>
void SetComparer(Func<T, T, int> comparer);
/// <summary>
/// Set a new filter. This will cause the collection to be filtered
/// </summary>
/// <param name="theFilter">The new filter, or null to not have any filtering</param>
void SetFilter(Func<T, int, IList<T>, bool> filter);
void AddItem(T item);
void RemoveItem(T item);
event NotifyCollectionChangedEventHandler CollectionChanged;
}
} | mit | C# |
eb36539775a03e035b041db5c51ad0f6684be992 | Add CORS to embedded files | peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Server/Internal/Resources/EmbeddedFileResource.cs | src/Glimpse.Server/Internal/Resources/EmbeddedFileResource.cs | // ReSharper disable RedundantUsingDirective
using System;
// ReSharper restore RedundantUsingDirective
using System.Collections.Generic;
using System.Reflection;
using Glimpse.Server.Resources;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.StaticFiles;
namespace Glimpse.Server.Internal.Resources
{
public abstract class EmbeddedFileResource : IResourceStartup
{
public void Configure(IResourceBuilder resourceBuilder)
{
var appBuilder = resourceBuilder.AppBuilder;
appBuilder.ModifyResponseWith(response => response.EnableCaching());
appBuilder.ModifyResponseWith(res => res.EnableCors());
appBuilder.UseFileServer(new FileServerOptions
{
RequestPath = "",
EnableDefaultFiles = true,
FileProvider =
new EmbeddedFileProvider(typeof (EmbeddedFileResource).GetTypeInfo().Assembly, BaseNamespace)
});
foreach (var registration in Register)
{
resourceBuilder.RegisterResource(registration.Key, registration.Value);
}
}
public abstract ResourceType Type { get; }
public abstract string BaseNamespace { get; }
public abstract IDictionary<string, string> Register { get; }
}
public class ClientEmbeddedFileResource : EmbeddedFileResource
{
public override ResourceType Type => ResourceType.Client;
public override string BaseNamespace => "Glimpse.Server.Internal.Resources.Embeded.Client";
public override IDictionary<string, string> Register => new Dictionary<string, string>
{
{ "client", "index.html?hash={hash}{&requestId,follow,metadataUri}"},
{ "hud", "hud.js?hash={hash}" }
};
}
public class AgentEmbeddedFileResource : EmbeddedFileResource
{
public override ResourceType Type => ResourceType.Agent;
public override string BaseNamespace => "Glimpse.Server.Internal.Resources.Embeded.Agent";
public override IDictionary<string, string> Register => new Dictionary<string, string>
{
{ "agent", "agent.js?hash={hash}"}
};
}
} | // ReSharper disable RedundantUsingDirective
using System;
// ReSharper restore RedundantUsingDirective
using System.Collections.Generic;
using System.Reflection;
using Glimpse.Server.Resources;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.StaticFiles;
namespace Glimpse.Server.Internal.Resources
{
public abstract class EmbeddedFileResource : IResourceStartup
{
public void Configure(IResourceBuilder resourceBuilder)
{
var appBuilder = resourceBuilder.AppBuilder;
appBuilder.ModifyResponseWith(response => response.EnableCaching());
appBuilder.UseFileServer(new FileServerOptions
{
RequestPath = "",
EnableDefaultFiles = true,
FileProvider =
new EmbeddedFileProvider(typeof (EmbeddedFileResource).GetTypeInfo().Assembly, BaseNamespace)
});
foreach (var registration in Register)
{
resourceBuilder.RegisterResource(registration.Key, registration.Value);
}
}
public abstract ResourceType Type { get; }
public abstract string BaseNamespace { get; }
public abstract IDictionary<string, string> Register { get; }
}
public class ClientEmbeddedFileResource : EmbeddedFileResource
{
public override ResourceType Type => ResourceType.Client;
public override string BaseNamespace => "Glimpse.Server.Internal.Resources.Embeded.Client";
public override IDictionary<string, string> Register => new Dictionary<string, string>
{
{ "client", "index.html?hash={hash}{&requestId,follow,metadataUri}"},
{ "hud", "hud.js?hash={hash}" }
};
}
public class AgentEmbeddedFileResource : EmbeddedFileResource
{
public override ResourceType Type => ResourceType.Agent;
public override string BaseNamespace => "Glimpse.Server.Internal.Resources.Embeded.Agent";
public override IDictionary<string, string> Register => new Dictionary<string, string>
{
{ "agent", "agent.js?hash={hash}"}
};
}
} | mit | C# |
d6aeedf11cc5757761f1a1ac3060bb1c56d4f70d | Hide nick, more secrets | w-l0f/PegBot | PegBot/Plugins/RandomPlugin.cs | PegBot/Plugins/RandomPlugin.cs | using Meebey.SmartIrc4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PegBot.Plugins
{
class RandomPlugin : BotPlugin
{
Random rnd;
public RandomPlugin(IrcClient irc)
: base(irc, "random")
{
rnd = new Random();
RegisterCommand(".roll", "[max]", "Roll a random number between 1 and 100 or [max]", OnRoll, arg => String.IsNullOrEmpty(arg) || Regex.IsMatch(arg, @"^\d+$"), false);
RegisterCommand(".magic8ball", "<question>", "Ask question to the magic 8 ball", OnMagic, false);
}
private void OnRoll(string arg, string channel, string nick, string replyTo)
{
int roll = String.IsNullOrEmpty(arg) ? rnd.Next(100) + 1 : rnd.Next(Int32.Parse(arg)) + 1; //they see me rollin
irc.SendMessage(SendType.Message, replyTo, nick + ": " + roll);
}
private void OnMagic(string arg, string channel, string nick, string replyTo)
{
string[] anwsers = {
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"};
irc.SendMessage(SendType.Message, channel, arg + " - " + anwsers[rnd.Next(anwsers.Length)]);
}
}
}
| using Meebey.SmartIrc4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PegBot.Plugins
{
class RandomPlugin : BotPlugin
{
Random rnd;
public RandomPlugin(IrcClient irc)
: base(irc, "random")
{
rnd = new Random();
RegisterCommand(".roll", "[max]", "Roll a random number between 1 and 100 or [max]", OnRoll, arg => String.IsNullOrEmpty(arg) || Regex.IsMatch(arg, @"^\d+$"), false);
RegisterCommand(".magic8ball", "<question>", "Ask question to the magic 8 ball", OnMagic, false);
}
private void OnRoll(string arg, string channel, string nick, string replyTo)
{
int roll = String.IsNullOrEmpty(arg) ? rnd.Next(100) + 1 : rnd.Next(Int32.Parse(arg)) + 1; //they see me rollin
irc.SendMessage(SendType.Message, replyTo, nick + ": " + roll);
}
private void OnMagic(string arg, string channel, string nick, string replyTo)
{
string[] anwsers = {
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"};
irc.SendMessage(SendType.Message, channel, nick + ": " + arg + " - " + anwsers[rnd.Next(anwsers.Length)]);
}
}
}
| mit | C# |
103f0be0536db9e04b94a08b7c20fe4091a7a7f4 | Bump version to 0.8.4 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.8.4")]
[assembly: AssemblyInformationalVersionAttribute("0.8.4")]
[assembly: AssemblyFileVersionAttribute("0.8.4")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.8.4";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.8.3")]
[assembly: AssemblyInformationalVersionAttribute("0.8.3")]
[assembly: AssemblyFileVersionAttribute("0.8.3")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.8.3";
}
}
| apache-2.0 | C# |
49e8d31f6dc4bca8c06ba32711923b24afd364fe | Bump version to 0.15.1 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.15.1")]
[assembly: AssemblyInformationalVersionAttribute("0.15.1")]
[assembly: AssemblyFileVersionAttribute("0.15.1")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.15.1";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.15.0")]
[assembly: AssemblyInformationalVersionAttribute("0.15.0")]
[assembly: AssemblyFileVersionAttribute("0.15.0")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.15.0";
}
}
| apache-2.0 | C# |
026d36412c007fd48e1122e09bc29ee65e012554 | Enable all warnings in 'InvalidAssertionMessageHighlightingTests' (except for the error test) | ulrichb/Roflcopter,ulrichb/Roflcopter | Src/Roflcopter.Plugin.Tests/AssertionMessages/InvalidAssertionMessageHighlightingTests.cs | Src/Roflcopter.Plugin.Tests/AssertionMessages/InvalidAssertionMessageHighlightingTests.cs | using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;
#if !RS20171
using Roflcopter.Plugin.AssertionMessages;
#endif
namespace Roflcopter.Plugin.Tests.AssertionMessages
{
[TestFixture]
[TestNetFramework4]
public class InvalidAssertionMessageHighlightingTests : CSharpHighlightingTestBase
{
[Test]
public void AssertionMessageContractAnnotationSamples() => DoNamedTest();
[Test]
public void AssertionMessageExtensionMethodSamples() => DoNamedTest();
#if !RS20171
[Test]
[HighlightOnly(typeof(InvalidAssertionMessageHighlighting))]
public void AssertionMessageErrorSamples() => DoNamedTest();
#endif
[Test]
public void AssertionMessageLegacyAnnotationSamples() => DoNamedTest();
}
}
| using JetBrains.Annotations;
using JetBrains.ReSharper.Daemon.CSharp.Errors;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.FeaturesTestFramework.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.TestFramework;
using NUnit.Framework;
using Roflcopter.Plugin.AssertionMessages;
namespace Roflcopter.Plugin.Tests.AssertionMessages
{
[TestFixture]
[TestNetFramework4]
public class InvalidAssertionMessageHighlightingTests : CSharpHighlightingTestBase
{
protected override bool HighlightingPredicate([NotNull] IHighlighting highlighting, [CanBeNull] IPsiSourceFile _)
{
return highlighting is InvalidAssertionMessageHighlighting ||
highlighting is ConditionIsAlwaysTrueOrFalseWarning ||
highlighting is HeuristicUnreachableCodeWarning;
}
[Test]
public void AssertionMessageContractAnnotationSamples() => DoNamedTest();
[Test]
public void AssertionMessageExtensionMethodSamples() => DoNamedTest();
[Test]
public void AssertionMessageErrorSamples() => DoNamedTest();
[Test]
public void AssertionMessageLegacyAnnotationSamples() => DoNamedTest();
}
}
| mit | C# |
ce21b2cf7d50170524d83108a1617f2462e00d59 | Use expression for filtering. | Picturepark/Picturepark.SDK.DotNet | samples/Picturepark.Microsite.Example/Repository/PressReleaseRepository.cs | samples/Picturepark.Microsite.Example/Repository/PressReleaseRepository.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Picturepark.Microsite.Example.Contracts;
using Picturepark.SDK.V1.Contract;
using Picturepark.Microsite.Example.Services;
using Picturepark.SDK.V1.Contract.Extensions;
namespace Picturepark.Microsite.Example.Repository
{
public class PressReleaseRepository : IPressReleaseRepository
{
private readonly IPictureparkAccessTokenService _client;
public PressReleaseRepository(IPictureparkAccessTokenService client)
{
_client = client;
}
public async Task<List<ContentItem<PressRelease>>> List(int start, int limit, string searchString)
{
var searchResult = await _client.Content.SearchAsync(new ContentSearchRequest
{
Start = start,
Limit = limit,
SearchString = searchString,
Filter = new AndFilter
{
Filters = new List<FilterBase>
{
// Limit to PressRelease content
FilterBase.FromExpression<Content>(i => i.ContentSchemaId, nameof(PressRelease)),
// Filter out future publications
new DateRangeFilter
{
Field = "pressRelease.publishDate",
Range = new DateRange
{
To = "now"
}
}
}
},
Sort = new List<SortInfo>
{
new SortInfo { Field = "pressRelease.publishDate", Direction = SortDirection.Desc }
}
});
// Fetch details
var contents = searchResult.Results.Any()
? await _client.Content.GetManyAsync(searchResult.Results.Select(i => i.Id),
new[]
{
ContentResolveBehaviour.Content
})
: new List<ContentDetail>();
// Convert to C# poco
var pressPortals = contents.AsContentItems<PressRelease>().ToList();
return pressPortals;
}
public async Task<ContentItem<PressRelease>> Get(string id)
{
var content = await _client.Content.GetAsync(id, new[] { ContentResolveBehaviour.Content });
return content.AsContentItem<PressRelease>();
}
public async Task<List<SearchResult>> Search(int start, int limit, string searchString)
{
var result = await List(start, limit, searchString);
return result.Select(i => new SearchResult { Id = i.Id, Title = i.Content.Headline.GetTranslation(), Description = i.Content.Teaser.GetTranslation() }).ToList();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Picturepark.Microsite.Example.Contracts;
using Picturepark.SDK.V1.Contract;
using Picturepark.Microsite.Example.Services;
using Picturepark.SDK.V1.Contract.Extensions;
namespace Picturepark.Microsite.Example.Repository
{
public class PressReleaseRepository : IPressReleaseRepository
{
private readonly IPictureparkAccessTokenService _client;
public PressReleaseRepository(IPictureparkAccessTokenService client)
{
_client = client;
}
public async Task<List<ContentItem<PressRelease>>> List(int start, int limit, string searchString)
{
var searchResult = await _client.Content.SearchAsync(new ContentSearchRequest
{
Start = start,
Limit = limit,
SearchString = searchString,
Filter = new AndFilter
{
Filters = new List<FilterBase>
{
// Limit to PressRelease content
new TermFilter
{
Field = "contentSchemaId",
Term = "PressRelease"
},
// Filter out future publications
new DateRangeFilter
{
Field = "pressRelease.publishDate",
Range = new DateRange
{
To = "now"
}
}
}
},
Sort = new List<SortInfo>
{
new SortInfo { Field = "pressRelease.publishDate", Direction = SortDirection.Desc }
}
});
// Fetch details
var contents = searchResult.Results.Any()
? await _client.Content.GetManyAsync(searchResult.Results.Select(i => i.Id),
new[]
{
ContentResolveBehaviour.Content
})
: new List<ContentDetail>();
// Convert to C# poco
var pressPortals = contents.AsContentItems<PressRelease>().ToList();
return pressPortals;
}
public async Task<ContentItem<PressRelease>> Get(string id)
{
var content = await _client.Content.GetAsync(id, new[] { ContentResolveBehaviour.Content });
return content.AsContentItem<PressRelease>();
}
public async Task<List<SearchResult>> Search(int start, int limit, string searchString)
{
var result = await List(start, limit, searchString);
return result.Select(i => new SearchResult { Id = i.Id, Title = i.Content.Headline.GetTranslation(), Description = i.Content.Teaser.GetTranslation() }).ToList();
}
}
}
| mit | C# |
2226c768492f57a41ccb7b20b98f1bb4af5a6581 | Update FileData.cs | A51UK/File-Repository | File-Repository/FileData.cs | File-Repository/FileData.cs | /*
* Copyright 2017 Craig Lee Mark Adams
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.Collections.Generic;
using System.Text;
using System.IO;
namespace File_Repository
{
public class FileData
{
public MemoryStream Stream { get; set; } = null;
public string Type { get; set; } = string.Empty;
public string Loc { get; set; } = string.Empty;
}
}
| /*
* Copyright 2017 Criag Lee Mark Adams
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.Collections.Generic;
using System.Text;
using System.IO;
namespace File_Repository
{
public class FileData
{
public MemoryStream Stream { get; set; } = null;
public string Type { get; set; } = string.Empty;
public string Loc { get; set; } = string.Empty;
}
}
| apache-2.0 | C# |
44fe6aa6acdbeb0fea761b2a136046356ce06a82 | Fix failing unit tests. | AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,MrDaedra/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,grokys/Perspex | tests/Avalonia.Base.UnitTests/AvaloniaObjectTests_Attached.cs | tests/Avalonia.Base.UnitTests/AvaloniaObjectTests_Attached.cs | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Xunit;
namespace Avalonia.Base.UnitTests
{
public class AvaloniaObjectTests_Attached
{
[Fact]
public void AddOwnered_Property_Retains_Default_Value()
{
var target = new Class2();
Assert.Equal("foodefault", target.GetValue(Class2.FooProperty));
}
[Fact]
public void AddOwnered_Property_Retains_Validation()
{
var target = new Class2();
Assert.Throws<IndexOutOfRangeException>(() => target.SetValue(Class2.FooProperty, "throw"));
}
[Fact]
public void AvaloniaProperty_Initialized_Is_Called_For_Attached_Property()
{
bool raised = false;
using (Class1.FooProperty.Initialized.Subscribe(x => raised = true))
{
new Class3();
}
Assert.True(raised);
}
private class Base : AvaloniaObject
{
}
private class Class1 : Base
{
public static readonly AttachedProperty<string> FooProperty =
AvaloniaProperty.RegisterAttached<Class1, Base, string>(
"Foo",
"foodefault",
validate: ValidateFoo);
private static string ValidateFoo(AvaloniaObject arg1, string arg2)
{
if (arg2 == "throw")
{
throw new IndexOutOfRangeException();
}
return arg2;
}
}
private class Class2 : Base
{
public static readonly AttachedProperty<string> FooProperty =
Class1.FooProperty.AddOwner<Class2>();
}
private class Class3 : Base
{
}
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Xunit;
namespace Avalonia.Base.UnitTests
{
public class AvaloniaObjectTests_Attached
{
[Fact]
public void AddOwnered_Property_Retains_Default_Value()
{
var target = new Class2();
Assert.Equal("foodefault", target.GetValue(Class2.FooProperty));
}
[Fact]
public void AddOwnered_Property_Retains_Validation()
{
var target = new Class2();
Assert.Throws<IndexOutOfRangeException>(() => target.SetValue(Class2.FooProperty, "throw"));
}
[Fact]
public void AvaloniaProperty_Initialized_Is_Called_For_Attached_Property()
{
bool raised = false;
using (Class1.FooProperty.Initialized.Subscribe(x => raised = true))
{
new Class3();
}
Assert.True(raised);
}
private class Class1 : AvaloniaObject
{
public static readonly AttachedProperty<string> FooProperty =
AvaloniaProperty.RegisterAttached<Class1, AvaloniaObject, string>(
"Foo",
"foodefault",
validate: ValidateFoo);
private static string ValidateFoo(AvaloniaObject arg1, string arg2)
{
if (arg2 == "throw")
{
throw new IndexOutOfRangeException();
}
return arg2;
}
}
private class Class2 : AvaloniaObject
{
public static readonly AttachedProperty<string> FooProperty =
Class1.FooProperty.AddOwner<Class2>();
}
private class Class3 : AvaloniaObject
{
}
}
}
| mit | C# |
8ab09e06b6e810794681e9fc43e40fcf647ce149 | Remove compile warning. | mono/taglib-sharp,punker76/taglib-sharp,punker76/taglib-sharp,CamargoR/taglib-sharp,hwahrmann/taglib-sharp,Clancey/taglib-sharp,Clancey/taglib-sharp,archrival/taglib-sharp,Clancey/taglib-sharp,archrival/taglib-sharp,CamargoR/taglib-sharp,hwahrmann/taglib-sharp | tests/fixtures/TagLib.Tests.Images/JpegSegmentSizeTest.cs | tests/fixtures/TagLib.Tests.Images/JpegSegmentSizeTest.cs | using System;
using NUnit.Framework;
using TagLib;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.Jpeg;
using TagLib.Xmp;
namespace TagLib.Tests.Images
{
[TestFixture]
public class JpegSegmentSizeTest
{
private static string sample_file = "samples/sample.jpg";
private static string tmp_file = "samples/tmpwrite_exceed_segment_size.jpg";
private static int max_segment_size = 0xFFFF;
private TagTypes contained_types =
TagTypes.JpegComment |
TagTypes.TiffIFD |
TagTypes.XMP;
private string CreateDataString (int min_size)
{
string src = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ByteVector data = new ByteVector ();
for (int i = 0; data.Count < min_size; i++)
{
int index = i % src.Length;
data.Add (src.Substring (index, src.Length - index));
}
return data.ToString ();
}
[Test]
public void ExifExceed ()
{
File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File;
CheckTags (tmp);
var exif_tag = tmp.GetTag (TagTypes.TiffIFD) as IFDTag;
Assert.IsNotNull (exif_tag, "exif tag");
// ensure data is big enough
exif_tag.Comment = CreateDataString (max_segment_size);
Assert.IsFalse (SaveFile (tmp), "file with exceed exif segment saved");
}
[Test]
public void XmpExceed ()
{
File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File;
CheckTags (tmp);
var xmp_tag = tmp.GetTag (TagTypes.XMP) as XmpTag;
Assert.IsNotNull (xmp_tag, "xmp tag");
// ensure data is big enough
xmp_tag.Comment = CreateDataString (max_segment_size);
Assert.IsFalse (SaveFile (tmp), "file with exceed xmp segment saved");
}
[Test]
public void JpegCommentExceed ()
{
File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File;
CheckTags (tmp);
var com_tag = tmp.GetTag (TagTypes.JpegComment) as JpegCommentTag;
Assert.IsNotNull (com_tag, "comment tag");
// ensure data is big enough
com_tag.Comment = CreateDataString (max_segment_size);
Assert.IsFalse (SaveFile (tmp), "file with exceed comment segment saved");
}
private void CheckTags (File file) {
Assert.IsTrue (file is Jpeg.File, "not a Jpeg file");
Assert.AreEqual (contained_types, file.TagTypes);
Assert.AreEqual (contained_types, file.TagTypesOnDisk);
}
private bool SaveFile (File file)
{
try {
file.Save ();
} catch (Exception) {
return false;
}
return true;
}
}
}
| using System;
using NUnit.Framework;
using TagLib;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.Jpeg;
using TagLib.Xmp;
namespace TagLib.Tests.Images
{
[TestFixture]
public class JpegSegmentSizeTest
{
private static string sample_file = "samples/sample.jpg";
private static string tmp_file = "samples/tmpwrite_exceed_segment_size.jpg";
private static int max_segment_size = 0xFFFF;
private TagTypes contained_types =
TagTypes.JpegComment |
TagTypes.TiffIFD |
TagTypes.XMP;
private string CreateDataString (int min_size)
{
string src = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ByteVector data = new ByteVector ();
for (int i = 0; data.Count < min_size; i++)
{
int index = i % src.Length;
data.Add (src.Substring (index, src.Length - index));
}
return data.ToString ();
}
[Test]
public void ExifExceed ()
{
File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File;
CheckTags (tmp);
var exif_tag = tmp.GetTag (TagTypes.TiffIFD) as IFDTag;
Assert.IsNotNull (exif_tag, "exif tag");
// ensure data is big enough
exif_tag.Comment = CreateDataString (max_segment_size);
Assert.IsFalse (SaveFile (tmp), "file with exceed exif segment saved");
}
[Test]
public void XmpExceed ()
{
File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File;
CheckTags (tmp);
var xmp_tag = tmp.GetTag (TagTypes.XMP) as XmpTag;
Assert.IsNotNull (xmp_tag, "xmp tag");
// ensure data is big enough
xmp_tag.Comment = CreateDataString (max_segment_size);
Assert.IsFalse (SaveFile (tmp), "file with exceed xmp segment saved");
}
[Test]
public void JpegCommentExceed ()
{
File tmp = Utils.CreateTmpFile (sample_file, tmp_file) as File;
CheckTags (tmp);
var com_tag = tmp.GetTag (TagTypes.JpegComment) as JpegCommentTag;
Assert.IsNotNull (com_tag, "comment tag");
// ensure data is big enough
com_tag.Comment = CreateDataString (max_segment_size);
Assert.IsFalse (SaveFile (tmp), "file with exceed comment segment saved");
}
private void CheckTags (File file) {
Assert.IsTrue (file is Jpeg.File, "not a Jpeg file");
Assert.AreEqual (contained_types, file.TagTypes);
Assert.AreEqual (contained_types, file.TagTypesOnDisk);
}
private bool SaveFile (File file)
{
try {
file.Save ();
} catch (Exception e) {
return false;
}
return true;
}
}
}
| lgpl-2.1 | C# |
62ff03224be369f835d5f99392bde48db5eec204 | Fix a typo in a comment | jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm | standard-library/Int32.cs | standard-library/Int32.cs | namespace System
{
/// <summary>
/// Represents a 32-bit integer.
/// </summary>
public struct Int32
{
// Note: integers are equivalent to instances of this data structure because
// flame-llvm stores the contents of single-field structs as a value of their
// field, rather than as a LLVM struct. So a 32-bit integer becomes an i32 and
// so does a `System.Int32`. So don't add, remove, or edit the fields in this
// struct.
private int value;
/// <summary>
/// Converts this integer to a string representation.
/// </summary>
/// <returns>The string representation for the integer.</returns>
public string ToString()
{
return Convert.ToString(value);
}
}
} | namespace System
{
/// <summary>
/// Represents a 32-bit integer.
/// </summary>
public struct Int32
{
// Note: integers are equivalent to instances of this data structure because
// flame-llvm the contents of single-field structs as a value of their single
// field, rather than as a LLVM struct. So a 32-bit integer becomes an i32 and
// so does a `System.Int32`. So don't add, remove, or edit the fields in this
// struct.
private int value;
/// <summary>
/// Converts this integer to a string representation.
/// </summary>
/// <returns>The string representation for the integer.</returns>
public string ToString()
{
return Convert.ToString(value);
}
}
} | mit | C# |
998d90a51eb05b73bec18c75924be24aa2cc9e29 | Set working directory for launched processes | danielchalmers/WpfAboutView | WpfAboutView/AboutView.xaml.cs | WpfAboutView/AboutView.xaml.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfAboutView
{
/// <summary>
/// Interaction logic for AboutView.xaml
/// </summary>
public partial class AboutView : UserControl
{
public static readonly DependencyProperty AppIconSourceProperty =
DependencyProperty.Register(
nameof(AppIconSource),
typeof(Uri),
typeof(AboutView));
public static readonly DependencyProperty AssemblyProperty =
DependencyProperty.Register(
nameof(Assembly),
typeof(Assembly),
typeof(AboutView),
new PropertyMetadata(Assembly.GetEntryAssembly()));
public static readonly DependencyProperty CreditsProperty =
DependencyProperty.Register(
nameof(Credits),
typeof(List<Credit>),
typeof(AboutView),
new FrameworkPropertyMetadata(new List<Credit>(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public AboutView()
{
InitializeComponent();
ProcessStartCommand = new ProcessStartCommand();
}
public Uri AppIconSource
{
get => (Uri)GetValue(AppIconSourceProperty);
set => SetValue(AppIconSourceProperty, value);
}
public string AppName => Assembly.GetTitle();
public Version AppVersion => Assembly.GetVersion();
public Assembly Assembly
{
get => (Assembly)GetValue(AssemblyProperty);
set => SetValue(AssemblyProperty, value);
}
public List<Credit> Credits
{
get => (List<Credit>)GetValue(CreditsProperty);
set => SetValue(CreditsProperty, value);
}
public ICommand ProcessStartCommand { get; }
private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo
{
FileName = e.Uri.ToString(),
WorkingDirectory = Assembly.GetDirectory(),
UseShellExecute = true
});
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfAboutView
{
/// <summary>
/// Interaction logic for AboutView.xaml
/// </summary>
public partial class AboutView : UserControl
{
public static readonly DependencyProperty AppIconSourceProperty =
DependencyProperty.Register(
nameof(AppIconSource),
typeof(Uri),
typeof(AboutView));
public static readonly DependencyProperty AssemblyProperty =
DependencyProperty.Register(
nameof(Assembly),
typeof(Assembly),
typeof(AboutView),
new PropertyMetadata(Assembly.GetEntryAssembly()));
public static readonly DependencyProperty CreditsProperty =
DependencyProperty.Register(
nameof(Credits),
typeof(List<Credit>),
typeof(AboutView),
new FrameworkPropertyMetadata(new List<Credit>(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public AboutView()
{
InitializeComponent();
ProcessStartCommand = new ProcessStartCommand();
}
public Uri AppIconSource
{
get => (Uri)GetValue(AppIconSourceProperty);
set => SetValue(AppIconSourceProperty, value);
}
public string AppName => Assembly.GetTitle();
public Version AppVersion => Assembly.GetVersion();
public Assembly Assembly
{
get => (Assembly)GetValue(AssemblyProperty);
set => SetValue(AssemblyProperty, value);
}
public List<Credit> Credits
{
get => (List<Credit>)GetValue(CreditsProperty);
set => SetValue(CreditsProperty, value);
}
public ICommand ProcessStartCommand { get; }
private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo { FileName = e.Uri.ToString(), UseShellExecute = true });
}
}
} | mit | C# |
ea65de89f93eb5c4b0958483d65e919f68c96fde | Add keyboard shortcut Cmd-Shift-R to run tests. | tenpn/untest,tenpn/untest | Assets/UnTest/Editor/UnityTestRunner.cs | Assets/UnTest/Editor/UnityTestRunner.cs | /*
Copyright(c) 2013 Andrew Fray
Licensed under the MIT license. See the license.txt file for full details.
*/
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
namespace UnTest {
// runs all unity tests it can find. run from console like this:
// /path/to/unity -projectPath "path/to/project" -batchmode -logFile -executeMethod TestRunner.RunTestsFromConsole -quit
// also run from Assets/Tests/Run menu.
public class UnityTestRunner {
public static void RunTestsFromConsole() {
var results = TestRunner.RunAllTests();
if (TestRunner.OutputTestResults(results, Debug.LogError) == false) {
EditorApplication.Exit(-1);
}
}
[MenuItem("Assets/Tests/Run #%r")]
public static void RunTestsFromEditor() {
var results = TestRunner.RunAllTests();
Debug.Log("Executed " + results.TotalTestsRun + " tests");
if (results.Failures.Any() == false) {
Debug.Log("All tests passed");
} else {
// file names have a full path, but that takes up a lot of log window.
// unity can still function if we take the project as root.
string assetsRoot = Application.dataPath; // /path/to/proj/assets
string projectRoot = assetsRoot.Substring(0,
assetsRoot.Length - "/Assets".Length);
int rootToTrim = projectRoot.Length;
Func<string,string> tryTrimProjectRoot = msg => {
if (msg.StartsWith(projectRoot)) {
return msg.Substring(rootToTrim);
} else {
return msg;
}
};
var failureOutput = TestRunner.CalculateFailureString(results.Failures);
foreach(var failureMessage in failureOutput) {
var sanitisedSubject = tryTrimProjectRoot(failureMessage.Subject);
Debug.LogError(sanitisedSubject + "\n" + failureMessage.Body);
}
}
}
}
} | /*
Copyright(c) 2013 Andrew Fray
Licensed under the MIT license. See the license.txt file for full details.
*/
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
namespace UnTest {
// runs all unity tests it can find. run from console like this:
// /path/to/unity -projectPath "path/to/project" -batchmode -logFile -executeMethod TestRunner.RunTestsFromConsole -quit
// also run from Assets/Tests/Run menu.
public class UnityTestRunner {
public static void RunTestsFromConsole() {
var results = TestRunner.RunAllTests();
if (TestRunner.OutputTestResults(results, Debug.LogError) == false) {
EditorApplication.Exit(-1);
}
}
[MenuItem("Assets/Tests/Run")]
public static void RunTestsFromEditor() {
var results = TestRunner.RunAllTests();
Debug.Log("Executed " + results.TotalTestsRun + " tests");
if (results.Failures.Any() == false) {
Debug.Log("All tests passed");
} else {
// file names have a full path, but that takes up a lot of log window.
// unity can still function if we take the project as root.
string assetsRoot = Application.dataPath; // /path/to/proj/assets
string projectRoot = assetsRoot.Substring(0,
assetsRoot.Length - "/Assets".Length);
int rootToTrim = projectRoot.Length;
Func<string,string> tryTrimProjectRoot = msg => {
if (msg.StartsWith(projectRoot)) {
return msg.Substring(rootToTrim);
} else {
return msg;
}
};
var failureOutput = TestRunner.CalculateFailureString(results.Failures);
foreach(var failureMessage in failureOutput) {
var sanitisedSubject = tryTrimProjectRoot(failureMessage.Subject);
Debug.LogError(sanitisedSubject + "\n" + failureMessage.Body);
}
}
}
}
} | mit | C# |
3b86d440fe35111aa94c0191453618fdc1eb8a2f | split only if he has enough money | gogus4/BlackJacker | BlackJacker/BlackJacker/Model/Joueur.cs | BlackJacker/BlackJacker/Model/Joueur.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlackJacker.Model
{
public class Joueur : Personne
{
public double jeton { get; set; }
public List<Carte> listSplit { get; set; }
public Boolean isSplit { get; set; }
public int mise { get; set; }
public Joueur()
{
InitialiserJeton();
listSplit = new List<Carte>();
}
public Boolean Split()
{
if (jeton > mise)
{
if (listSimple[0].nom == listSimple[1].nom)
{
listSplit.Add(listSimple[1]);
listSimple.Remove(listSimple[1]);
isSplit = true;
return true;
}
}
return false;
}
public void InitialiserJeton()
{
jeton = 100;
}
public void Miserjeton(int valueMiser)
{
mise = valueMiser;
jeton -= mise;
}
public void AjouterSplit(Carte carte)
{
listSplit.Add(carte);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlackJacker.Model
{
public class Joueur : Personne
{
public double jeton { get; set; }
public List<Carte> listSplit { get; set; }
public Boolean isSplit { get; set; }
public int mise { get; set; }
public Joueur()
{
InitialiserJeton();
listSplit = new List<Carte>();
}
public Boolean Split()
{
if (listSimple[0].nom == listSimple[1].nom)
{
listSplit.Add(listSimple[1]);
listSimple.Remove(listSimple[1]);
isSplit = true;
return true;
}
return false;
}
public void InitialiserJeton()
{
jeton = 100;
}
public void Miserjeton(int valueMiser)
{
mise = valueMiser;
jeton -= mise;
}
public void AjouterSplit(Carte carte)
{
listSplit.Add(carte);
}
}
}
| apache-2.0 | C# |
c8e8d2dcd417174734c6138ade83a4741444cc79 | Change database to unblock tests | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Identity.Entity/IdentitySqlContext.cs | src/Microsoft.AspNet.Identity.Entity/IdentitySqlContext.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.AspNet.Identity.Entity
{
public class IdentitySqlContext :
IdentitySqlContext<User>
{
public IdentitySqlContext() { }
public IdentitySqlContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentitySqlContext(DbContextOptions options) : base(options) { }
public IdentitySqlContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
}
public class IdentitySqlContext<TUser> : DbContext
where TUser : User
{
public DbSet<TUser> Users { get; set; }
public DbSet<IdentityUserClaim> UserClaims { get; set; }
//public DbSet<TRole> Roles { get; set; }
public IdentitySqlContext() { }
public IdentitySqlContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentitySqlContext(DbContextOptions options) : base(options) { }
public IdentitySqlContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
protected override void OnConfiguring(DbContextOptions builder)
{
// TODO: pull connection string from config
builder.UseSqlServer(@"Server=(localdb)\v11.0;Database=SimpleIdentity-5-28;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>()
.Key(u => u.Id)
.Properties(ps => ps.Property(u => u.UserName))
.ToTable("AspNetUsers");
builder.Entity<IdentityUserClaim>()
.Key(uc => uc.Id)
// TODO: this throws a length exception currently, investigate
//.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
.ToTable("AspNetUserClaims");
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.AspNet.Identity.Entity
{
public class IdentitySqlContext :
IdentitySqlContext<User>
{
public IdentitySqlContext() { }
public IdentitySqlContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentitySqlContext(DbContextOptions options) : base(options) { }
public IdentitySqlContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
}
public class IdentitySqlContext<TUser> : DbContext
where TUser : User
{
public DbSet<TUser> Users { get; set; }
public DbSet<IdentityUserClaim> UserClaims { get; set; }
//public DbSet<TRole> Roles { get; set; }
public IdentitySqlContext() { }
public IdentitySqlContext(IServiceProvider serviceProvider) : base(serviceProvider) { }
public IdentitySqlContext(DbContextOptions options) : base(options) { }
public IdentitySqlContext(IServiceProvider serviceProvider, DbContextOptions options) : base(serviceProvider, options) { }
protected override void OnConfiguring(DbContextOptions builder)
{
// TODO: pull connection string from config
builder.UseSqlServer(@"Server=(localdb)\v11.0;Database=SimpleIdentity;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>()
.Key(u => u.Id)
.Properties(ps => ps.Property(u => u.UserName))
.ToTable("AspNetUsers");
builder.Entity<IdentityUserClaim>()
.Key(uc => uc.Id)
// TODO: this throws a length exception currently, investigate
//.ForeignKeys(fk => fk.ForeignKey<TUser>(f => f.UserId))
.ToTable("AspNetUserClaims");
}
}
} | apache-2.0 | C# |
ffb6070af8a417ec256738cfbd681ba15c7aa787 | Add a Started indicator to Eto.Forms.UITimer. | bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto,l8s/Eto,PowerOfCode/Eto | Source/Eto/Forms/UITimer.cs | Source/Eto/Forms/UITimer.cs | using System;
namespace Eto.Forms
{
public interface IUITimer : IInstanceWidget
{
double Interval { get; set; }
void Start ();
void Stop ();
}
public class UITimer : InstanceWidget
{
new IUITimer Handler { get { return (IUITimer)base.Handler; } }
public static double DefaultInterval = 1.0; // 1 second
public event EventHandler<EventArgs> Elapsed;
public virtual void OnElapsed (EventArgs e)
{
if (Elapsed != null)
Elapsed (this, e);
}
public UITimer()
: this((Generator)null)
{
}
public UITimer (Generator generator) : this (generator, typeof(IUITimer))
{
}
protected UITimer (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
}
/// <summary>
/// Gets or sets the interval, in seconds
/// </summary>
public double Interval {
get { return Handler.Interval; }
set { Handler.Interval = value; }
}
/// <summary>
/// Gets a value indicating whether this <see cref="Eto.Forms.UITimer"/> is started.
/// </summary>
/// <value><c>true</c> if started; otherwise, <c>false</c>.</value>
public bool Started { get; private set; }
public void Start ()
{
Started = true;
Handler.Start ();
}
public void Stop ()
{
Started = false;
Handler.Stop ();
}
}
}
| using System;
namespace Eto.Forms
{
public interface IUITimer : IInstanceWidget
{
double Interval { get; set; }
void Start ();
void Stop ();
}
public class UITimer : InstanceWidget
{
new IUITimer Handler { get { return (IUITimer)base.Handler; } }
public static double DefaultInterval = 1.0; // 1 second
public event EventHandler<EventArgs> Elapsed;
public virtual void OnElapsed (EventArgs e)
{
if (Elapsed != null)
Elapsed (this, e);
}
public UITimer()
: this((Generator)null)
{
}
public UITimer (Generator generator) : this (generator, typeof(IUITimer))
{
}
protected UITimer (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
}
/// <summary>
/// Gets or sets the interval, in seconds
/// </summary>
public double Interval {
get { return Handler.Interval; }
set { Handler.Interval = value; }
}
public void Start ()
{
Handler.Start ();
}
public void Stop ()
{
Handler.Stop ();
}
}
}
| bsd-3-clause | C# |
8801dfa8fb3b93d38072be9cef1fa642afadc73b | Fix build error with unused variable | AlexStefan/template-app | ExpandableList/ExpandableList.Android/Views/DetailsView.cs | ExpandableList/ExpandableList.Android/Views/DetailsView.cs | using Android.App;
using Android.OS;
using MvvmCross.Droid.Support.V7.AppCompat;
using System;
namespace ExpandableList.Droid.Views
{
[Activity(Label = "DetailsView")]
public class DetailsView : MvxAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
}
} | using Android.App;
using Android.OS;
using MvvmCross.Droid.Support.V7.AppCompat;
using System;
namespace ExpandableList.Droid.Views
{
[Activity(Label = "DetailsView")]
public class DetailsView : MvxAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
base.OnCreate(savedInstanceState);
}
catch (Exception ex)
{
}
}
}
} | mit | C# |
a270f56be5f2f4707454a501bb99b8e8ca3d7ecb | Fix performance regression due to sample being prematurely added | ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework | osu.Framework/Audio/Sample/SampleStore.cs | osu.Framework/Audio/Sample/SampleStore.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Concurrent;
using System.IO;
using osu.Framework.IO.Stores;
using osu.Framework.Statistics;
using System.Linq;
using System.Threading.Tasks;
namespace osu.Framework.Audio.Sample
{
public class SampleStore : AudioCollectionManager<SampleChannel>, IAdjustableResourceStore<SampleChannel>
{
private readonly IResourceStore<byte[]> store;
private readonly ConcurrentDictionary<string, Sample> sampleCache = new ConcurrentDictionary<string, Sample>();
/// <summary>
/// How many instances of a single sample should be allowed to playback concurrently before stopping the longest playing.
/// </summary>
public int PlaybackConcurrency { get; set; } = Sample.DEFAULT_CONCURRENCY;
internal SampleStore(IResourceStore<byte[]> store)
{
this.store = store;
}
public SampleChannel Get(string name)
{
if (string.IsNullOrEmpty(name)) return null;
lock (sampleCache)
{
SampleChannel channel = null;
if (!sampleCache.TryGetValue(name, out Sample sample))
{
byte[] data = store.Get(name);
sample = sampleCache[name] = data == null ? null : new SampleBass(data, PendingActions, PlaybackConcurrency);
}
if (sample != null)
{
channel = new SampleChannelBass(sample, AddItem);
}
return channel;
}
}
public Task<SampleChannel> GetAsync(string name) => Task.Run(() => Get(name));
public override void UpdateDevice(int deviceIndex)
{
foreach (var sample in sampleCache.Values.OfType<IBassAudio>())
sample.UpdateDevice(deviceIndex);
base.UpdateDevice(deviceIndex);
}
protected override void UpdateState()
{
FrameStatistics.Add(StatisticsCounterType.Samples, sampleCache.Count);
base.UpdateState();
}
public Stream GetStream(string name) => store.GetStream(name);
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Concurrent;
using System.IO;
using osu.Framework.IO.Stores;
using osu.Framework.Statistics;
using System.Linq;
using System.Threading.Tasks;
namespace osu.Framework.Audio.Sample
{
public class SampleStore : AudioCollectionManager<SampleChannel>, IAdjustableResourceStore<SampleChannel>
{
private readonly IResourceStore<byte[]> store;
private readonly ConcurrentDictionary<string, Sample> sampleCache = new ConcurrentDictionary<string, Sample>();
/// <summary>
/// How many instances of a single sample should be allowed to playback concurrently before stopping the longest playing.
/// </summary>
public int PlaybackConcurrency { get; set; } = Sample.DEFAULT_CONCURRENCY;
internal SampleStore(IResourceStore<byte[]> store)
{
this.store = store;
}
public SampleChannel Get(string name)
{
if (string.IsNullOrEmpty(name)) return null;
lock (sampleCache)
{
SampleChannel channel = null;
if (!sampleCache.TryGetValue(name, out Sample sample))
{
byte[] data = store.Get(name);
sample = sampleCache[name] = data == null ? null : new SampleBass(data, PendingActions, PlaybackConcurrency);
}
if (sample != null)
{
AddItem(channel = new SampleChannelBass(sample, AddItem));
}
return channel;
}
}
public Task<SampleChannel> GetAsync(string name) => Task.Run(() => Get(name));
public override void UpdateDevice(int deviceIndex)
{
foreach (var sample in sampleCache.Values.OfType<IBassAudio>())
sample.UpdateDevice(deviceIndex);
base.UpdateDevice(deviceIndex);
}
protected override void UpdateState()
{
FrameStatistics.Add(StatisticsCounterType.Samples, sampleCache.Count);
base.UpdateState();
}
public Stream GetStream(string name) => store.GetStream(name);
}
}
| mit | C# |
d47516b487865257487a2667abd36b80b5e115e2 | Update question grading icons | zaynetro/PicMatcher | PicMatcher/Models/Question.cs | PicMatcher/Models/Question.cs | using System;
using System.Collections.ObjectModel;
namespace PicMatcher
{
public class Question
{
public event EventHandler Correct;
public event EventHandler Mistake;
protected virtual void OnCorrect(EventArgs e) {
if (Correct != null)
Correct (this, e);
}
protected virtual void OnMistake(EventArgs e) {
if (Mistake != null)
Mistake (this, e);
}
public static string FormUri (int cat, string lang) {
return String.Format ("question?cat={0}&lang={1}", cat, lang);
}
/**
* Urls to correct and wrong icons
*/
public static string CorrectImg = "https://cdn2.iconfinder.com/data/icons/free-basic-icon-set-2/300/11-256.png";
public static string WrongImg = "https://cdn2.iconfinder.com/data/icons/free-basic-icon-set-2/300/17-256.png";
public Question () {}
public bool IsCorrectAnswer (string answer) {
var isCorrect = answer.ToUpper() == Answer.Name.ToUpper();
if (isCorrect)
OnCorrect (EventArgs.Empty);
else
OnMistake (EventArgs.Empty);
return isCorrect;
}
public int Question_id { set; get; }
public string Name { set; get; }
public string Picture { set; get; }
public Answer Answer { set; get; }
public string Category { set; get; }
public ObservableCollection<Answer> Answers { set; get; }
}
}
| using System;
using System.Collections.ObjectModel;
namespace PicMatcher
{
public class Question
{
public event EventHandler Correct;
public event EventHandler Mistake;
protected virtual void OnCorrect(EventArgs e) {
if (Correct != null)
Correct (this, e);
}
protected virtual void OnMistake(EventArgs e) {
if (Mistake != null)
Mistake (this, e);
}
public static string FormUri (int cat, string lang) {
return String.Format ("question?cat={0}&lang={1}", cat, lang);
}
/**
* Urls to correct and wrong icons
* TODO: use a better way to grade the question
*/
public static string CorrectImg = "https://cdn3.iconfinder.com/data/icons/shadcon/512/circle-tick-256.png";
public static string WrongImg = "https://cdn1.iconfinder.com/data/icons/toolbar-signs/512/no-256.png";
public Question () {}
public bool IsCorrectAnswer (string answer) {
var isCorrect = answer.ToUpper() == Answer.Name.ToUpper();
if (isCorrect)
OnCorrect (EventArgs.Empty);
else
OnMistake (EventArgs.Empty);
return isCorrect;
}
public int Question_id { set; get; }
public string Name { set; get; }
public string Picture { set; get; }
public Answer Answer { set; get; }
public string Category { set; get; }
public ObservableCollection<Answer> Answers { set; get; }
}
}
| mit | C# |
1022d265a467e72ee1ba09bfdeeef3d0eb0c8782 | Remove unused overload of Convention.Lifecycle. | fixie/fixie | src/Fixie/Convention.cs | src/Fixie/Convention.cs | namespace Fixie
{
using System;
using Conventions;
/// <summary>
/// Base class for all Fixie conventions. Subclass Convention to customize test discovery and execution.
/// </summary>
public class Convention
{
public Convention()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
Parameters = new ParameterSourceExpression(Config);
}
/// <summary>
/// The current state describing the convention. This state can be manipulated through
/// the other properties on Convention.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
/// <summary>
/// Defines the set of parameter sources, which provide inputs to parameterized test methods.
/// </summary>
public ParameterSourceExpression Parameters { get; }
/// <summary>
/// Overrides the default test class lifecycle.
/// </summary>
public void Lifecycle(Lifecycle lifecycle)
=> Config.Lifecycle = lifecycle;
}
} | namespace Fixie
{
using System;
using Conventions;
/// <summary>
/// Base class for all Fixie conventions. Subclass Convention to customize test discovery and execution.
/// </summary>
public class Convention
{
public Convention()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
Parameters = new ParameterSourceExpression(Config);
}
/// <summary>
/// The current state describing the convention. This state can be manipulated through
/// the other properties on Convention.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
/// <summary>
/// Defines the set of parameter sources, which provide inputs to parameterized test methods.
/// </summary>
public ParameterSourceExpression Parameters { get; }
/// <summary>
/// Overrides the default test class lifecycle.
/// </summary>
[Obsolete]
public void Lifecycle<TLifecycle>() where TLifecycle : Lifecycle, new()
=> Config.Lifecycle = new TLifecycle();
/// <summary>
/// Overrides the default test class lifecycle.
/// </summary>
[Obsolete]
public void Lifecycle(Lifecycle lifecycle)
=> Config.Lifecycle = lifecycle;
}
} | mit | C# |
21b14ddef8626263dc46d16a455dc5e565b91c32 | Update 20170714.cs | twilightspike/cuddly-disco,twilightspike/cuddly-disco | main/20170714.cs | main/20170714.cs | public struct AABB(Vector2 center, Vector2 halfSize){
public Vector2 center;
public Vector2 halfSize;
}
| public struct AABB{
}
| mit | C# |
118f233b57e040bc290bcf612b55400acef1561b | Fix new test on CI host | peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework | osu.Framework.Tests/Audio/AudioComponentTest.cs | osu.Framework.Tests/Audio/AudioComponentTest.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Audio;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioComponentTest
{
[Test]
public void TestVirtualTrack()
{
Architecture.SetIncludePath();
var thread = new AudioThread();
var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.dll"), @"Resources");
var manager = new AudioManager(thread, store, store);
thread.Start();
var track = manager.Tracks.GetVirtual();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(0, track.CurrentTime);
track.Start();
Task.Delay(50);
Assert.Greater(track.CurrentTime, 0);
track.Stop();
Assert.IsFalse(track.IsRunning);
thread.Exit();
Task.Delay(500);
Assert.IsFalse(thread.Exited);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Audio;
using osu.Framework.IO.Stores;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioComponentTest
{
[Test]
public void TestVirtualTrack()
{
var thread = new AudioThread();
var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.dll"), @"Resources");
var manager = new AudioManager(thread, store, store);
thread.Start();
var track = manager.Tracks.GetVirtual();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(0, track.CurrentTime);
track.Start();
Task.Delay(50);
Assert.Greater(track.CurrentTime, 0);
track.Stop();
Assert.IsFalse(track.IsRunning);
thread.Exit();
Task.Delay(500);
Assert.IsFalse(thread.Exited);
}
}
}
| mit | C# |
e08c8827ed6914ed0257c5af5f77eab443310fe3 | Make FrameworkTestCase abstract | Tom94/osu-framework,DrabWeb/osu-framework,default0/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,default0/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,peppy/osu-framework | osu.Framework.Tests/Visual/FrameworkTestCase.cs | osu.Framework.Tests/Visual/FrameworkTestCase.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual
{
public abstract class FrameworkTestCase : TestCase
{
public override void RunTest()
{
using (var host = new HeadlessGameHost())
host.Run(new FrameworkTestCaseTestRunner(this));
}
private class FrameworkTestCaseTestRunner : TestCaseTestRunner
{
public FrameworkTestCaseTestRunner(TestCase testCase)
: base(testCase)
{
}
[BackgroundDependencyLoader]
private void load()
{
Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.exe"), "Resources"));
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual
{
public class FrameworkTestCase : TestCase
{
public override void RunTest()
{
using (var host = new HeadlessGameHost())
host.Run(new FrameworkTestCaseTestRunner(this));
}
private class FrameworkTestCaseTestRunner : TestCaseTestRunner
{
public FrameworkTestCaseTestRunner(TestCase testCase)
: base(testCase)
{
}
[BackgroundDependencyLoader]
private void load()
{
Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.exe"), "Resources"));
}
}
}
}
| mit | C# |
742b9d9f4469a7aa97be61fa74534459be2c8e19 | Remove old bootstrapper stuff from UI-project. | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade.UI/Bootstrapper.cs | src/Arkivverket.Arkade.UI/Bootstrapper.cs | using System.Windows;
using Arkivverket.Arkade.UI.Views;
using Arkivverket.Arkade.Util;
using Autofac;
using Prism.Autofac;
using Prism.Modularity;
namespace Arkivverket.Arkade.UI
{
public class Bootstrapper : AutofacBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void ConfigureModuleCatalog()
{
var catalog = (ModuleCatalog) ModuleCatalog;
catalog.AddModule(typeof(ModuleAModule));
}
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
{
base.ConfigureContainerBuilder(builder);
builder.RegisterModule(new ArkadeAutofacModule());
}
}
} | using System.Windows;
using Arkivverket.Arkade.UI.Views;
using Arkivverket.Arkade.Util;
using Autofac;
using Prism.Autofac;
using Prism.Modularity;
namespace Arkivverket.Arkade.UI
{
public class Bootstrapper : AutofacBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void ConfigureModuleCatalog()
{
var catalog = (ModuleCatalog) ModuleCatalog;
catalog.AddModule(typeof(ModuleAModule));
}
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
{
base.ConfigureContainerBuilder(builder);
builder.RegisterModule(new ArkadeAutofacModule());
}
}
/* public class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterTypeForNavigation<View000Debug>("View000Debug");
Container.RegisterTypeForNavigation<View100Status>("View100Status");
ILogService logService = new RandomLogService();
Container.RegisterInstance(logService);
}
protected override void ConfigureModuleCatalog()
{
ModuleCatalog catalog = (ModuleCatalog)ModuleCatalog;
catalog.AddModule(typeof(ModuleAModule));
}
}
public static class UnityExtensons
{
public static void RegisterTypeForNavigation<T>(this IUnityContainer container, string name)
{
container.RegisterType(typeof(object), typeof(T), name);
}
}
*/
} | agpl-3.0 | C# |
6ae7ea13ab1ab14ba811e1ca1590c78aaf1dd2bf | remove missing grammar. | AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit | src/AvaloniaEdit.TextMate/GrammarNames.cs | src/AvaloniaEdit.TextMate/GrammarNames.cs | namespace AvaloniaEdit.TextMate
{
internal class GrammarNames
{
internal static string[] SupportedGrammars = new string[] {
"Bat",
"Clojure",
"CoffeeScript",
"Cpp",
"CSharp",
"CSS",
"Dart",
"Docker",
"FSharp",
"Git",
"Go",
"Groovy",
"HandleBars",
"HLSL",
"HTML",
"Ini",
"Jake",
"Java",
"Javascript",
"Json",
"Julia",
"Less",
"Lua",
"Make",
"MarkdownBasics",
"MarkdownMath",
"ObjectiveC",
"Perl",
"PHP",
"PowerShell",
"Pug",
"Python",
"R",
"Razor",
"Ruby",
"Rust",
"SCSS",
"ShaderLab",
"ShellScript",
"SQL",
"Swift",
"TypescriptBasics",
"VB",
"XML",
"YAML"
};
}
}
| namespace AvaloniaEdit.TextMate
{
internal class GrammarNames
{
internal static string[] SupportedGrammars = new string[] {
"Bat",
"Clojure",
"CoffeeScript",
"Cpp",
"CSharp",
"CSS",
"Dart",
"Docker",
"FSharp",
"Git",
"Go",
"Groovy",
"HandleBars",
"HLSL",
"HTML",
"Ini",
"Jake",
"Java",
"Javascript",
"Json",
"Julia",
"Less",
"Log",
"Lua",
"Make",
"MarkdownBasics",
"MarkdownMath",
"ObjectiveC",
"Perl",
"PHP",
"PowerShell",
"Pug",
"Python",
"R",
"Razor",
"Ruby",
"Rust",
"SCSS",
"ShaderLab",
"ShellScript",
"SQL",
"Swift",
"TypescriptBasics",
"VB",
"XML",
"YAML"
};
}
}
| mit | C# |
0ee85469dabb9b13fb3390f9d266383422254fdb | fix #39 | nerai/CMenu | src/ExampleMenu/Procedures/ProcManager.cs | src/ExampleMenu/Procedures/ProcManager.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ConsoleMenu;
namespace ExampleMenu.Procedures
{
public class ProcManager
{
private class Proc
{
public readonly List<string> Commands = new List<string> ();
public readonly Dictionary<string, int> JumpMarks = new Dictionary<string, int> ();
public Proc (IEnumerable<string> content)
{
Commands = new List<string> (content);
for (int i = 0; i < Commands.Count; i++) {
var s = Commands[i];
if (s.StartsWith (":")) {
s = s.Substring (1);
var name = MenuUtil.SplitFirstWord (ref s);
JumpMarks[name] = i;
Commands[i] = s;
}
}
}
}
private readonly Dictionary<string, Proc> _Procs = new Dictionary<string, Proc> ();
private bool _RequestReturn = false;
private string _RequestJump = null;
public void AddProc (string name, IEnumerable<string> content)
{
if (_Procs.ContainsKey (name)) {
Console.WriteLine ("Procedure \"" + name + "\" is already defined.");
return;
}
var proc = new Proc (content);
_Procs.Add (name, proc);
}
public IEnumerable<string> GenerateInput (string procname)
{
Proc proc;
if (!_Procs.TryGetValue (procname, out proc)) {
Console.WriteLine ("Unknown procedure: " + proc);
yield break;
}
int i = 0;
while (i < proc.Commands.Count) {
var line = proc.Commands[i];
yield return line;
i++;
if (_RequestReturn) {
_RequestReturn = false;
break;
}
if (_RequestJump != null) {
int to;
if (proc.JumpMarks.TryGetValue (_RequestJump, out to)) {
i = to;
}
else {
Console.WriteLine ("Could not find jump target \"" + _RequestJump+"\", aborting.");
yield break;
}
_RequestJump = null;
}
}
}
public void Return ()
{
_RequestReturn = true;
}
public void Jump (string mark)
{
_RequestJump = mark;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ConsoleMenu;
namespace ExampleMenu.Procedures
{
public class ProcManager
{
private class Proc
{
public readonly List<string> Commands = new List<string> ();
public readonly Dictionary<string, int> JumpMarks = new Dictionary<string, int> ();
public Proc (IEnumerable<string> content)
{
Commands = new List<string> (content);
for (int i = 0; i < Commands.Count; i++) {
var s = Commands[i];
if (s.StartsWith (":")) {
s = s.Substring (1);
var name = MenuUtil.SplitFirstWord (ref s);
JumpMarks[name] = i;
Commands[i] = s;
}
}
}
}
private readonly Dictionary<string, Proc> _Procs = new Dictionary<string, Proc> ();
private bool _RequestReturn = false;
private string _RequestJump = null;
public void AddProc (string name, IEnumerable<string> content)
{
if (_Procs.ContainsKey (name)) {
Console.WriteLine ("Procedure \"" + name + "\" is already defined.");
return;
}
var proc = new Proc (content);
_Procs.Add (name, proc);
}
public IEnumerable<string> GenerateInput (string procname)
{
Proc proc;
if (!_Procs.TryGetValue (procname, out proc)) {
Console.WriteLine ("Unknown procedure: " + proc);
yield break;
}
int i = 0;
while (i < proc.Commands.Count) {
var line = proc.Commands[i];
yield return line;
i++;
if (_RequestReturn) {
_RequestReturn = false;
break;
}
if (_RequestJump != null) {
i = proc.JumpMarks[_RequestJump]; // todo check
_RequestJump = null;
}
}
}
public void Return ()
{
_RequestReturn = true;
}
public void Jump (string mark)
{
_RequestJump = mark;
}
}
}
| mit | C# |
f8a3ffde43b453488a372f31b0e8862a7f894a9a | Update GlennStephens.cs | planetxamarin/planetxamarin,MabroukENG/planetxamarin,beraybentesen/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,stvansolano/planetxamarin,stvansolano/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,stvansolano/planetxamarin,planetxamarin/planetxamarin,beraybentesen/planetxamarin,beraybentesen/planetxamarin | src/Firehose.Web/Authors/GlennStephens.cs | src/Firehose.Web/Authors/GlennStephens.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class GlennStephens : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Glenn";
public string LastName => "Stephens";
public string StateOrRegion => "Sunshine Coast, Australia";
public string EmailAddress => "";
public string ShortBioOrTagLine => "is one of the Xamarin University instructors";
public Uri WebSite => new Uri("http://www.glennstephens.com.au/tag/xamarin/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://www.glennstephens.com.au/tag/xamarin/rss/"); }
}
public string TwitterHandle => "glenntstephens";
public string GravatarHash => "ffc4ec4a7133be87d2587325ac7b1d00";
public string GitHubHandle => string.Empty;
public GeoPosition Position => new GeoPosition(-26.6500000, 153.0666670);
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class GlennStephens : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Glenn";
public string LastName => "Stephens";
public string StateOrRegion => "Sunshine Coast, Australia";
public string EmailAddress => "";
public string ShortBioOrTagLine => "Senior Trainer at Xamarin University";
public Uri WebSite => new Uri("http://www.glennstephens.com.au/tag/xamarin/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://www.glennstephens.com.au/tag/xamarin/rss/"); }
}
public string TwitterHandle => "glenntstephens";
public string GravatarHash => "ffc4ec4a7133be87d2587325ac7b1d00";
public string GitHubHandle => string.Empty;
public GeoPosition Position => new GeoPosition(-26.6500000, 153.0666670);
}
} | mit | C# |
45a48a2d6f47ca212bb53b26e9e8829aea589859 | Change valid drive detection. | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | src/HelloCoreClrApp/Health/DiskMonitor.cs | src/HelloCoreClrApp/Health/DiskMonitor.cs | using System;
using System.IO;
using System.Linq;
using Humanizer.Bytes;
using Serilog;
namespace HelloCoreClrApp.Health
{
public class DiskMonitor : IMonitor
{
private static readonly ILogger Log = Serilog.Log.ForContext<DiskMonitor>();
public void LogUsage()
{
var summary = DriveInfo.GetDrives()
.Where(drive =>
(drive.DriveType == DriveType.Fixed || drive.VolumeLabel == "/")
&& drive.TotalSize > 0)
.Aggregate(string.Empty, (current, drive) =>
current + $"{ByteSize.FromBytes(drive.AvailableFreeSpace).Gigabytes:0.00G} of " +
$"{ByteSize.FromBytes(drive.TotalSize).Gigabytes:0.00G} free for " +
$"{drive.Name}{Environment.NewLine}");
Log.Information("Available disk space:{0}{1}", Environment.NewLine, summary.TrimEnd());
}
}
} | using System;
using System.IO;
using System.Linq;
using Humanizer.Bytes;
using Serilog;
namespace HelloCoreClrApp.Health
{
public class DiskMonitor : IMonitor
{
private static readonly ILogger Log = Serilog.Log.ForContext<DiskMonitor>();
public void LogUsage()
{
var summary = DriveInfo.GetDrives()
.Where(drive =>
(drive.DriveType == DriveType.Fixed || drive.DriveType == DriveType.Unknown)
&& drive.TotalSize > 0)
.Aggregate(string.Empty, (current, drive) =>
current + $"{ByteSize.FromBytes(drive.AvailableFreeSpace).Gigabytes:0.00G} of " +
$"{ByteSize.FromBytes(drive.TotalSize).Gigabytes:0.00G} free for " +
$"{drive.Name}{Environment.NewLine}");
Log.Information("Available disk space:{0}{1}", Environment.NewLine, summary.TrimEnd());
}
}
} | mit | C# |
6d7fa9d088fb365657a2d96d72f6a815b03a7e57 | allow RegEx to specify end of line | felipeleusin/Nancy,charleypeng/Nancy,charleypeng/Nancy,Novakov/Nancy,jonathanfoster/Nancy,tareq-s/Nancy,AIexandr/Nancy,khellang/Nancy,tsdl2013/Nancy,anton-gogolev/Nancy,anton-gogolev/Nancy,dbabox/Nancy,sadiqhirani/Nancy,phillip-haydon/Nancy,VQComms/Nancy,sloncho/Nancy,horsdal/Nancy,NancyFx/Nancy,sloncho/Nancy,dbolkensteyn/Nancy,AIexandr/Nancy,jeff-pang/Nancy,danbarua/Nancy,jongleur1983/Nancy,sroylance/Nancy,thecodejunkie/Nancy,danbarua/Nancy,jchannon/Nancy,tareq-s/Nancy,horsdal/Nancy,AcklenAvenue/Nancy,rudygt/Nancy,rudygt/Nancy,daniellor/Nancy,adamhathcock/Nancy,Novakov/Nancy,joebuschmann/Nancy,nicklv/Nancy,grumpydev/Nancy,fly19890211/Nancy,murador/Nancy,EliotJones/NancyTest,ccellar/Nancy,AlexPuiu/Nancy,AlexPuiu/Nancy,ccellar/Nancy,jchannon/Nancy,joebuschmann/Nancy,jeff-pang/Nancy,guodf/Nancy,EliotJones/NancyTest,wtilton/Nancy,tparnell8/Nancy,JoeStead/Nancy,cgourlay/Nancy,EliotJones/NancyTest,jchannon/Nancy,felipeleusin/Nancy,asbjornu/Nancy,EIrwin/Nancy,davidallyoung/Nancy,Worthaboutapig/Nancy,jmptrader/Nancy,Worthaboutapig/Nancy,lijunle/Nancy,sadiqhirani/Nancy,jmptrader/Nancy,damianh/Nancy,thecodejunkie/Nancy,davidallyoung/Nancy,duszekmestre/Nancy,malikdiarra/Nancy,nicklv/Nancy,NancyFx/Nancy,dbabox/Nancy,Novakov/Nancy,vladlopes/Nancy,dbolkensteyn/Nancy,blairconrad/Nancy,jongleur1983/Nancy,felipeleusin/Nancy,kekekeks/Nancy,AIexandr/Nancy,duszekmestre/Nancy,malikdiarra/Nancy,NancyFx/Nancy,daniellor/Nancy,blairconrad/Nancy,ayoung/Nancy,hitesh97/Nancy,davidallyoung/Nancy,hitesh97/Nancy,Worthaboutapig/Nancy,jonathanfoster/Nancy,phillip-haydon/Nancy,jeff-pang/Nancy,dbabox/Nancy,murador/Nancy,murador/Nancy,khellang/Nancy,daniellor/Nancy,Worthaboutapig/Nancy,SaveTrees/Nancy,JoeStead/Nancy,MetSystem/Nancy,MetSystem/Nancy,rudygt/Nancy,jonathanfoster/Nancy,guodf/Nancy,charleypeng/Nancy,hitesh97/Nancy,joebuschmann/Nancy,davidallyoung/Nancy,fly19890211/Nancy,jchannon/Nancy,sadiqhirani/Nancy,vladlopes/Nancy,EliotJones/NancyTest,AcklenAvenue/Nancy,jeff-pang/Nancy,anton-gogolev/Nancy,ayoung/Nancy,tareq-s/Nancy,thecodejunkie/Nancy,albertjan/Nancy,malikdiarra/Nancy,lijunle/Nancy,rudygt/Nancy,AlexPuiu/Nancy,JoeStead/Nancy,xt0rted/Nancy,guodf/Nancy,joebuschmann/Nancy,nicklv/Nancy,xt0rted/Nancy,xt0rted/Nancy,phillip-haydon/Nancy,thecodejunkie/Nancy,daniellor/Nancy,sroylance/Nancy,dbolkensteyn/Nancy,tsdl2013/Nancy,dbabox/Nancy,AIexandr/Nancy,MetSystem/Nancy,charleypeng/Nancy,murador/Nancy,tparnell8/Nancy,duszekmestre/Nancy,danbarua/Nancy,asbjornu/Nancy,albertjan/Nancy,jmptrader/Nancy,asbjornu/Nancy,lijunle/Nancy,hitesh97/Nancy,charleypeng/Nancy,nicklv/Nancy,EIrwin/Nancy,damianh/Nancy,anton-gogolev/Nancy,vladlopes/Nancy,VQComms/Nancy,vladlopes/Nancy,Crisfole/Nancy,NancyFx/Nancy,wtilton/Nancy,sroylance/Nancy,ayoung/Nancy,khellang/Nancy,tparnell8/Nancy,asbjornu/Nancy,cgourlay/Nancy,SaveTrees/Nancy,kekekeks/Nancy,SaveTrees/Nancy,cgourlay/Nancy,dbolkensteyn/Nancy,VQComms/Nancy,EIrwin/Nancy,adamhathcock/Nancy,jchannon/Nancy,lijunle/Nancy,cgourlay/Nancy,VQComms/Nancy,asbjornu/Nancy,wtilton/Nancy,AIexandr/Nancy,albertjan/Nancy,Novakov/Nancy,malikdiarra/Nancy,adamhathcock/Nancy,adamhathcock/Nancy,tareq-s/Nancy,jongleur1983/Nancy,tparnell8/Nancy,horsdal/Nancy,Crisfole/Nancy,kekekeks/Nancy,phillip-haydon/Nancy,wtilton/Nancy,guodf/Nancy,tsdl2013/Nancy,sloncho/Nancy,ccellar/Nancy,grumpydev/Nancy,ayoung/Nancy,jonathanfoster/Nancy,blairconrad/Nancy,danbarua/Nancy,AcklenAvenue/Nancy,blairconrad/Nancy,duszekmestre/Nancy,fly19890211/Nancy,fly19890211/Nancy,jongleur1983/Nancy,EIrwin/Nancy,grumpydev/Nancy,albertjan/Nancy,Crisfole/Nancy,tsdl2013/Nancy,felipeleusin/Nancy,davidallyoung/Nancy,JoeStead/Nancy,horsdal/Nancy,khellang/Nancy,SaveTrees/Nancy,damianh/Nancy,sadiqhirani/Nancy,grumpydev/Nancy,jmptrader/Nancy,VQComms/Nancy,AcklenAvenue/Nancy,AlexPuiu/Nancy,sroylance/Nancy,sloncho/Nancy,ccellar/Nancy,MetSystem/Nancy,xt0rted/Nancy | src/Nancy/Routing/Trie/TrieNodeFactory.cs | src/Nancy/Routing/Trie/TrieNodeFactory.cs | namespace Nancy.Routing.Trie
{
using Nancy.Routing.Trie.Nodes;
/// <summary>
/// Factory for creating the correct type of TrieNode
/// </summary>
public class TrieNodeFactory : ITrieNodeFactory
{
/// <summary>
/// Gets the correct Trie node type for the given segment
/// </summary>
/// <param name="parent">Parent node</param>
/// <param name="segment">Segment</param>
/// <returns>TrieNode instance</returns>
public TrieNode GetNodeForSegment(TrieNode parent, string segment)
{
if (parent == null)
{
return new RootNode(this);
}
if (segment.StartsWith("(") && segment.EndsWith(")"))
{
return new RegExNode(parent, segment, this);
}
if (segment.StartsWith("{") && segment.EndsWith("}"))
{
return this.GetCaptureNode(parent, segment);
}
if (segment.StartsWith("^(") && (segment.EndsWith(")") || segment.EndsWith(")$")))
{
return new GreedyRegExCaptureNode(parent, segment, this);
}
return new LiteralNode(parent, segment, this);
}
private TrieNode GetCaptureNode(TrieNode parent, string segment)
{
if (segment.EndsWith("?}"))
{
return new OptionalCaptureNode(parent, segment, this);
}
if (segment.EndsWith("*}"))
{
return new GreedyCaptureNode(parent, segment, this);
}
if (segment.Contains("?"))
{
return new CaptureNodeWithDefaultValue(parent, segment, this);
}
return new CaptureNode(parent, segment, this);
}
}
} | namespace Nancy.Routing.Trie
{
using Nancy.Routing.Trie.Nodes;
/// <summary>
/// Factory for creating the correct type of TrieNode
/// </summary>
public class TrieNodeFactory : ITrieNodeFactory
{
/// <summary>
/// Gets the correct Trie node type for the given segment
/// </summary>
/// <param name="parent">Parent node</param>
/// <param name="segment">Segment</param>
/// <returns>TrieNode instance</returns>
public TrieNode GetNodeForSegment(TrieNode parent, string segment)
{
if (parent == null)
{
return new RootNode(this);
}
if (segment.StartsWith("(") && segment.EndsWith(")"))
{
return new RegExNode(parent, segment, this);
}
if (segment.StartsWith("{") && segment.EndsWith("}"))
{
return this.GetCaptureNode(parent, segment);
}
if (segment.StartsWith("^(") && segment.EndsWith(")"))
{
return new GreedyRegExCaptureNode(parent, segment, this);
}
return new LiteralNode(parent, segment, this);
}
private TrieNode GetCaptureNode(TrieNode parent, string segment)
{
if (segment.EndsWith("?}"))
{
return new OptionalCaptureNode(parent, segment, this);
}
if (segment.EndsWith("*}"))
{
return new GreedyCaptureNode(parent, segment, this);
}
if (segment.Contains("?"))
{
return new CaptureNodeWithDefaultValue(parent, segment, this);
}
return new CaptureNode(parent, segment, this);
}
}
} | mit | C# |
dc67cac6ec6253d0bc6e1524f7665982d8194058 | Set tool name of Csc to csc (#23) | jeffkl/RoslynCodeTaskFactory | src/RoslynCodeTaskFactory/Internal/Csc.cs | src/RoslynCodeTaskFactory/Internal/Csc.cs | using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
namespace RoslynCodeTaskFactory.Internal
{
internal sealed class Csc : ManagedCompiler
{
public bool? NoStandardLib { get; set; }
protected override string ToolName => "csc.exe";
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendPlusOrMinusSwitch("/nostdlib", NoStandardLib);
if (References != null)
{
foreach (ITaskItem reference in References)
{
commandLine.AppendSwitchIfNotNull("/reference:", reference.ItemSpec);
}
}
base.AddResponseFileCommands(commandLine);
}
}
} | using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
namespace RoslynCodeTaskFactory.Internal
{
internal sealed class Csc : ManagedCompiler
{
public bool? NoStandardLib { get; set; }
protected override string ToolName => "Csc.exe";
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendPlusOrMinusSwitch("/nostdlib", NoStandardLib);
if (References != null)
{
foreach (ITaskItem reference in References)
{
commandLine.AppendSwitchIfNotNull("/reference:", reference.ItemSpec);
}
}
base.AddResponseFileCommands(commandLine);
}
}
} | mit | C# |
71da075e02a3a86123241f5508bff439fdc76335 | Remove unused method on timeline db | bwatts/Totem,bwatts/Totem | src/Totem.Runtime/Timeline/ITimelineDb.cs | src/Totem.Runtime/Timeline/ITimelineDb.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Describes the database persisting the timeline
/// </summary>
public interface ITimelineDb
{
Many<TimelinePoint> Append(TimelinePosition cause, Many<Event> events);
TimelinePoint AppendOccurred(TimelinePoint scheduledPoint);
TimelineResumeInfo ReadResumeInfo();
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Describes the database persisting the timeline
/// </summary>
public interface ITimelineDb
{
Many<TimelinePoint> Append(TimelinePosition cause, Many<Event> events);
TimelinePoint AppendOccurred(TimelinePoint scheduledPoint);
void RemoveFromSchedule(TimelinePosition position);
TimelineResumeInfo ReadResumeInfo();
}
} | mit | C# |
02cdd0b2deff3a03ee3a020d6e5a46684b5daa17 | use drawable link compiler in markdown link | UselessToucan/osu,UselessToucan/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu | osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.cs | osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using Markdig.Syntax.Inlines;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Online.Chat;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownLinkText : MarkdownLinkText
{
[Resolved(canBeNull: true)]
private OsuGame game { get; set; }
protected string Text;
protected string Title;
public OsuMarkdownLinkText(string text, LinkInline linkInline)
: base(text, linkInline)
{
Text = text;
Title = linkInline.Title;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
var text = CreateSpriteText().With(t => t.Text = Text);
InternalChildren = new Drawable[]
{
text,
new OsuMarkdownLinkCompiler(new[] { text })
{
RelativeSizeAxes = Axes.Both,
Action = OnLinkPressed,
TooltipText = Title ?? Url,
}
};
}
protected override void OnLinkPressed() => game?.HandleLink(Url);
private class OsuMarkdownLinkCompiler : DrawableLinkCompiler
{
public OsuMarkdownLinkCompiler(IEnumerable<Drawable> parts)
: base(parts)
{
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
IdleColour = colourProvider.Light2;
HoverColour = colourProvider.Light1;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax.Inlines;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownLinkText : MarkdownLinkText
{
[Resolved]
private OverlayColourProvider colourProvider { get; set; }
private SpriteText spriteText;
public OsuMarkdownLinkText(string text, LinkInline linkInline)
: base(text, linkInline)
{
}
[BackgroundDependencyLoader]
private void load()
{
spriteText.Colour = colourProvider.Light2;
}
public override SpriteText CreateSpriteText()
{
return spriteText = base.CreateSpriteText();
}
protected override bool OnHover(HoverEvent e)
{
spriteText.Colour = colourProvider.Light1;
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
spriteText.Colour = colourProvider.Light2;
base.OnHoverLost(e);
}
}
}
| mit | C# |
39ed5250d5b3bf748f781c97bf724467b72cde4a | Fix formatting | hydna/Hydna.NET | src/Hydna.Net/ChannelMode.cs | src/Hydna.Net/ChannelMode.cs | using System;
namespace Hydna.Net
{
/// <summary>
/// The mode that channel is, or should be opened in.
/// </summary>
[Flags]
public enum ChannelMode : byte
{
/// <summary>
/// Indicates that only signals are recivied on the Channel.
/// </summary>
Listen = 0x0,
/// <summary>
/// Indicates that signals and data is recieved on the Channel.
/// </summary>
Read = 0x1,
/// <summary>
/// Indicates that signals is recived and that data can be
/// sent to the Channel.
/// </summary>
Write = 0x2,
/// <summary>
/// Indicates that signals and data are recived and that data can be
/// sent to the Channel.
/// </summary>
ReadWrite = 0x3,
/// <summary>
/// Indicates that signals is recived and that signals can be
/// emitted to the Channel.
/// </summary>
Emit = 0x4,
/// <summary>
/// Indicates that signals and data are recived and that signals can be
/// emitted to the Channel.
/// </summary>
ReadEmit = 0x5,
/// <summary>
/// Indicates that signals is recived and that signals can be
/// emitted, and that data can be sent to the Channel.
/// </summary>
WriteEmit = 0x6,
/// <summary>
/// Indicates that signals and data are recived and that signals can be
/// emitted, and that data can be sent to the Channel.
/// </summary>
ReadWriteEmit = 0x7
}
} | using System;
namespace Hydna.Net
{
/// <summary>
/// The mode that channel is, or should be opened in.
/// </summary>
public enum ChannelMode : byte {
/// <summary>
/// Indicates that only signals are recivied on the Channel.
/// </summary>
Listen = 0x0,
/// <summary>
/// Indicates that signals and data is recieved on the Channel.
/// </summary>
Read = 0x1,
/// <summary>
/// Indicates that signals is recived and that data can be
/// sent to the Channel.
/// </summary>
Write = 0x2,
/// <summary>
/// Indicates that signals and data are recived and that data can be
/// sent to the Channel.
/// </summary>
ReadWrite = 0x3,
/// <summary>
/// Indicates that signals is recived and that signals can be
/// emitted to the Channel.
/// </summary>
Emit = 0x4,
/// <summary>
/// Indicates that signals and data are recived and that signals can be
/// emitted to the Channel.
/// </summary>
ReadEmit = 0x5,
/// <summary>
/// Indicates that signals is recived and that signals can be
/// emitted, and that data can be sent to the Channel.
/// </summary>
WriteEmit = 0x6,
/// <summary>
/// Indicates that signals and data are recived and that signals can be
/// emitted, and that data can be sent to the Channel.
/// </summary>
ReadWriteEmit = 0x7
}
}
| mit | C# |
8fea3dacee5ce9d3cb46789a8a672668cc9deed0 | Update session only is value is changed | AlexPuiu/Nancy,tareq-s/Nancy,horsdal/Nancy,jonathanfoster/Nancy,rudygt/Nancy,sloncho/Nancy,AlexPuiu/Nancy,rudygt/Nancy,NancyFx/Nancy,tsdl2013/Nancy,xt0rted/Nancy,joebuschmann/Nancy,horsdal/Nancy,phillip-haydon/Nancy,fly19890211/Nancy,sadiqhirani/Nancy,albertjan/Nancy,sroylance/Nancy,MetSystem/Nancy,cgourlay/Nancy,blairconrad/Nancy,hitesh97/Nancy,malikdiarra/Nancy,dbabox/Nancy,ayoung/Nancy,guodf/Nancy,VQComms/Nancy,EIrwin/Nancy,AIexandr/Nancy,sloncho/Nancy,kekekeks/Nancy,jeff-pang/Nancy,charleypeng/Nancy,anton-gogolev/Nancy,dbolkensteyn/Nancy,blairconrad/Nancy,nicklv/Nancy,Worthaboutapig/Nancy,AIexandr/Nancy,jmptrader/Nancy,duszekmestre/Nancy,jmptrader/Nancy,AlexPuiu/Nancy,wtilton/Nancy,wtilton/Nancy,danbarua/Nancy,xt0rted/Nancy,khellang/Nancy,cgourlay/Nancy,fly19890211/Nancy,VQComms/Nancy,kekekeks/Nancy,asbjornu/Nancy,tparnell8/Nancy,vladlopes/Nancy,SaveTrees/Nancy,davidallyoung/Nancy,VQComms/Nancy,horsdal/Nancy,guodf/Nancy,VQComms/Nancy,tsdl2013/Nancy,AIexandr/Nancy,SaveTrees/Nancy,davidallyoung/Nancy,felipeleusin/Nancy,AcklenAvenue/Nancy,guodf/Nancy,tparnell8/Nancy,SaveTrees/Nancy,kekekeks/Nancy,damianh/Nancy,MetSystem/Nancy,MetSystem/Nancy,khellang/Nancy,davidallyoung/Nancy,ayoung/Nancy,joebuschmann/Nancy,NancyFx/Nancy,grumpydev/Nancy,NancyFx/Nancy,murador/Nancy,SaveTrees/Nancy,jongleur1983/Nancy,sloncho/Nancy,Novakov/Nancy,tparnell8/Nancy,phillip-haydon/Nancy,charleypeng/Nancy,ayoung/Nancy,ccellar/Nancy,sadiqhirani/Nancy,AcklenAvenue/Nancy,murador/Nancy,jeff-pang/Nancy,jongleur1983/Nancy,jonathanfoster/Nancy,thecodejunkie/Nancy,jmptrader/Nancy,malikdiarra/Nancy,duszekmestre/Nancy,felipeleusin/Nancy,hitesh97/Nancy,danbarua/Nancy,VQComms/Nancy,joebuschmann/Nancy,jchannon/Nancy,grumpydev/Nancy,wtilton/Nancy,EIrwin/Nancy,AlexPuiu/Nancy,asbjornu/Nancy,daniellor/Nancy,nicklv/Nancy,tsdl2013/Nancy,AIexandr/Nancy,ccellar/Nancy,NancyFx/Nancy,jongleur1983/Nancy,adamhathcock/Nancy,felipeleusin/Nancy,murador/Nancy,JoeStead/Nancy,charleypeng/Nancy,davidallyoung/Nancy,tparnell8/Nancy,guodf/Nancy,jchannon/Nancy,vladlopes/Nancy,grumpydev/Nancy,danbarua/Nancy,charleypeng/Nancy,AcklenAvenue/Nancy,damianh/Nancy,sloncho/Nancy,anton-gogolev/Nancy,EIrwin/Nancy,felipeleusin/Nancy,dbolkensteyn/Nancy,davidallyoung/Nancy,nicklv/Nancy,danbarua/Nancy,jeff-pang/Nancy,tareq-s/Nancy,fly19890211/Nancy,phillip-haydon/Nancy,cgourlay/Nancy,wtilton/Nancy,hitesh97/Nancy,jchannon/Nancy,xt0rted/Nancy,grumpydev/Nancy,JoeStead/Nancy,Crisfole/Nancy,albertjan/Nancy,Novakov/Nancy,murador/Nancy,tareq-s/Nancy,duszekmestre/Nancy,sroylance/Nancy,blairconrad/Nancy,ccellar/Nancy,ccellar/Nancy,dbolkensteyn/Nancy,tareq-s/Nancy,jongleur1983/Nancy,rudygt/Nancy,thecodejunkie/Nancy,MetSystem/Nancy,cgourlay/Nancy,Worthaboutapig/Nancy,jchannon/Nancy,dbabox/Nancy,sroylance/Nancy,JoeStead/Nancy,Crisfole/Nancy,sadiqhirani/Nancy,malikdiarra/Nancy,lijunle/Nancy,vladlopes/Nancy,joebuschmann/Nancy,EliotJones/NancyTest,Novakov/Nancy,anton-gogolev/Nancy,thecodejunkie/Nancy,dbolkensteyn/Nancy,Worthaboutapig/Nancy,EliotJones/NancyTest,dbabox/Nancy,adamhathcock/Nancy,Worthaboutapig/Nancy,daniellor/Nancy,jonathanfoster/Nancy,AIexandr/Nancy,malikdiarra/Nancy,jonathanfoster/Nancy,jmptrader/Nancy,daniellor/Nancy,albertjan/Nancy,AcklenAvenue/Nancy,albertjan/Nancy,jeff-pang/Nancy,xt0rted/Nancy,asbjornu/Nancy,khellang/Nancy,hitesh97/Nancy,lijunle/Nancy,khellang/Nancy,horsdal/Nancy,charleypeng/Nancy,duszekmestre/Nancy,sadiqhirani/Nancy,JoeStead/Nancy,rudygt/Nancy,asbjornu/Nancy,vladlopes/Nancy,ayoung/Nancy,lijunle/Nancy,phillip-haydon/Nancy,asbjornu/Nancy,lijunle/Nancy,daniellor/Nancy,tsdl2013/Nancy,EliotJones/NancyTest,dbabox/Nancy,jchannon/Nancy,damianh/Nancy,EIrwin/Nancy,sroylance/Nancy,fly19890211/Nancy,anton-gogolev/Nancy,blairconrad/Nancy,Crisfole/Nancy,thecodejunkie/Nancy,Novakov/Nancy,adamhathcock/Nancy,nicklv/Nancy,adamhathcock/Nancy,EliotJones/NancyTest | src/Nancy/Session/Session.cs | src/Nancy/Session/Session.cs | namespace Nancy.Session
{
using System.Collections;
using System.Collections.Generic;
public class Session : ISession
{
private readonly IDictionary<string, object> dictionary;
private bool hasChanged;
public Session() : this(new Dictionary<string, object>(0)){}
public Session(IDictionary<string, object> dictionary)
{
this.dictionary = dictionary;
}
public int Count
{
get { return dictionary.Count; }
}
public void DeleteAll()
{
if (Count > 0) { MarkAsChanged(); }
dictionary.Clear();
}
public void Delete(string key)
{
if (dictionary.Remove(key)) { MarkAsChanged(); }
}
public object this[string key]
{
get { return dictionary.ContainsKey(key) ? dictionary[key] : null; }
set
{
if (this[key] == value) return;
dictionary[key] = value;
MarkAsChanged();
}
}
public bool HasChanged
{
get { return this.hasChanged; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
private void MarkAsChanged()
{
hasChanged = true;
}
}
} | namespace Nancy.Session
{
using System.Collections;
using System.Collections.Generic;
public class Session : ISession
{
private readonly IDictionary<string, object> dictionary;
private bool hasChanged;
public Session() : this(new Dictionary<string, object>(0)){}
public Session(IDictionary<string, object> dictionary)
{
this.dictionary = dictionary;
}
public int Count
{
get { return dictionary.Count; }
}
public void DeleteAll()
{
if (Count > 0) { MarkAsChanged(); }
dictionary.Clear();
}
public void Delete(string key)
{
if (dictionary.Remove(key)) { MarkAsChanged(); }
}
public object this[string key]
{
get { return dictionary.ContainsKey(key) ? dictionary[key] : null; }
set
{
dictionary[key] = value;
MarkAsChanged();
}
}
public bool HasChanged
{
get { return this.hasChanged; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
private void MarkAsChanged()
{
hasChanged = true;
}
}
} | mit | C# |
5fe764b2db98b30113fdc9f2fc7690df8db97ed8 | Fix tournament videos stuttering when changing scenes | EVAST9919/osu,peppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,peppy/osu-new,johnneijzen/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu | osu.Game.Tournament/Components/TourneyVideo.cs | osu.Game.Tournament/Components/TourneyVideo.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Video;
using osu.Framework.Timing;
using osu.Game.Graphics;
namespace osu.Game.Tournament.Components
{
public class TourneyVideo : CompositeDrawable
{
private readonly VideoSprite video;
private ManualClock manualClock;
private IFrameBasedClock sourceClock;
public TourneyVideo(Stream stream)
{
if (stream == null)
{
InternalChild = new Box
{
Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)),
RelativeSizeAxes = Axes.Both,
};
}
else
InternalChild = video = new VideoSprite(stream)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
};
}
public bool Loop
{
set
{
if (video != null)
video.Loop = value;
}
}
protected override void LoadComplete()
{
base.LoadComplete();
sourceClock = Clock;
Clock = new FramedClock(manualClock = new ManualClock());
}
protected override void Update()
{
base.Update();
// we want to avoid seeking as much as possible, because we care about performance, not sync.
// to avoid seeking completely, we only increment out local clock when in an updating state.
manualClock.CurrentTime += sourceClock.ElapsedFrameTime;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Video;
using osu.Game.Graphics;
namespace osu.Game.Tournament.Components
{
public class TourneyVideo : CompositeDrawable
{
private readonly VideoSprite video;
public TourneyVideo(Stream stream)
{
if (stream == null)
{
InternalChild = new Box
{
Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)),
RelativeSizeAxes = Axes.Both,
};
}
else
InternalChild = video = new VideoSprite(stream)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
};
}
public bool Loop
{
set
{
if (video != null)
video.Loop = value;
}
}
}
}
| mit | C# |
f08a4f1ef9f58b5af1bead43ffb0bf3728e1876e | Update AssemblyInfo.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | src/Core2D.Avalonia.Direct2D/Properties/AssemblyInfo.cs | src/Core2D.Avalonia.Direct2D/Properties/AssemblyInfo.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Core2D.Avalonia.Direct2D")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Core2D.Avalonia.Direct2D")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("4868069e-3ad4-497e-9b8e-148d1eeacfd7")]
| mit | C# |
9c3f3a272c26195e199715a779014d89a7f66adb | clean code | dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP | src/DotNetCore.CAP.SqlServer/ICapPublisher.SqlServer.cs | src/DotNetCore.CAP.SqlServer/ICapPublisher.SqlServer.cs | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Models;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
namespace DotNetCore.CAP.SqlServer
{
public class SqlServerPublisher : CapPublisherBase, ICallbackPublisher
{
private readonly SqlServerOptions _options;
public SqlServerPublisher(IServiceProvider provider) : base(provider)
{
_options = ServiceProvider.GetService<SqlServerOptions>();
}
public async Task PublishCallbackAsync(CapPublishedMessage message)
{
await PublishAsyncInternal(message);
}
protected override async Task ExecuteAsync(CapPublishedMessage message, ICapTransaction transaction,
CancellationToken cancel = default(CancellationToken))
{
if (NotUseTransaction)
{
using (var connection = new SqlConnection(_options.ConnectionString))
{
await connection.ExecuteAsync(PrepareSql(), message);
return;
}
}
var dbTrans = transaction.DbTransaction as IDbTransaction;
if (dbTrans == null && transaction.DbTransaction is IDbContextTransaction dbContextTrans)
{
dbTrans = dbContextTrans.GetDbTransaction();
}
var conn = dbTrans?.Connection;
await conn.ExecuteAsync(PrepareSql(), message, dbTrans);
}
#region private methods
private string PrepareSql()
{
return
$"INSERT INTO {_options.Schema}.[Published] ([Id],[Name],[Content],[Retries],[Added],[ExpiresAt],[StatusName])VALUES(@Id,@Name,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";
}
#endregion private methods
}
} | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using DotNetCore.CAP.Abstractions;
using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Models;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
namespace DotNetCore.CAP.SqlServer
{
public class SqlServerPublisher : CapPublisherBase, ICallbackPublisher
{
private readonly SqlServerOptions _options;
public SqlServerPublisher(IServiceProvider provider) : base(provider)
{
_options = ServiceProvider.GetService<SqlServerOptions>();
}
public async Task PublishCallbackAsync(CapPublishedMessage message)
{
await PublishAsyncInternal(message);
}
protected override async Task ExecuteAsync(CapPublishedMessage message, ICapTransaction transaction,
CancellationToken cancel = default(CancellationToken))
{
if (NotUseTransaction)
{
using (var connection = new SqlConnection(_options.ConnectionString))
{
await connection.ExecuteAsync(PrepareSql(), message);
return;
}
}
var dbTrans = transaction.DbTransaction as IDbTransaction;
if (dbTrans == null && transaction.DbTransaction is IDbContextTransaction dbContextTrans)
{
dbTrans = dbContextTrans.GetDbTransaction();
}
var conn = dbTrans?.Connection;
await conn.ExecuteAsync(PrepareSql(), message, dbTrans);
}
#region private methods
private string PrepareSql()
{
return
$"INSERT INTO {_options.Schema}.[Published] ([Id],[Name],[Content],[Retries],[Added],[ExpiresAt],[StatusName])VALUES(@Id,@Name,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";
}
//private IDbConnection InitDbConnection()
//{
// var conn = ;
// conn.OpenAsync();
// return conn;
//}
#endregion private methods
}
} | mit | C# |
ef48dc9153a0b8be73e16481450b8107a2f6a077 | Remove unneeded 'syntatic noise' | takenet/messaginghub-client-csharp | src/Takenet.MessagingHub.Client/MessageSenderWrapper.cs | src/Takenet.MessagingHub.Client/MessageSenderWrapper.cs | using Lime.Protocol;
using Lime.Protocol.Client;
using System.Threading.Tasks;
namespace Takenet.MessagingHub.Client
{
class MessageSenderWrapper : IMessageSender
{
IClientChannel clientChannel;
public MessageSenderWrapper(IClientChannel clientChannel)
{
this.clientChannel = clientChannel;
}
public Task SendMessageAsync(Message message) => clientChannel.SendMessageAsync(message);
}
}
| using Lime.Messaging.Contents;
using Lime.Protocol;
using Lime.Protocol.Client;
using System.Threading.Tasks;
namespace Takenet.MessagingHub.Client
{
internal class MessageSenderWrapper : IMessageSender
{
IClientChannel clientChannel;
public MessageSenderWrapper(IClientChannel clientChannel)
{
this.clientChannel = clientChannel;
}
public Task SendMessageAsync(Message message)
{
return clientChannel.SendMessageAsync(message);
}
}
}
| apache-2.0 | C# |
3637ebf4c2110517e46f5bb989e2bd20092cec52 | Update version | dongruiqing/WindowsProtocolTestSuites,dongruiqing/WindowsProtocolTestSuites,JessieF/WindowsProtocolTestSuites,JessieF/WindowsProtocolTestSuites | AssemblyInfo/SharedAssemblyInfo.cs | AssemblyInfo/SharedAssemblyInfo.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyVersion("1.0.5000.0")]
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyVersion("1.0.0.0")] | mit | C# |
4cc1771b574980b77b29d7f0a263488131f284c7 | Fix typo in public variable | Saduras/DungeonGenerator | Assets/SourceCode/RoomGenerator.cs | Assets/SourceCode/RoomGenerator.cs | using UnityEngine;
public class RoomGenerator : MonoBehaviour
{
public GameObject roomPrefab;
public int roomCount = 100;
public int spaceWidth = 500;
public int spaceLength = 500;
public int minRoomWidth = 5;
public int maxRoomWidth = 20;
public int minRoomLength = 5;
public int maxRoomLength = 20;
public Room[] generatedRooms;
public void Run()
{
for (int i = 0; i < generatedRooms.Length; i++)
{
DestroyImmediate(generatedRooms[i].gameObject);
}
generatedRooms = new Room[roomCount];
for (int i = 0; i < roomCount; i++)
{
var posX = Random.Range (0, spaceWidth);
var posZ = Random.Range (0, spaceLength);
var sizeX = Random.Range (minRoomWidth, maxRoomWidth);
var sizeZ = Random.Range (minRoomLength, maxRoomLength);
var instance = Instantiate (roomPrefab);
instance.transform.SetParent (this.transform);
instance.transform.localPosition = new Vector3 (posX, 0f, posZ);
instance.transform.localScale = Vector3.one;
var room = instance.GetComponent<Room> ();
room.Init (sizeX, sizeZ);
generatedRooms [i] = room;
}
}
}
| using UnityEngine;
public class RoomGenerator : MonoBehaviour
{
public GameObject roomPrefab;
public int roomCount = 100;
public int spaceWidth = 500;
public int spaceLength = 500;
public int minRoomWidth = 5;
public int maxRoomWidth = 20;
public int minRoomLength = 5;
public int maxRoomLength = 20;
public Room[] generatedrRooms;
public void Run()
{
for (int i = 0; i < this.transform.childCount; i++)
{
DestroyImmediate(this.transform.GetChild(i).gameObject);
}
generatedrRooms = new Room[roomCount];
for (int i = 0; i < roomCount; i++)
{
var posX = Random.Range (0, spaceWidth);
var posZ = Random.Range (0, spaceLength);
var sizeX = Random.Range (minRoomWidth, maxRoomWidth);
var sizeZ = Random.Range (minRoomLength, maxRoomLength);
var instance = Instantiate (roomPrefab);
instance.transform.SetParent (this.transform);
instance.transform.localPosition = new Vector3 (posX, 0f, posZ);
instance.transform.localScale = Vector3.one;
var room = instance.GetComponent<Room> ();
room.Init (sizeX, sizeZ);
generatedrRooms [i] = room;
}
}
}
| mit | C# |
f659a9e3746b8cda6b93b6e789e35ffaf0f81ab2 | Bump assembly versions | maxmind/minfraud-api-dotnet | MaxMind.MinFraud/Properties/AssemblyInfo.cs | MaxMind.MinFraud/Properties/AssemblyInfo.cs | using System;
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("MaxMind.MinFraud")]
[assembly: AssemblyDescription("API for MaxMind minFraud Score and Insights web services")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MaxMind, Inc.")]
[assembly: AssemblyProduct("MaxMind.MinFraud")]
[assembly: AssemblyCopyright("Copyright © 2015-2018")]
[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("7208d9c8-f862-4675-80e5-77a2f8901b96")]
[assembly: CLSCompliant(true)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")] | using System;
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("MaxMind.MinFraud")]
[assembly: AssemblyDescription("API for MaxMind minFraud Score and Insights web services")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MaxMind, Inc.")]
[assembly: AssemblyProduct("MaxMind.MinFraud")]
[assembly: AssemblyCopyright("Copyright © 2015-2018")]
[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("7208d9c8-f862-4675-80e5-77a2f8901b96")]
[assembly: CLSCompliant(true)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.6.0.0")]
[assembly: AssemblyFileVersion("0.6.0")]
[assembly: AssemblyInformationalVersion("0.6.0")] | apache-2.0 | C# |
4ccd18f9136d6a53177b3c7d0d42f32689e23ab7 | Revert ordering. Actually transient should be at the end since they are not present in the stream. | modulexcite/Migrant,rogeralsing/Migrant,rogeralsing/Migrant,antmicro/Migrant,modulexcite/Migrant,antmicro/Migrant | Migrant/VersionTolerance/TypeStampReader.cs | Migrant/VersionTolerance/TypeStampReader.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace AntMicro.Migrant.VersionTolerance
{
internal sealed class TypeStampReader
{
public TypeStampReader(PrimitiveReader reader)
{
this.reader = reader;
stampCache = new Dictionary<Type, List<FieldInfoOrEntryToOmit>>();
}
public void ReadStamp(Type type)
{
if(!StampHelpers.IsStampNeeded(type))
{
return;
}
if(stampCache.ContainsKey(type))
{
return;
}
var result = new List<FieldInfoOrEntryToOmit>();
var currentFields = StampHelpers.GetFieldsInSerializationOrder(type, true).ToDictionary(x => x.Name, x => x);
var fieldNo = reader.ReadInt32();
for(var i = 0; i < fieldNo; i++)
{
var fieldName = reader.ReadString();
var fieldType = Type.GetType(reader.ReadString());
FieldInfo currentField;
if(!currentFields.TryGetValue(fieldName, out currentField))
{
// field is missing in the newer version of the class
// we have to read the data to properly move stream,
// but that's all
result.Add(new FieldInfoOrEntryToOmit(fieldType));
continue;
}
// are the types compatible?
if(currentField.FieldType != fieldType)
{
// TODO: better exception message
throw new InvalidOperationException("Not compatible version.");
}
result.Add(new FieldInfoOrEntryToOmit(currentField));
}
// result should also contain transient fields, because some of them may
// be marked with the [Constructor] attribute
result.AddRange(currentFields.Select(x => x.Value).Where(x => !Helpers.IsNotTransient(x)).Select(x => new FieldInfoOrEntryToOmit(x)));
stampCache.Add(type, result);
}
public IEnumerable<FieldInfoOrEntryToOmit> GetFieldsToDeserialize(Type type)
{
return stampCache[type];
}
private readonly Dictionary<Type, List<FieldInfoOrEntryToOmit>> stampCache;
private readonly PrimitiveReader reader;
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace AntMicro.Migrant.VersionTolerance
{
internal sealed class TypeStampReader
{
public TypeStampReader(PrimitiveReader reader)
{
this.reader = reader;
stampCache = new Dictionary<Type, List<FieldInfoOrEntryToOmit>>();
}
public void ReadStamp(Type type)
{
if(!StampHelpers.IsStampNeeded(type))
{
return;
}
if(stampCache.ContainsKey(type))
{
return;
}
var result = new List<FieldInfoOrEntryToOmit>();
var currentFields = StampHelpers.GetFieldsInSerializationOrder(type, true).ToDictionary(x => x.Name, x => x);
var fieldNo = reader.ReadInt32();
for(var i = 0; i < fieldNo; i++)
{
var fieldName = reader.ReadString();
var fieldType = Type.GetType(reader.ReadString());
FieldInfo currentField;
if(!currentFields.TryGetValue(fieldName, out currentField))
{
// field is missing in the newer version of the class
// we have to read the data to properly move stream,
// but that's all
result.Add(new FieldInfoOrEntryToOmit(fieldType));
continue;
}
// are the types compatible?
if(currentField.FieldType != fieldType)
{
// TODO: better exception message
throw new InvalidOperationException("Not compatible version.");
}
result.Add(new FieldInfoOrEntryToOmit(currentField));
}
// result should also contain transient fields, because some of them may
// be marked with the [Constructor] attribute
result.AddRange(currentFields.Select(x => x.Value).Where(x => !Helpers.IsNotTransient(x)).Select(x => new FieldInfoOrEntryToOmit(x)));
stampCache.Add(type, result.OrderBy(x => x.Field == null ? x.TypeToOmit.Name : x.Field.FieldType.Name).ToList());
}
public IEnumerable<FieldInfoOrEntryToOmit> GetFieldsToDeserialize(Type type)
{
return stampCache[type];
}
private readonly Dictionary<Type, List<FieldInfoOrEntryToOmit>> stampCache;
private readonly PrimitiveReader reader;
}
}
| mit | C# |
149f79b1e5b1b2d54b93da01a18a712e3b879a4b | Update Comment.cs | mattnis/ZendeskApi_v2,CKCobra/ZendeskApi_v2,mwarger/ZendeskApi_v2,dcrowe/ZendeskApi_v2 | ZendeskApi_v2/Models/Tickets/Comment.cs | ZendeskApi_v2/Models/Tickets/Comment.cs | using System.Collections.Generic;
using Newtonsoft.Json;
using ZendeskApi_v2.Models.Shared;
namespace ZendeskApi_v2.Models.Tickets
{
public class Comment
{
[JsonProperty("id")]
public long? Id { get; set; }
[JsonProperty("public")]
public bool Public { get; set; }
[JsonProperty("body")]
public string Body { get; set; }
/// <summary>
/// Used for uploading attachments only
/// When creating and updating tickets you may attach files by passing in an array of the tokens received from uploading the files.
/// For the upload attachment to succeed when updating a ticket, a comment must be included.
/// Use Attachments.UploadAttachment to get the token first.
/// </summary>
[JsonProperty("uploads")]
public IList<string> Uploads { get; set; }
/// <summary>
/// Used only for getting ticket comments
/// </summary>
[JsonProperty("author_id")]
public long? AuthorId { get; private set; }
[JsonProperty("html_body")]
public string HtmlBody { get; private set; }
[JsonProperty("attachments")]
public IList<Attachment> Attachments { get; private set; }
[JsonProperty("via")]
public Via Via { get; private set; }
[JsonProperty("metadata")]
public MetaData MetaData { get; private set; }
[JsonProperty("created_at")]
public string CreatedAt { get; set; }
}
}
| using System.Collections.Generic;
using Newtonsoft.Json;
using ZendeskApi_v2.Models.Shared;
namespace ZendeskApi_v2.Models.Tickets
{
public class Comment
{
[JsonProperty("id")]
public long? Id { get; set; }
[JsonProperty("public")]
public bool Public { get; set; }
[JsonProperty("body")]
public string Body { get; set; }
/// <summary>
/// Used for uploading attachments only
/// When creating and updating tickets you may attach files by passing in an array of the tokens received from uploading the files.
/// For the upload attachment to succeed when updating a ticket, a comment must be included.
/// Use Attachments.UploadAttachment to get the token first.
/// </summary>
[JsonProperty("uploads")]
public IList<string> Uploads { get; set; }
/// <summary>
/// Used only for getting ticket comments
/// </summary>
[JsonProperty("author_id")]
public long? AuthorId { get; private set; }
[JsonProperty("html_body")]
public string HtmlBody { get; private set; }
[JsonProperty("attachments")]
public IList<Attachment> Attachments { get; private set; }
[JsonProperty("via")]
public Via Via { get; private set; }
[JsonProperty("metadata")]
public MetaData MetaData { get; private set; }
}
} | apache-2.0 | C# |
10388c3b39619d7ba4e330bc478d2317cc563414 | Remove the default route. | otac0n/GitReview,otac0n/GitReview,otac0n/GitReview | GitReview/App_Start/RouteConfig.cs | GitReview/App_Start/RouteConfig.cs | // -----------------------------------------------------------------------
// <copyright file="RouteConfig.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview
{
using System.Web.Mvc;
using System.Web.Routing;
/// <summary>
/// Contains route registrations.
/// </summary>
public static class RouteConfig
{
/// <summary>
/// Registers the application's routes against the specified <see cref="RouteCollection"/>.
/// </summary>
/// <param name="routes">The route collection to update.</param>
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Home", "", new { controller = "Home", action = "Index" });
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="RouteConfig.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview
{
using System.Web.Mvc;
using System.Web.Routing;
/// <summary>
/// Contains route registrations.
/// </summary>
public static class RouteConfig
{
/// <summary>
/// Registers the application's routes against the specified <see cref="RouteCollection"/>.
/// </summary>
/// <param name="routes">The route collection to update.</param>
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
}
}
| mit | C# |
ecf4bf27a0c3ba210cf6c915c782637e9bda714a | Fix minor bug. | Eusth/HoneySelectVR | HoneySelectVR/HoneyStandingMode.cs | HoneySelectVR/HoneyStandingMode.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VRGIN.Controls;
using VRGIN.Helpers;
using VRGIN.Modes;
using VRGIN.Core;
using System.Collections;
using UnityEngine;
namespace HoneySelectVR
{
class HoneyStandingMode : StandingMode
{
protected override IEnumerable<IShortcut> CreateShortcuts()
{
return base.CreateShortcuts().Concat(new IShortcut[] {
new MultiKeyboardShortcut(new KeyStroke("Ctrl + C"), new KeyStroke("Ctrl + C"), delegate { VR.Manager.SetMode<HoneySeatedMode>(); } )
});
}
protected override void OnLevel(int level)
{
base.OnLevel(level);
VRLog.Info("Level {0}", level);
if (GameObject.FindObjectOfType<ADVScene>())
{
StartCoroutine(PositionForADV());
}
if(level == 2)
{
// Title screen
StartCoroutine(PositionForTitle());
}
}
public override IEnumerable<Type> Tools
{
get
{
return base.Tools.Concat(new Type[] { typeof(PlayTool) });
}
}
private IEnumerator PositionForADV()
{
yield return new WaitForEndOfFrame();
if (Camera.main)
{
VR.Camera.Copy(Camera.main);
MoveToPosition(Camera.main.transform.position, Camera.main.transform.rotation);
}
//VR.Camera.SteamCam.origin.position = -VR.Camera.SteamCam.origin.forward + VR.Camera.SteamCam.origin.position.y * Vector3.up;
//VR.Camera.SteamCam.origin.position = new Vector3(0, 1.4f, 1f);
//VR.Camera.SteamCam.origin.rotation = Quaternion.LookRotation(-Vector3.forward);
}
private IEnumerator PositionForTitle()
{
yield return new WaitForEndOfFrame();
MoveToPosition(Vector3.forward *3, Quaternion.LookRotation(-Vector3.forward));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VRGIN.Controls;
using VRGIN.Helpers;
using VRGIN.Modes;
using VRGIN.Core;
using System.Collections;
using UnityEngine;
namespace HoneySelectVR
{
class HoneyStandingMode : StandingMode
{
protected override IEnumerable<IShortcut> CreateShortcuts()
{
return base.CreateShortcuts().Concat(new IShortcut[] {
new MultiKeyboardShortcut(new KeyStroke("Ctrl + C"), new KeyStroke("Ctrl + C"), delegate { VR.Manager.SetMode<HoneySeatedMode>(); } )
});
}
protected override void OnLevel(int level)
{
base.OnLevel(level);
VRLog.Info("Level {0}", level);
if (GameObject.FindObjectOfType<CustomScene>())
{
StartCoroutine(PositionForADV());
}
}
public override IEnumerable<Type> Tools
{
get
{
return base.Tools.Concat(new Type[] { typeof(PlayTool) });
}
}
private IEnumerator PositionForADV()
{
yield return new WaitForEndOfFrame();
if (Camera.main)
{
VR.Camera.Copy(Camera.main);
MoveToPosition(Camera.main.transform.position, Camera.main.transform.rotation);
}
//VR.Camera.SteamCam.origin.position = -VR.Camera.SteamCam.origin.forward + VR.Camera.SteamCam.origin.position.y * Vector3.up;
//VR.Camera.SteamCam.origin.position = new Vector3(0, 1.4f, 1f);
//VR.Camera.SteamCam.origin.rotation = Quaternion.LookRotation(-Vector3.forward);
}
}
}
| mit | C# |
36c35dd84d90af37ad5fc0ba9f74cb261ec05d9e | Update version number | Infinario/unity-sdk | source/Assets/Scripts/InfinarioSDK/Constants.cs | source/Assets/Scripts/InfinarioSDK/Constants.cs | namespace Infinario
{
internal class Constants
{
/**
* SDK
*/
public static string SDK = "Unity SDK";
public static string VERSION = "2.0.2";
/**
* Tracking ids, events and properties
*/
public static string ID_REGISTERED = "registered";
public static string ID_COOKIE = "cookie";
public static string EVENT_SESSION_START = "session_start";
public static string EVENT_SESSION_END = "session_end";
public static string EVENT_IDENTIFICATION = "identification";
public static string EVENT_VIRTUAL_PAYMENT = "virtual_payment";
public static string PROPERTY_APP_VERSION = "app_version";
public static string PROPERTY_DURATION = "duration";
public static string PROPERTY_REGISTRATION_ID = "registration_id";
public static string PROPERTY_CURRENCY = "currency";
public static string PROPERTY_AMOUNT = "amount";
public static string PROPERTY_ITEM_NAME = "item_name";
public static string PROPERTY_ITEM_TYPE = "item_type";
public static string PROPERTY_SESSION_START_TIMESTAMP = "session_start_timestamp";
public static string PROPERTY_SESSION_START_PROPERTIES = "session_start_properties";
public static string PROPERTY_SESSION_END_TIMESTAMP = "session_end_timestamp";
public static string PROPERTY_SESSION_END_PROPERTIES = "session_end_properties";
/**
* Sending
*/
public static int BULK_LIMIT = 49;
public static int BULK_TIMEOUT_MS = 10000;
public static int BULK_INTERVAL_MS = 1000;
public static int BULK_MAX_RETRIES = 20;
public static int BULK_MAX_RETRY_WAIT_MS = 60 * 1000;
public static long BULK_MAX = 60 * 20;
public static double SESSION_TIMEOUT = 60;
public static string DEFAULT_TARGET = "https://api.infinario.com";
public static string BULK_URL = "/bulk";
public static string ENDPOINT_UPDATE = "crm/customers";
public static string ENDPOINT_TRACK = "crm/events";
}
}
| namespace Infinario
{
internal class Constants
{
/**
* SDK
*/
public static string SDK = "Unity SDK";
public static string VERSION = "2.0.1";
/**
* Tracking ids, events and properties
*/
public static string ID_REGISTERED = "registered";
public static string ID_COOKIE = "cookie";
public static string EVENT_SESSION_START = "session_start";
public static string EVENT_SESSION_END = "session_end";
public static string EVENT_IDENTIFICATION = "identification";
public static string EVENT_VIRTUAL_PAYMENT = "virtual_payment";
public static string PROPERTY_APP_VERSION = "app_version";
public static string PROPERTY_DURATION = "duration";
public static string PROPERTY_REGISTRATION_ID = "registration_id";
public static string PROPERTY_CURRENCY = "currency";
public static string PROPERTY_AMOUNT = "amount";
public static string PROPERTY_ITEM_NAME = "item_name";
public static string PROPERTY_ITEM_TYPE = "item_type";
public static string PROPERTY_SESSION_START_TIMESTAMP = "session_start_timestamp";
public static string PROPERTY_SESSION_START_PROPERTIES = "session_start_properties";
public static string PROPERTY_SESSION_END_TIMESTAMP = "session_end_timestamp";
public static string PROPERTY_SESSION_END_PROPERTIES = "session_end_properties";
/**
* Sending
*/
public static int BULK_LIMIT = 49;
public static int BULK_TIMEOUT_MS = 10000;
public static int BULK_INTERVAL_MS = 1000;
public static int BULK_MAX_RETRIES = 20;
public static int BULK_MAX_RETRY_WAIT_MS = 60 * 1000;
public static long BULK_MAX = 60 * 20;
public static double SESSION_TIMEOUT = 60;
public static string DEFAULT_TARGET = "https://api.infinario.com";
public static string BULK_URL = "/bulk";
public static string ENDPOINT_UPDATE = "crm/customers";
public static string ENDPOINT_TRACK = "crm/events";
}
}
| apache-2.0 | C# |
a2a0c2162427c396863311f97e090721b2895846 | Split RuntimeDependency and RuntimeAssembly into separate files | filipw/dotnet-script,filipw/dotnet-script | src/Dotnet.Script.DependencyModel/Runtime/RuntimeDependency.cs | src/Dotnet.Script.DependencyModel/Runtime/RuntimeDependency.cs | using System.Collections.Generic;
namespace Dotnet.Script.DependencyModel.Runtime
{
public class RuntimeDependency
{
public RuntimeDependency(string name, string version, IReadOnlyList<RuntimeAssembly> assemblies, IReadOnlyList<string> nativeAssets, IReadOnlyList<string> scripts)
{
Name = name;
Version = version;
Assemblies = assemblies;
NativeAssets = nativeAssets;
Scripts = scripts;
}
public string Name { get; }
public string Version { get;}
public IReadOnlyList<RuntimeAssembly> Assemblies { get; }
public IReadOnlyList<string> NativeAssets { get; }
public IReadOnlyList<string> Scripts { get; }
}
} | using System.Collections.Generic;
using System.Reflection;
namespace Dotnet.Script.DependencyModel.Runtime
{
public class RuntimeAssembly
{
public AssemblyName Name { get; }
public string Path { get; }
public RuntimeAssembly(AssemblyName name, string path)
{
Name = name;
Path = path;
}
public override int GetHashCode()
{
return Name.GetHashCode() ^ Path.GetHashCode();
}
public override bool Equals(object obj)
{
var other = (RuntimeAssembly)obj;
return other.Name == Name && other.Path == Path;
}
public override string ToString()
{
return $"{nameof(Name)}: {Name}, {nameof(Path)}: {Path}";
}
}
public class RuntimeDependency
{
public RuntimeDependency(string name, string version, IReadOnlyList<RuntimeAssembly> assemblies, IReadOnlyList<string> nativeAssets, IReadOnlyList<string> scripts)
{
Name = name;
Version = version;
Assemblies = assemblies;
NativeAssets = nativeAssets;
Scripts = scripts;
}
public string Name { get; }
public string Version { get;}
public IReadOnlyList<RuntimeAssembly> Assemblies { get; }
public IReadOnlyList<string> NativeAssets { get; }
public IReadOnlyList<string> Scripts { get; }
}
} | mit | C# |
247ff6c10cc5fbd24007107543ee21af233e4cf7 | Add support for listening on multiple urls. | Jark/DeployStatus,Jark/DeployStatus,Jark/DeployStatus | src/DeployStatus/Service/DeployStatusService.cs | src/DeployStatus/Service/DeployStatusService.cs | using System;
using System.Linq;
using DeployStatus.Configuration;
using DeployStatus.SignalR;
using log4net;
using Microsoft.Owin.Hosting;
namespace DeployStatus.Service
{
public class DeployStatusService : IService
{
private IDisposable webApp;
private readonly ILog log;
private readonly DeployStatusConfiguration deployConfiguration;
public DeployStatusService()
{
log = LogManager.GetLogger(typeof (DeployStatusService));
deployConfiguration = DeployStatusSettingsSection.Settings.AsDeployConfiguration();
}
public void Start()
{
log.Info("Starting api polling service...");
DeployStatusState.Instance.Value.Start(deployConfiguration);
var webAppUrl = deployConfiguration.WebAppUrl;
log.Info($"Starting web app service on {webAppUrl}...");
var startOptions = new StartOptions();
foreach (var url in webAppUrl.Split(','))
{
startOptions.Urls.Add(url);
}
webApp = WebApp.Start<Startup>(startOptions);
log.Info("Started.");
}
public void Stop()
{
webApp.Dispose();
DeployStatusState.Instance.Value.Stop();
}
}
} | using System;
using DeployStatus.Configuration;
using DeployStatus.SignalR;
using log4net;
using Microsoft.Owin.Hosting;
namespace DeployStatus.Service
{
public class DeployStatusService : IService
{
private IDisposable webApp;
private readonly ILog log;
private readonly DeployStatusConfiguration deployConfiguration;
public DeployStatusService()
{
log = LogManager.GetLogger(typeof (DeployStatusService));
deployConfiguration = DeployStatusSettingsSection.Settings.AsDeployConfiguration();
}
public void Start()
{
log.Info("Starting api polling service...");
DeployStatusState.Instance.Value.Start(deployConfiguration);
var webAppUrl = deployConfiguration.WebAppUrl;
log.Info($"Starting web app service on {webAppUrl}...");
webApp = WebApp.Start<Startup>(webAppUrl);
log.Info("Started.");
}
public void Stop()
{
webApp.Dispose();
DeployStatusState.Instance.Value.Stop();
}
}
} | mit | C# |
b11156b2cc1e19e419b3174558c1ac0200ee11bf | Create and release tooltip content on demand | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.InlineReviews/Tags/ShowInlineCommentGlyph.xaml.cs | src/GitHub.InlineReviews/Tags/ShowInlineCommentGlyph.xaml.cs | using System;
using System.Windows.Controls;
using GitHub.InlineReviews.Views;
using GitHub.InlineReviews.ViewModels;
namespace GitHub.InlineReviews.Tags
{
public partial class ShowInlineCommentGlyph : UserControl
{
readonly ToolTip toolTip;
public ShowInlineCommentGlyph()
{
InitializeComponent();
toolTip = new ToolTip();
ToolTip = toolTip;
}
protected override void OnToolTipOpening(ToolTipEventArgs e)
{
var tag = Tag as ShowInlineCommentTag;
var viewModel = new CommentTooltipViewModel();
foreach (var comment in tag.Thread.Comments)
{
var commentViewModel = new TooltipCommentViewModel(comment.User, comment.Body, comment.CreatedAt);
viewModel.Comments.Add(commentViewModel);
}
var view = new CommentTooltipView();
view.DataContext = viewModel;
toolTip.Content = view;
}
protected override void OnToolTipClosing(ToolTipEventArgs e)
{
toolTip.Content = null;
}
}
}
| using System;
using System.Windows.Controls;
using GitHub.InlineReviews.Views;
using GitHub.InlineReviews.ViewModels;
namespace GitHub.InlineReviews.Tags
{
public partial class ShowInlineCommentGlyph : UserControl
{
readonly CommentTooltipView commentTooltipView;
public ShowInlineCommentGlyph()
{
InitializeComponent();
commentTooltipView = new CommentTooltipView();
ToolTip = commentTooltipView;
ToolTipOpening += ShowInlineCommentGlyph_ToolTipOpening;
}
private void ShowInlineCommentGlyph_ToolTipOpening(object sender, ToolTipEventArgs e)
{
var tag = Tag as ShowInlineCommentTag;
var viewModel = new CommentTooltipViewModel();
foreach (var comment in tag.Thread.Comments)
{
var commentViewModel = new TooltipCommentViewModel(comment.User, comment.Body, comment.CreatedAt);
viewModel.Comments.Add(commentViewModel);
}
commentTooltipView.DataContext = viewModel;
}
}
}
| mit | C# |
8d55340325b457427661d0ae31d8b0a5e66b255a | Fix up youtube URL regex matching | JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS | src/Umbraco.Web/Media/EmbedProviders/Youtube.cs | src/Umbraco.Web/Media/EmbedProviders/Youtube.cs | using System.Collections.Generic;
namespace Umbraco.Web.Media.EmbedProviders
{
public class YouTube : EmbedProviderBase
{
public override string ApiEndpoint => "https://www.youtube.com/oembed";
public override string[] UrlSchemeRegex => new string[]
{
@"youtu.be/.*",
@"youtube.com/watch.*"
};
public override Dictionary<string, string> RequestParams => new Dictionary<string, string>()
{
//ApiUrl/?format=json
{"format", "json"}
};
public override string GetMarkup(string url, int maxWidth = 0, int maxHeight = 0)
{
var requestUrl = base.GetEmbedProviderUrl(url, maxWidth, maxHeight);
var oembed = base.GetJsonResponse<OEmbedResponse>(requestUrl);
return oembed.GetHtml();
}
}
}
| using System.Collections.Generic;
namespace Umbraco.Web.Media.EmbedProviders
{
public class YouTube : EmbedProviderBase
{
public override string ApiEndpoint => "https://www.youtube.com/oembed";
public override string[] UrlSchemeRegex => new string[]
{
@"youtu.be/.*",
@"youtu.be/.*"
};
public override Dictionary<string, string> RequestParams => new Dictionary<string, string>()
{
//ApiUrl/?format=json
{"format", "json"}
};
public override string GetMarkup(string url, int maxWidth = 0, int maxHeight = 0)
{
var requestUrl = base.GetEmbedProviderUrl(url, maxWidth, maxHeight);
var oembed = base.GetJsonResponse<OEmbedResponse>(requestUrl);
return oembed.GetHtml();
}
}
}
| mit | C# |
e682e6fa3bdbfc8af11494b5d05d1ed32f65e4a9 | update the message | ryanswanstrom/topicnew2 | messages/EchoDialog.csx | messages/EchoDialog.csx | using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
// For more information about this template visit http://aka.ms/azurebots-csharp-basic
[Serializable]
public class EchoDialog : IDialog<object>
{
protected int count = 1;
public Task StartAsync(IDialogContext context)
{
try
{
context.Wait(MessageReceivedAsync);
}
catch (OperationCanceledException error)
{
return Task.FromCanceled(error.CancellationToken);
}
catch (Exception error)
{
return Task.FromException(error);
}
return Task.CompletedTask;
}
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;
if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the count?",
"Didn't get that!",
promptStyle: PromptStyle.Auto);
}
else
{
await context.PostAsync($"{this.count++}: Dr. Bot says {message.Text}");
context.Wait(MessageReceivedAsync);
}
}
public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument)
{
var confirm = await argument;
if (confirm)
{
this.count = 1;
await context.PostAsync("Reset count.");
}
else
{
await context.PostAsync("Did not reset count.");
}
context.Wait(MessageReceivedAsync);
}
} | using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
// For more information about this template visit http://aka.ms/azurebots-csharp-basic
[Serializable]
public class EchoDialog : IDialog<object>
{
protected int count = 1;
public Task StartAsync(IDialogContext context)
{
try
{
context.Wait(MessageReceivedAsync);
}
catch (OperationCanceledException error)
{
return Task.FromCanceled(error.CancellationToken);
}
catch (Exception error)
{
return Task.FromException(error);
}
return Task.CompletedTask;
}
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;
if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the count?",
"Didn't get that!",
promptStyle: PromptStyle.Auto);
}
else
{
await context.PostAsync($"{this.count++}: Super Cool Bot says {message.Text}");
context.Wait(MessageReceivedAsync);
}
}
public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument)
{
var confirm = await argument;
if (confirm)
{
this.count = 1;
await context.PostAsync("Reset count.");
}
else
{
await context.PostAsync("Did not reset count.");
}
context.Wait(MessageReceivedAsync);
}
} | mit | C# |
d8fc29387c85603e20639ad513d3ff6ce02cafea | add saveFileDialog | BartoszBaczek/WorkshopRequestsManager | Project/WorkshopManager/WorkshopManager/PDF/PDFGenerator.cs | Project/WorkshopManager/WorkshopManager/PDF/PDFGenerator.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Reporting.WinForms;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using WorkshopManager.Models;
namespace WorkshopManager
{
class PDFGenerator
{
public void PDFGenerate(Request request)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "pdf files (*.pdf)|*.pdf";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.LocalReport.ReportEmbeddedResource = "WorkshopManager.PDF.PDF.rdlc";
DateTime thisDay = DateTime.Today;
string numberPDF = thisDay.ToString("d") + '/' + request.ID;
ReportParameter owner = new ReportParameter("owner", request.Owner);
ReportParameter pdfno = new ReportParameter("pdfno", numberPDF);
ReportParameter date = new ReportParameter("date", thisDay.ToString("d"));
ReportViewer1.LocalReport.SetParameters(new ReportParameter[] { owner, pdfno, date });
byte[] byteViewer = ReportViewer1.LocalReport.Render("PDF");
myStream.Write(byteViewer, 0, byteViewer.Length);
myStream.Close();
}
}
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Reporting.WinForms;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using WorkshopManager.Models;
namespace WorkshopManager
{
class PDFGenerator
{
public void PDFGenerate(Request request)
{
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.LocalReport.ReportEmbeddedResource = "WorkshopManager.PDF.PDF.rdlc";
DateTime thisDay = DateTime.Today;
string numberPDF = thisDay.ToString("d") + '/' + request.ID;
ReportParameter owner = new ReportParameter("owner", request.Owner);
ReportParameter pdfno = new ReportParameter("pdfno", numberPDF);
ReportParameter date = new ReportParameter("date", thisDay.ToString("d"));
ReportViewer1.LocalReport.SetParameters(new ReportParameter[] { owner, pdfno, date });
byte[] byteViewer = ReportViewer1.LocalReport.Render("PDF");
FileStream newFile;
string filename = request.ID.ToString() + ".pdf";
string path = "C:\\Users\\Rafał\\Desktop" + filename;
newFile = new FileStream(path, FileMode.Create);
newFile.Write(byteViewer, 0, byteViewer.Length);
newFile.Flush();
newFile.Close();
}
}
} | mit | C# |
bc921cf8b62a4de4e6761857596c9f6a726aa7fa | Add documentation for access token implementation. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Authentication/TraktAccessToken.cs | Source/Lib/TraktApiSharp/Authentication/TraktAccessToken.cs | namespace TraktApiSharp.Authentication
{
using Enums;
using Newtonsoft.Json;
using System;
/// <summary>
/// Represents a Trakt access token response.
/// <para>
/// See also <seealso cref="TraktOAuth.GetAccessTokenAsync()" />,
/// <seealso cref="TraktOAuth.GetAccessTokenAsync(string)" />,
/// <seealso cref="TraktOAuth.GetAccessTokenAsync(string, string)" />,
/// <seealso cref="TraktOAuth.GetAccessTokenAsync(string, string, string)" /> or
/// <seealso cref="TraktOAuth.GetAccessTokenAsync(string, string, string, string)" />.<para />
/// See also <seealso cref="TraktDeviceAuth.PollForAccessTokenAsync()" />,
/// <seealso cref="TraktDeviceAuth.PollForAccessTokenAsync(TraktDevice)" />,
/// <seealso cref="TraktDeviceAuth.PollForAccessTokenAsync(TraktDevice, string)" />,
/// <seealso cref="TraktDeviceAuth.PollForAccessTokenAsync(TraktDevice, string, string)" />.<para />
/// See also <seealso cref="TraktAuthentication.AccessToken" />.<para />
/// See <a href="http://docs.trakt.apiary.io/#reference/authentication-oauth/get-token/exchange-code-for-access_token">"Trakt API Doc - OAuth: Get Token"</a> for more information.
/// </para>
/// </summary>
public class TraktAccessToken
{
/// <summary>
/// Initializes a new instance of the <see cref="TraktAccessToken" /> class.
/// <para>The instantiated token instance is invalid.</para>
/// </summary>
public TraktAccessToken()
{
Created = DateTime.UtcNow;
}
/// <summary>Gets or sets the actual access token.</summary>
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
/// <summary>Gets or sets the actual refresh token.</summary>
[JsonProperty(PropertyName = "refresh_token")]
public string RefreshToken { get; set; }
/// <summary>Gets or sets the token access scope. See also <seealso cref="TraktAccessScope" />.</summary>
[JsonProperty(PropertyName = "scope")]
[JsonConverter(typeof(TraktAccessScopeConverter))]
public TraktAccessScope AccessScope { get; set; }
/// <summary>Gets or sets the seconds, after which this token will expire.</summary>
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresInSeconds { get; set; }
/// <summary>Gets or sets the token type. See also <seealso cref="TraktAccessTokenType" />.</summary>
[JsonProperty(PropertyName = "token_type")]
[JsonConverter(typeof(TraktAccessTokenTypeConverter))]
public TraktAccessTokenType TokenType { get; set; }
/// <summary>
/// Returns, whether this token is valid.
/// <para>
/// A Trakt access token is valid, as long as the actual <see cref="AccessToken" />
/// is neither null nor empty and as long as this token is not expired.<para />
/// See also <seealso cref="ExpiresInSeconds" />.
/// </para>
/// </summary>
[JsonIgnore]
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && DateTime.UtcNow.AddSeconds(ExpiresInSeconds) > DateTime.UtcNow;
/// <summary>Gets the UTC DateTime, when this token was created.</summary>
[JsonIgnore]
public DateTime Created { get; private set; }
}
}
| namespace TraktApiSharp.Authentication
{
using Enums;
using Newtonsoft.Json;
using System;
public class TraktAccessToken
{
public TraktAccessToken()
{
Created = DateTime.UtcNow;
}
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty(PropertyName = "scope")]
[JsonConverter(typeof(TraktAccessScopeConverter))]
public TraktAccessScope AccessScope { get; set; }
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresInSeconds { get; set; }
[JsonProperty(PropertyName = "token_type")]
[JsonConverter(typeof(TraktAccessTokenTypeConverter))]
public TraktAccessTokenType TokenType { get; set; }
[JsonIgnore]
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && DateTime.UtcNow.AddSeconds(ExpiresInSeconds) > DateTime.UtcNow;
[JsonIgnore]
public DateTime Created { get; private set; }
}
}
| mit | C# |
4b370ec763b69d06569933d71677a6d4727da66a | Fix issue with Page calculation | Krusen/ErgastApi.Net | src/ErgastApi/Responses/ErgastResponse.cs | src/ErgastApi/Responses/ErgastResponse.cs | using System;
using Newtonsoft.Json;
namespace ErgastApi.Responses
{
// TODO: Use internal/private constructors for all response types?
public abstract class ErgastResponse
{
[JsonProperty("url")]
public string RequestUrl { get; protected set; }
[JsonProperty("limit")]
public int Limit { get; protected set; }
[JsonProperty("offset")]
public int Offset { get; protected set; }
[JsonProperty("total")]
public int TotalResults { get; protected set; }
// TODO: Note that it can be inaccurate if limit/offset do not divide evenly
public int Page
{
get
{
if (Limit <= 0)
return 1;
return (int) Math.Ceiling((double) Offset / Limit) + 1;
}
}
// TODO: Test with 0 values
public int TotalPages => (int) Math.Ceiling(TotalResults / (double) Limit);
// TODO: Test
public bool HasMorePages => TotalResults > Limit + Offset;
}
}
| using System;
using Newtonsoft.Json;
namespace ErgastApi.Responses
{
// TODO: Use internal/private constructors for all response types?
public abstract class ErgastResponse
{
[JsonProperty("url")]
public virtual string RequestUrl { get; private set; }
[JsonProperty("limit")]
public virtual int Limit { get; private set; }
[JsonProperty("offset")]
public virtual int Offset { get; private set; }
[JsonProperty("total")]
public virtual int TotalResults { get; private set; }
// TODO: Note that it can be inaccurate if limit/offset do not correlate
// TODO: Test with 0 values
public virtual int Page => Offset / Limit + 1;
// TODO: Test with 0 values
public virtual int TotalPages => (int) Math.Ceiling(TotalResults / (double)Limit);
// TODO: Test
public virtual bool HasMorePages => TotalResults > Limit + Offset;
}
}
| unlicense | C# |
251cbc8f829a7b5a8687857e03aa9d5c4675b111 | Add checking of Read() return value. | yvschmid/NModbus4,richardlawley/NModbus4,NModbus4/NModbus4,Maxwe11/NModbus4,NModbus/NModbus,xlgwr/NModbus4 | Modbus/IO/StreamResourceUtility.cs | Modbus/IO/StreamResourceUtility.cs | using System.Linq;
using System.Text;
namespace Modbus.IO
{
internal static class StreamResourceUtility
{
internal static string ReadLine(IStreamResource stream)
{
var result = new StringBuilder();
var singleByteBuffer = new byte[1];
do
{
if (0 == stream.Read(singleByteBuffer, 0, 1))
continue;
result.Append(Encoding.ASCII.GetChars(singleByteBuffer).First());
} while (!result.ToString().EndsWith(Modbus.NewLine));
return result.ToString().Substring(0, result.Length - Modbus.NewLine.Length);
}
}
}
| using System.Linq;
using System.Text;
namespace Modbus.IO
{
internal static class StreamResourceUtility
{
internal static string ReadLine(IStreamResource stream)
{
var result = new StringBuilder();
var singleByteBuffer = new byte[1];
do
{
stream.Read(singleByteBuffer, 0, 1);
result.Append(Encoding.ASCII.GetChars(singleByteBuffer).First());
} while (!result.ToString().EndsWith(Modbus.NewLine));
return result.ToString().Substring(0, result.Length - Modbus.NewLine.Length);
}
}
} | mit | C# |
5571f262c4c7f30bebfb763e4fb05cc92daa1359 | remove sealed from Success.Map | acple/ParsecSharp | ParsecSharp/Core/Result/Success.cs | ParsecSharp/Core/Result/Success.cs | using System;
namespace ParsecSharp
{
public class Success<TToken, T> : Result<TToken, T>
{
public override T Value { get; }
protected internal Success(T result, IParsecStateStream<TToken> state) : base(state)
{
this.Value = result;
}
internal sealed override Result<TToken, TResult> Next<TNext, TResult>(Func<T, Parser<TToken, TNext>> next, Func<Result<TToken, TNext>, Result<TToken, TResult>> cont)
=> next(this.Value).Run(this.Rest, cont);
public sealed override TResult CaseOf<TResult>(Func<Fail<TToken, T>, TResult> fail, Func<Success<TToken, T>, TResult> success)
=> success(this);
public override Result<TToken, TResult> Map<TResult>(Func<T, TResult> function)
=> new Success<TToken, TResult>(function(this.Value), this.Rest);
public override string ToString()
=> this.Value?.ToString() ?? string.Empty;
}
}
| using System;
namespace ParsecSharp
{
public class Success<TToken, T> : Result<TToken, T>
{
public override T Value { get; }
protected internal Success(T result, IParsecStateStream<TToken> state) : base(state)
{
this.Value = result;
}
internal sealed override Result<TToken, TResult> Next<TNext, TResult>(Func<T, Parser<TToken, TNext>> next, Func<Result<TToken, TNext>, Result<TToken, TResult>> cont)
=> next(this.Value).Run(this.Rest, cont);
public sealed override TResult CaseOf<TResult>(Func<Fail<TToken, T>, TResult> fail, Func<Success<TToken, T>, TResult> success)
=> success(this);
public sealed override Result<TToken, TResult> Map<TResult>(Func<T, TResult> function)
=> new Success<TToken, TResult>(function(this.Value), this.Rest);
public override string ToString()
=> this.Value?.ToString() ?? string.Empty;
}
}
| mit | C# |
63340ca663e5970b95c95a05b1fbafac06eb6962 | use custom json serialization in metrics module | MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,ntent-ad/Metrics.NET,Liwoj/Metrics.NET,Liwoj/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,huoxudong125/Metrics.NET,huoxudong125/Metrics.NET,etishor/Metrics.NET,ntent-ad/Metrics.NET,mnadel/Metrics.NET,Recognos/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET | Src/Adapters/Nancy.Metrics/MetricsModule.cs | Src/Adapters/Nancy.Metrics/MetricsModule.cs | using System;
using Metrics;
using Metrics.Reporters;
using Metrics.Visualization;
namespace Nancy.Metrics
{
public class MetricsModule : NancyModule
{
private struct ModuleConfig
{
public readonly string ModulePath;
public readonly Action<INancyModule> ModuleConfigAction;
public readonly MetricsRegistry Registry;
public ModuleConfig(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
this.Registry = registry;
this.ModuleConfigAction = moduleConfig;
this.ModulePath = metricsPath;
}
}
private static ModuleConfig Config;
public static void Configure(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
MetricsModule.Config = new ModuleConfig(registry, moduleConfig, metricsPath);
}
public MetricsModule()
: base(Config.ModulePath ?? "/")
{
if (string.IsNullOrEmpty(Config.ModulePath))
{
return;
}
if (Config.ModuleConfigAction != null)
{
Config.ModuleConfigAction(this);
}
Get["/"] = _ => Response.AsText(FlotWebApp.GetFlotApp(new Uri(this.Context.Request.Url, "json")), "text/html");
Get["/text"] = _ => Response.AsText(Metric.GetAsHumanReadable());
Get["/json"] = _ => Response.AsText(new RegistrySerializer().ValuesAsJson(Config.Registry), "text/json");
}
}
}
| using System;
using Metrics;
using Metrics.Reporters;
using Metrics.Visualization;
namespace Nancy.Metrics
{
public class MetricsModule : NancyModule
{
private struct ModuleConfig
{
public readonly string ModulePath;
public readonly Action<INancyModule> ModuleConfigAction;
public readonly MetricsRegistry Registry;
public ModuleConfig(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
this.Registry = registry;
this.ModuleConfigAction = moduleConfig;
this.ModulePath = metricsPath;
}
}
private static ModuleConfig Config;
public static void Configure(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
MetricsModule.Config = new ModuleConfig(registry, moduleConfig, metricsPath);
}
public MetricsModule()
: base(Config.ModulePath ?? "/")
{
if (string.IsNullOrEmpty(Config.ModulePath))
{
return;
}
if (Config.ModuleConfigAction != null)
{
Config.ModuleConfigAction(this);
}
Get["/"] = _ => Response.AsText(FlotWebApp.GetFlotApp(new Uri(this.Context.Request.Url, "json")), "text/html");
Get["/text"] = _ => Response.AsText(Metric.GetAsHumanReadable());
Get["/json"] = _ => Response.AsJson(new RegistrySerializer().GetForSerialization(Config.Registry));
}
}
}
| apache-2.0 | C# |
c8a11599f40f38f53f568135dd5d12e4a70ebb86 | add PasswordEntry.PlaceholderText sample | cra0zy/xwt,akrisiun/xwt,directhex/xwt,iainx/xwt,mminns/xwt,sevoku/xwt,mono/xwt,antmicro/xwt,steffenWi/xwt,mminns/xwt,hwthomas/xwt,TheBrainTech/xwt,hamekoz/xwt,residuum/xwt,lytico/xwt | TestApps/Samples/Samples/PasswordEntries.cs | TestApps/Samples/Samples/PasswordEntries.cs | //
// PasswordEntry.cs
//
// Author:
// Bojan Rajkovic <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
namespace Samples
{
public class PasswordEntries : VBox
{
public PasswordEntries ()
{
PasswordEntry te1 = new PasswordEntry ();
te1.PlaceholderText = "Enter Password ...";
PackStart (te1);
Button b = new Button ("Show password");
Label l = new Label ();
b.Clicked += (sender, e) => {
l.Text = ("Password is: " + te1.Password);
};
PackStart (b);
PackStart (l);
}
}
}
| //
// PasswordEntry.cs
//
// Author:
// Bojan Rajkovic <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
namespace Samples
{
public class PasswordEntries : VBox
{
public PasswordEntries ()
{
PasswordEntry te1 = new PasswordEntry ();
PackStart (te1);
Button b = new Button ("Show password");
Label l = new Label ();
b.Clicked += (sender, e) => {
l.Text = ("Password is: " + te1.Password);
};
PackStart (b);
PackStart (l);
}
}
}
| mit | C# |
1807fa2d6208e5dbbdb0110d09404d3d6c306301 | Improve EF Core tests | axelheer/nein-linq,BenJenkinson/nein-linq | test/NeinLinq.Tests/EntityAsyncQuery/Context.cs | test/NeinLinq.Tests/EntityAsyncQuery/Context.cs | using Microsoft.EntityFrameworkCore;
using NeinLinq.Fakes.EntityAsyncQuery;
namespace NeinLinq.Tests.EntityAsyncQuery
{
public class Context : DbContext
{
public DbSet<Dummy> Dummies { get; }
public Context()
{
Dummies = Set<Dummy>();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlite("Data Source=NeinLinq.EntityFrameworkCore.db");
public void CreateDatabase(params Dummy[] seed)
{
if (Database.EnsureCreated())
{
Dummies.AddRange(seed);
_ = SaveChanges();
}
}
}
}
| using Microsoft.EntityFrameworkCore;
using NeinLinq.Fakes.EntityAsyncQuery;
namespace NeinLinq.Tests.EntityAsyncQuery
{
public class Context : DbContext
{
public DbSet<Dummy> Dummies { get; }
public Context()
{
Dummies = Set<Dummy>();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlite("Data Source=NeinLinq.EntityFrameworkCore.db");
public void CreateDatabase(params Dummy[] seed)
{
_ = Database.EnsureDeleted();
_ = Database.EnsureCreated();
Dummies.AddRange(seed);
_ = SaveChanges();
}
}
}
| mit | C# |
30a2f54b499e3bb852034aa1e9a9fe9aeabd7666 | Remove unused code | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade.Core/Base/Addml/AddmlUtil.cs | src/Arkivverket.Arkade.Core/Base/Addml/AddmlUtil.cs | using System;
using System.IO;
using Arkivverket.Arkade.Core.Base.Addml.Definitions;
using Arkivverket.Arkade.Core.ExternalModels.Addml;
using Arkivverket.Arkade.Core.Util;
using System.Xml.Schema;
using Serilog;
namespace Arkivverket.Arkade.Core.Base.Addml
{
public class AddmlUtil
{
public static addml ReadFromString(string xml)
{
return SerializeUtil.DeserializeFromString<addml>(xml);
}
public static AddmlInfo ReadFromFile(string fileName)
{
string addmlXsd = ResourceUtil.ReadResource(ArkadeConstants.AddmlXsdResource);
try
{
string fileContent = File.ReadAllText(fileName);
addml addml = ReadFromString(fileContent);
Validate(fileContent, addmlXsd);
return new AddmlInfo(addml, new FileInfo(fileName));
}
catch (Exception e)
{
throw new ArkadeException(string.Format(Resources.Messages.ExceptionReadingAddmlFile, e.Message), e);
}
}
private static void Validate(string fileContent, string addmlXsd)
{
try
{
new XmlValidator().Validate(fileContent, addmlXsd);
} catch (XmlSchemaException e)
{
throw new ArkadeException(e.Message);
}
}
}
}
| using System;
using System.IO;
using Arkivverket.Arkade.Core.Base.Addml.Definitions;
using Arkivverket.Arkade.Core.ExternalModels.Addml;
using Arkivverket.Arkade.Core.Util;
using System.Xml.Schema;
using Serilog;
namespace Arkivverket.Arkade.Core.Base.Addml
{
public class AddmlUtil
{
public static addml ReadFromString(string xml)
{
return SerializeUtil.DeserializeFromString<addml>(xml);
}
public static AddmlInfo ReadFromFile(string fileName)
{
string addmlXsd = ResourceUtil.ReadResource(ArkadeConstants.AddmlXsdResource);
try
{
string fileContent = File.ReadAllText(fileName);
addml addml = ReadFromString(fileContent);
Validate(fileContent, addmlXsd);
return new AddmlInfo(addml, new FileInfo(fileName));
}
catch (FileNotFoundException e)
{
Log.Logger.Debug(e.ToString());
throw new ArkadeException(string.Format(Resources.ExceptionMessages.FileNotFound, fileName));
}
catch (Exception e)
{
throw new ArkadeException(string.Format(Resources.Messages.ExceptionReadingAddmlFile, e.Message), e);
}
}
private static void Validate(string fileContent, string addmlXsd)
{
try
{
new XmlValidator().Validate(fileContent, addmlXsd);
} catch (XmlSchemaException e)
{
throw new ArkadeException(e.Message);
}
}
public static AddmlInfo ReadFromBaseDirectory(string fileName)
{
return ReadFromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName));
}
private static void Validate(addml addml)
{
}
}
}
| agpl-3.0 | C# |
320476f8da56704035b9da6f558960638ab4d1ef | Sort and remove unused usings | SaarCohen/VisualStudio,YOTOV-LIMITED/VisualStudio,Dr0idKing/VisualStudio,luizbon/VisualStudio,shaunstanislaus/VisualStudio,yovannyr/VisualStudio,bbqchickenrobot/VisualStudio,github/VisualStudio,modulexcite/VisualStudio,github/VisualStudio,HeadhunterXamd/VisualStudio,radnor/VisualStudio,mariotristan/VisualStudio,GuilhermeSa/VisualStudio,8v060htwyc/VisualStudio,bradthurber/VisualStudio,GProulx/VisualStudio,ChristopherHackett/VisualStudio,AmadeusW/VisualStudio,nulltoken/VisualStudio,naveensrinivasan/VisualStudio,amytruong/VisualStudio,github/VisualStudio,pwz3n0/VisualStudio | src/GitHub.VisualStudio/Services/SharedResources.cs | src/GitHub.VisualStudio/Services/SharedResources.cs | using System.Collections.Generic;
using System.Windows.Media;
using GitHub.UI;
using GitHub.VisualStudio.UI;
namespace GitHub.VisualStudio
{
public static class SharedResources
{
static readonly Dictionary<string, DrawingBrush> drawingBrushes = new Dictionary<string, DrawingBrush>();
public static DrawingBrush GetDrawingForIcon(Octicon icon, Brush color)
{
string name = icon.ToString();
if (drawingBrushes.ContainsKey(name))
return drawingBrushes[name];
var brush = new DrawingBrush()
{
Drawing = new GeometryDrawing()
{
Brush = color,
Pen = new Pen(color, 1.0).FreezeThis(),
Geometry = OcticonPath.GetGeometryForIcon(icon).FreezeThis()
}
.FreezeThis(),
Stretch = Stretch.Uniform
}
.FreezeThis();
drawingBrushes.Add(name, brush);
return brush;
}
}
}
| using GitHub.UI;
using GitHub.VisualStudio.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace GitHub.VisualStudio
{
public static class SharedResources
{
static readonly Dictionary<string, DrawingBrush> drawingBrushes = new Dictionary<string, DrawingBrush>();
public static DrawingBrush GetDrawingForIcon(Octicon icon, Brush color)
{
string name = icon.ToString();
if (drawingBrushes.ContainsKey(name))
return drawingBrushes[name];
var brush = new DrawingBrush()
{
Drawing = new GeometryDrawing()
{
Brush = color,
Pen = new Pen(color, 1.0).FreezeThis(),
Geometry = OcticonPath.GetGeometryForIcon(icon).FreezeThis()
}
.FreezeThis(),
Stretch = Stretch.Uniform
}
.FreezeThis();
drawingBrushes.Add(name, brush);
return brush;
}
}
}
| mit | C# |
e47057819d804efdffdaa0e0120d15e749952ae0 | Refactor StatementMapperTests | lpatalas/NhLogAnalyzer | NhLogAnalyzer.UnitTests/Infrastructure/StatementMapperTests.cs | NhLogAnalyzer.UnitTests/Infrastructure/StatementMapperTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NhLogAnalyzer.Infrastructure;
using Xunit;
namespace NhLogAnalyzer.UnitTests.Fakes
{
public class StatementMapperTests
{
public class MapMethod
{
private readonly MockSqlFormatter fullSqlFormatter = new MockSqlFormatter();
private readonly MockSqlFormatter shortSqlFormatter = new MockSqlFormatter();
private readonly MockStackTraceParser stackTraceParser = new MockStackTraceParser();
private readonly StatementMapper statementMapper;
public MapMethod()
{
statementMapper = new StatementMapper(fullSqlFormatter, shortSqlFormatter, stackTraceParser);
}
[Fact]
public void Should_copy_Id_and_Timestamp_properties_to_returned_row()
{
// Arrange
var input = new StatementRow(1, string.Empty, string.Empty, new DateTime(2013, 2, 12));
// Act
var output = statementMapper.Map(input);
// Assert
Assert.Equal(input.Id, output.Id);
Assert.Equal(input.Timestamp, output.Timestamp);
}
[Fact]
public void Should_use_shortSqlFormatter_to_set_ShortSqlText_property()
{
// Arrange
var inputRow = new StatementRow(1, "SQL", string.Empty, DateTime.Now);
shortSqlFormatter.FormatImpl = input => "Short" + input;
// Act
var output = statementMapper.Map(inputRow);
// Assert
Assert.Equal("ShortSQL", output.ShortSql);
}
[Fact]
public void Should_use_fullSqlFormatter_to_format_FullSql_property()
{
// Arrange
var inputRow = new StatementRow(1, "SQL", string.Empty, DateTime.Now);
fullSqlFormatter.FormatImpl = input => "Full" + input;
// Act
var output = statementMapper.Map(inputRow);
// Assert
Assert.Equal("FullSQL", output.FullSql);
}
[Fact]
public void Should_use_stack_trace_parser_to_extract_stack_frames_from_StrackTrace_column()
{
// Arrange
stackTraceParser.ParseImpl = input =>
{
return new[]
{
new StackFrame(input + "Method", input + "File", 0, 0),
};
};
var inputRow = new StatementRow { StackTrace = "Stack" };
// Act
var output = statementMapper.Map(inputRow);
// Assert
Assert.Equal(1, output.StackFrames.Count);
Assert.Equal("StackMethod", output.StackFrames[0].Method);
Assert.Equal("StackFile", output.StackFrames[0].FileName);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NhLogAnalyzer.Infrastructure;
using Xunit;
namespace NhLogAnalyzer.UnitTests.Fakes
{
public class StatementMapperTests
{
public class MapMethod
{
private readonly MockSqlFormatter dummySqlFormatter = new MockSqlFormatter();
private readonly MockStackTraceParser dummyStackTraceParser = new MockStackTraceParser();
[Fact]
public void Should_copy_Id_and_Timestamp_properties_to_returned_row()
{
// Arrange
var input = new StatementRow(1, string.Empty, string.Empty, new DateTime(2013, 2, 12));
var statementMapper = new StatementMapper(dummySqlFormatter, dummySqlFormatter, dummyStackTraceParser);
// Act
var output = statementMapper.Map(input);
// Assert
Assert.Equal(input.Id, output.Id);
Assert.Equal(input.Timestamp, output.Timestamp);
}
[Fact]
public void Should_use_shortSqlFormatter_to_set_ShortSqlText_property()
{
// Arrange
var inputRow = new StatementRow(1, "SQL", string.Empty, DateTime.Now);
var shortSqlFormatter = new MockSqlFormatter();
shortSqlFormatter.FormatImpl = input => "Short" + input;
var statementMapper = new StatementMapper(dummySqlFormatter, shortSqlFormatter, dummyStackTraceParser);
// Act
var output = statementMapper.Map(inputRow);
// Assert
Assert.Equal("ShortSQL", output.ShortSql);
}
[Fact]
public void Should_use_fullSqlFormatter_to_format_FullSql_property()
{
// Arrange
var inputRow = new StatementRow(1, "SQL", string.Empty, DateTime.Now);
var fullSqlFormatter = new MockSqlFormatter();
fullSqlFormatter.FormatImpl = input => "Full" + input;
var statementMapper = new StatementMapper(fullSqlFormatter, dummySqlFormatter, dummyStackTraceParser);
// Act
var output = statementMapper.Map(inputRow);
// Assert
Assert.Equal("FullSQL", output.FullSql);
}
[Fact]
public void Should_use_stack_trace_parser_to_extract_stack_frames_from_StrackTrace_column()
{
// Arrange
var stackTraceParser = new MockStackTraceParser();
stackTraceParser.ParseImpl = input =>
{
return new[]
{
new StackFrame(input + "Method", input + "File", 0, 0),
};
};
var inputRow = new StatementRow { StackTrace = "Stack" };
var statementMapper = new StatementMapper(dummySqlFormatter, dummySqlFormatter, stackTraceParser);
// Act
var output = statementMapper.Map(inputRow);
// Assert
Assert.Equal(1, output.StackFrames.Count);
Assert.Equal("StackMethod", output.StackFrames[0].Method);
Assert.Equal("StackFile", output.StackFrames[0].FileName);
}
}
}
}
| mit | C# |
998237b83d5d753a066e5910563cae3209481517 | Add extra work to RedditBrowser sample | canton7/Stylet,canton7/Stylet,cH40z-Lord/Stylet,cH40z-Lord/Stylet | Samples/Stylet.Samples.RedditBrowser/Pages/TaskbarViewModel.cs | Samples/Stylet.Samples.RedditBrowser/Pages/TaskbarViewModel.cs | using Stylet.Samples.RedditBrowser.Events;
using Stylet.Samples.RedditBrowser.RedditApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stylet.Samples.RedditBrowser.Pages
{
public class TaskbarViewModel : Screen
{
private IEventAggregator events;
public string Subreddit { get; set; }
public IEnumerable<SortMode> SortModes { get; private set; }
public SortMode SelectedSortMode { get; set; }
public TaskbarViewModel(IEventAggregator events)
{
this.events = events;
this.SortModes = SortMode.AllModes;
this.SelectedSortMode = SortMode.Hot;
}
public bool CanOpen
{
get { return !String.IsNullOrWhiteSpace(this.Subreddit); }
}
public void Open()
{
this.events.Publish(new OpenSubredditEvent() { Subreddit = this.Subreddit, SortMode = this.SelectedSortMode });
}
}
}
| using Stylet.Samples.RedditBrowser.Events;
using Stylet.Samples.RedditBrowser.RedditApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stylet.Samples.RedditBrowser.Pages
{
public class TaskbarViewModel : Screen
{
private IEventAggregator events;
public string Subreddit { get; set; }
public IEnumerable<SortMode> SortModes { get; private set; }
public SortMode SelectedSortMode { get; set; }
public TaskbarViewModel(IEventAggregator events)
{
this.events = events;
this.SortModes = SortMode.AllModes;
this.SelectedSortMode = SortMode.Hot;
}
public void Open()
{
this.events.Publish(new OpenSubredditEvent() { Subreddit = this.Subreddit, SortMode = this.SelectedSortMode });
}
}
}
| mit | C# |
bf903140927f4a34dba006a7aff0dfb835d36128 | Order of registrations in BatchClient.PopulateSearchCache | OS2CPRbroker/cprbroker,OS2CPRbroker/cprbroker,magenta-aps/cprbroker,magenta-aps/cprbroker,magenta-aps/cprbroker | PART/Source/CprBroker/BatchClient/PopulateSearchCache.cs | PART/Source/CprBroker/BatchClient/PopulateSearchCache.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CprBroker.Utilities.ConsoleApps;
namespace BatchClient
{
class PopulateSearchCache : ConsoleEnvironment
{
public override string[] LoadCprNumbers()
{
using (var dataContext = new CprBroker.Data.Part.PartDataContext(BrokerConnectionString))
{
return dataContext.PersonRegistrations
.Select(pr => pr.UUID.ToString()).Distinct().OrderBy(pr => pr).ToArray();
}
}
public override void ProcessPerson(string uuid)
{
using (var dataContext = new CprBroker.Data.Part.PartDataContext(BrokerConnectionString))
{
var reg = dataContext.PersonRegistrations.Where(pr => pr.UUID == new Guid(uuid))
.OrderByDescending(pr => pr.RegistrationDate)
.ThenByDescending(pr => pr.BrokerUpdateDate)
.First();
dataContext.ExecuteCommand("UPDATE PersonRegistration SET Contents = Contents WHERE UUID={0} AND PersonRegistrationId = {1}", uuid, reg.PersonRegistrationId);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CprBroker.Utilities.ConsoleApps;
namespace BatchClient
{
class PopulateSearchCache : ConsoleEnvironment
{
public override string[] LoadCprNumbers()
{
using (var dataContext = new CprBroker.Data.Part.PartDataContext(BrokerConnectionString))
{
return dataContext.PersonRegistrations
.Select(pr => pr.UUID.ToString()).Distinct().OrderBy(pr => pr).ToArray();
}
}
public override void ProcessPerson(string uuid)
{
using (var dataContext = new CprBroker.Data.Part.PartDataContext(BrokerConnectionString))
{
var reg = dataContext.PersonRegistrations.Where(pr => pr.UUID == new Guid(uuid)).OrderByDescending(pr => pr.RegistrationDate).First();
dataContext.ExecuteCommand("UPDATE PersonRegistration SET Contents = Contents WHERE UUID={0} AND PersonRegistrationId = {1}", uuid, reg.PersonRegistrationId);
}
}
}
}
| mpl-2.0 | C# |
8c123c07f7e35a6fca57f4890cc0bc9f4a3a22d4 | Make Case abstract | yawaramin/TDDUnit | Case.cs | Case.cs | using System;
namespace TDDUnit {
abstract class Case {
public Case(string name) {
m_name = name;
}
public virtual void SetUp() {
}
public void Run(Result result) {
try {
SetUp();
} catch (Exception) {
return;
}
result.TestStarted();
try {
GetType().GetMethod(m_name).Invoke(this, null);
} catch (Exception) {
result.TestFailed();
} finally {
TearDown();
}
}
public string Name {
get {
return m_name;
}
}
public virtual void TearDown() {
}
private string m_name;
}
}
| using System;
namespace TDDUnit {
class Case {
public Case(string name) {
m_name = name;
}
public virtual void SetUp() {
}
public void Run(Result result) {
try {
SetUp();
} catch (Exception) {
return;
}
result.TestStarted();
try {
GetType().GetMethod(m_name).Invoke(this, null);
} catch (Exception) {
result.TestFailed();
} finally {
TearDown();
}
}
public string Name {
get {
return m_name;
}
}
public virtual void TearDown() {
}
private string m_name;
}
}
| apache-2.0 | C# |
986af83de568cc1b0090f37afe3fcbf9e7f9bacd | Update assembly | matt40k/TabularDataPackageBuilder | SRC/TabularDataPackageBuilder/Properties/AssemblyInfo.cs | SRC/TabularDataPackageBuilder/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("Tabular Data Package Builder")]
[assembly: AssemblyDescription("Creates a Data Package from CSV files")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tabular Data Package Builder")]
[assembly: AssemblyCopyright("Copyright © Matt Smith 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("287faf67-895e-460a-854c-be003bd88c39")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TabularDataPackage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TabularDataPackage")]
[assembly: AssemblyCopyright("Copyright © Matt Smith 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("287faf67-895e-460a-854c-be003bd88c39")]
// 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# |
d843f39a4cb2533344afe5b41cea015cdac8ae4c | Fix not considering window being null in headless tests | peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework | osu.Framework.Tests/Visual/Platform/TestSceneActiveState.cs | osu.Framework.Tests/Visual/Platform/TestSceneActiveState.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Platform
{
public class TestSceneActiveState : FrameworkTestScene
{
private IBindable<bool> isActive;
private IBindable<bool> cursorInWindow;
private Box isActiveBox;
private Box cursorInWindowBox;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
isActive = host.IsActive.GetBoundCopy();
cursorInWindow = host.Window?.CursorInWindow.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
Children = new Drawable[]
{
isActiveBox = new Box
{
Colour = Color4.Black,
Width = 0.5f,
RelativeSizeAxes = Axes.Both,
},
cursorInWindowBox = new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
Width = 0.5f,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
};
isActive.BindValueChanged(active => isActiveBox.Colour = active.NewValue ? Color4.Green : Color4.Red, true);
cursorInWindow?.BindValueChanged(active => cursorInWindowBox.Colour = active.NewValue ? Color4.Green : Color4.Red, true);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Platform
{
public class TestSceneActiveState : FrameworkTestScene
{
private IBindable<bool> isActive;
private IBindable<bool> cursorInWindow;
private Box isActiveBox;
private Box cursorInWindowBox;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
isActive = host.IsActive.GetBoundCopy();
cursorInWindow = host.Window.CursorInWindow.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
Children = new Drawable[]
{
isActiveBox = new Box
{
Colour = Color4.Black,
Width = 0.5f,
RelativeSizeAxes = Axes.Both,
},
cursorInWindowBox = new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
Width = 0.5f,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
};
isActive.BindValueChanged(active => isActiveBox.Colour = active.NewValue ? Color4.Green : Color4.Red, true);
cursorInWindow.BindValueChanged(active => cursorInWindowBox.Colour = active.NewValue ? Color4.Green : Color4.Red, true);
}
}
}
| mit | C# |
6ee4f6a4889dc07e1277604aed89f440df868725 | bump version | Fody/PropertyChanged | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.2.4")] | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.2.3")] | mit | C# |
0cf685a24ca53860d809cb7202aab134599d5b15 | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.79.*")]
| 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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.78.*")]
| mit | C# |
8aa29ec3441cf169bef02e83f213bff06ce6cc36 | Fix Transparent Default Button (#468) | Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms | Xamarin.Forms.Platform.WinRT/FormsButton.cs | Xamarin.Forms.Platform.WinRT/FormsButton.cs | using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
#if WINDOWS_UWP
using WContentPresenter = Windows.UI.Xaml.Controls.ContentPresenter;
namespace Xamarin.Forms.Platform.UWP
#else
namespace Xamarin.Forms.Platform.WinRT
#endif
{
public class FormsButton : Windows.UI.Xaml.Controls.Button
{
public static readonly DependencyProperty BorderRadiusProperty = DependencyProperty.Register(nameof(BorderRadius), typeof(int), typeof(FormsButton),
new PropertyMetadata(default(int), OnBorderRadiusChanged));
public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register(nameof(BackgroundColor), typeof(Brush), typeof(FormsButton),
new PropertyMetadata(default(Brush), OnBackgroundColorChanged));
#if WINDOWS_UWP
WContentPresenter _contentPresenter;
#else
Border _border;
#endif
public Brush BackgroundColor
{
get
{
return (Brush)GetValue(BackgroundColorProperty);
}
set
{
SetValue(BackgroundColorProperty, value);
}
}
public int BorderRadius
{
get
{
return (int)GetValue(BorderRadiusProperty);
}
set
{
SetValue(BorderRadiusProperty, value);
}
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
#if WINDOWS_UWP
_contentPresenter = GetTemplateChild("ContentPresenter") as WContentPresenter;
#else
_border = GetTemplateChild("Border") as Border;
#endif
UpdateBackgroundColor();
UpdateBorderRadius();
}
static void OnBackgroundColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((FormsButton)d).UpdateBackgroundColor();
}
static void OnBorderRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((FormsButton)d).UpdateBorderRadius();
}
void UpdateBackgroundColor()
{
if (BackgroundColor == null)
BackgroundColor = Background;
#if WINDOWS_UWP
if (_contentPresenter != null)
_contentPresenter.Background = BackgroundColor;
#else
if (_border != null)
_border.Background = BackgroundColor;
#endif
Background = Color.Transparent.ToBrush();
}
void UpdateBorderRadius()
{
#if WINDOWS_UWP
if (_contentPresenter != null)
_contentPresenter.CornerRadius = new CornerRadius(BorderRadius);
#else
if (_border != null)
_border.CornerRadius = new CornerRadius(BorderRadius);
#endif
}
}
} | using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
#if WINDOWS_UWP
using WContentPresenter = Windows.UI.Xaml.Controls.ContentPresenter;
namespace Xamarin.Forms.Platform.UWP
#else
namespace Xamarin.Forms.Platform.WinRT
#endif
{
public class FormsButton : Windows.UI.Xaml.Controls.Button
{
public static readonly DependencyProperty BorderRadiusProperty = DependencyProperty.Register(nameof(BorderRadius), typeof(int), typeof(FormsButton),
new PropertyMetadata(default(int), OnBorderRadiusChanged));
public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register(nameof(BackgroundColor), typeof(Brush), typeof(FormsButton),
new PropertyMetadata(default(Brush), OnBackgroundColorChanged));
#if WINDOWS_UWP
WContentPresenter _contentPresenter;
#else
Border _border;
#endif
public Brush BackgroundColor
{
get
{
return (Brush)GetValue(BackgroundColorProperty);
}
set
{
SetValue(BackgroundColorProperty, value);
}
}
public int BorderRadius
{
get
{
return (int)GetValue(BorderRadiusProperty);
}
set
{
SetValue(BorderRadiusProperty, value);
}
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
#if WINDOWS_UWP
_contentPresenter = GetTemplateChild("ContentPresenter") as WContentPresenter;
#else
_border = GetTemplateChild("Border") as Border;
#endif
UpdateBackgroundColor();
UpdateBorderRadius();
}
static void OnBackgroundColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((FormsButton)d).UpdateBackgroundColor();
}
static void OnBorderRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((FormsButton)d).UpdateBorderRadius();
}
void UpdateBackgroundColor()
{
Background = Color.Transparent.ToBrush();
#if WINDOWS_UWP
if (_contentPresenter != null)
_contentPresenter.Background = BackgroundColor;
#else
if (_border != null)
_border.Background = BackgroundColor;
#endif
}
void UpdateBorderRadius()
{
#if WINDOWS_UWP
if (_contentPresenter != null)
_contentPresenter.CornerRadius = new CornerRadius(BorderRadius);
#else
if (_border != null)
_border.CornerRadius = new CornerRadius(BorderRadius);
#endif
}
}
} | mit | C# |
83bb07d5a4282a7486d5ef426f53633db1f083ae | Fix parameter name (#1066) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.SignalR.Core/HubLifetimeManager.cs | src/Microsoft.AspNetCore.SignalR.Core/HubLifetimeManager.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.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.SignalR
{
public abstract class HubLifetimeManager<THub>
{
public abstract Task OnConnectedAsync(HubConnectionContext connection);
public abstract Task OnDisconnectedAsync(HubConnectionContext connection);
public abstract Task InvokeAllAsync(string methodName, object[] args);
public abstract Task InvokeAllExceptAsync(string methodName, object[] args, IReadOnlyList<string> excludedIds);
public abstract Task InvokeConnectionAsync(string connectionId, string methodName, object[] args);
public abstract Task InvokeGroupAsync(string groupName, string methodName, object[] args);
public abstract Task InvokeUserAsync(string userId, string methodName, object[] args);
public abstract Task AddGroupAsync(string connectionId, string groupName);
public abstract Task RemoveGroupAsync(string connectionId, string groupName);
}
}
| // 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.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.SignalR
{
public abstract class HubLifetimeManager<THub>
{
public abstract Task OnConnectedAsync(HubConnectionContext connection);
public abstract Task OnDisconnectedAsync(HubConnectionContext connection);
public abstract Task InvokeAllAsync(string methodName, object[] args);
public abstract Task InvokeAllExceptAsync(string methodName, object[] args, IReadOnlyList<string> excludedIds);
public abstract Task InvokeConnectionAsync(string connectionId, string methodName, object[] args);
public abstract Task InvokeGroupAsync(string groupName, string methodName, object[] args);
public abstract Task InvokeUserAsync(string userId, string methodName, object[] args);
public abstract Task AddGroupAsync(string connectionId, string groupName);
public abstract Task RemoveGroupAsync(string connnectionId, string groupName);
}
}
| apache-2.0 | C# |
9d082680272d132149b15b489c0903cf322afdb0 | fix bug for no match in sort of orderby extension | 2020IP/TwentyTwenty.BaseLine | src/TwentyTwenty.BaseLine/Extensions/QueryableExtensions.cs | src/TwentyTwenty.BaseLine/Extensions/QueryableExtensions.cs | using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using TwentyTwenty.BaseLine;
namespace System.Linq
{
public static class QuerableExtensions
{
public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> queryable, SortSpec sortSpec)
{
var prop = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.SingleOrDefault(p => p.Name.Equals(sortSpec.Member, StringComparison.OrdinalIgnoreCase));
if (prop == null)
{
throw new ArgumentException($"No property '{sortSpec.Member}' in '{typeof(TEntity).Name}'");
}
var arg = Expression.Parameter(typeof(TEntity));
var expr = Expression.Property(arg, prop);
var delegateType = typeof(Func<,>).MakeGenericType(typeof(TEntity), prop.PropertyType);
var lambda = Expression.Lambda(delegateType, expr, arg);
var methodName = sortSpec.SortDirection == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
var method = typeof(Queryable).GetMethods().Single(m => m.Name == methodName
&& m.IsGenericMethodDefinition
&& m.GetGenericArguments().Length == 2
&& m.GetParameters().Length == 2);
return (IOrderedQueryable<TEntity>)method
.MakeGenericMethod(typeof(TEntity), prop.PropertyType)
.Invoke(null, new object[] { queryable, lambda });
}
public static PagedList<TEntity> ToPagedList<TEntity>(this IQueryable<TEntity> queryable, int pageNumber,
int pageSize, SortSpec sortSpec = null)
{
if (sortSpec != null)
{
queryable = queryable.OrderBy(sortSpec);
}
return new PagedList<TEntity>(queryable, pageNumber, pageSize);
}
}
} | using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using TwentyTwenty.BaseLine;
namespace System.Linq
{
public static class QuerableExtensions
{
public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> queryable, SortSpec sortSpec)
{
var prop = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Single(p => p.Name.Equals(sortSpec.Member, StringComparison.OrdinalIgnoreCase));
if (prop == null)
{
throw new ArgumentException($"No property '{sortSpec.Member}' in '{typeof(TEntity).Name}'");
}
var arg = Expression.Parameter(typeof(TEntity));
var expr = Expression.Property(arg, prop);
var delegateType = typeof(Func<,>).MakeGenericType(typeof(TEntity), prop.PropertyType);
var lambda = Expression.Lambda(delegateType, expr, arg);
var methodName = sortSpec.SortDirection == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
var method = typeof(Queryable).GetMethods().Single(m => m.Name == methodName
&& m.IsGenericMethodDefinition
&& m.GetGenericArguments().Length == 2
&& m.GetParameters().Length == 2);
return (IOrderedQueryable<TEntity>)method
.MakeGenericMethod(typeof(TEntity), prop.PropertyType)
.Invoke(null, new object[] { queryable, lambda });
}
public static PagedList<TEntity> ToPagedList<TEntity>(this IQueryable<TEntity> queryable, int pageNumber,
int pageSize, SortSpec sortSpec = null)
{
if (sortSpec != null)
{
queryable = queryable.OrderBy(sortSpec);
}
return new PagedList<TEntity>(queryable, pageNumber, pageSize);
}
}
} | apache-2.0 | C# |
c6838597c849fe6c6cb8fb668c6c27ab90dd9e19 | Update Main class for compatibility Pre-Alpha 5. | ParkitectNexus/HelloMod | Main.cs | Main.cs | using UnityEngine;
namespace HelloMod
{
public class Main : IMod
{
private GameObject _go;
public void onEnabled()
{
_go = new GameObject();
_go.AddComponent<HelloBehaviour>();
}
public void onDisabled()
{
UnityEngine.Object.Destroy(_go);
}
public string Name
{
get { return "Hello Mod"; }
}
public string Description
{
get { return "Validates if mods are working on your PC"; }
}
}
}
| using UnityEngine;
namespace HelloMod
{
class Main : IMod
{
private GameObject _go;
public void onEnabled()
{
_go = new GameObject();
_go.AddComponent<HelloBehaviour>();
}
public void onDisabled()
{
UnityEngine.Object.Destroy(_go);
}
public string Name
{
get { return "Hello Mod"; }
}
public string Description
{
get { return "Validates if mods are working on your PC"; }
}
}
}
| mit | C# |
d3e4853611a588af196bea4c5ff67d2fef9c2aec | Revise tests for commands | y-iihoshi/ThScoreFileConverter,y-iihoshi/ThScoreFileConverter | ThScoreFileConverterTests/Commands/CloseWindowCommandTests.cs | ThScoreFileConverterTests/Commands/CloseWindowCommandTests.cs | using System;
using System.Windows;
using System.Windows.Input;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Commands;
using ThScoreFileConverterTests.Models;
namespace ThScoreFileConverterTests.Commands
{
[TestClass]
public class CloseWindowCommandTests
{
[TestMethod]
public void InstanceTest()
{
var instance = CloseWindowCommand.Instance;
Assert.IsTrue(instance is ICommand);
}
[TestMethod]
public void CanExecuteTest()
{
var instance = CloseWindowCommand.Instance;
var window = new Window();
Assert.IsTrue(instance.CanExecute(window));
}
[TestMethod]
public void CanExecuteTestNull()
{
var instance = CloseWindowCommand.Instance;
Assert.IsFalse(instance.CanExecute(null));
}
[TestMethod]
public void CanExecuteTestInvalid()
{
var instance = CloseWindowCommand.Instance;
Assert.IsFalse(instance.CanExecute(5));
}
[TestMethod]
public void ExecuteTest()
{
var instance = CloseWindowCommand.Instance;
var window = new Window();
var invoked = false;
void onClosed(object sender, EventArgs e) { invoked = true; }
window.Closed += onClosed;
instance.Execute(window);
Assert.IsTrue(invoked);
invoked = false;
window.Closed -= onClosed;
instance.Execute(window);
Assert.IsFalse(invoked);
}
[TestMethod]
public void ExecuteTestNull()
{
var instance = CloseWindowCommand.Instance;
instance.Execute(null);
}
[TestMethod]
public void ExecuteTestInvalid()
{
var instance = CloseWindowCommand.Instance;
instance.Execute(5);
}
[TestMethod]
public void CanExecuteChangedTest()
{
var instance = CloseWindowCommand.Instance;
instance.CanExecuteChanged += (sender, e) => Assert.Fail(TestUtils.Unreachable);
instance.Execute(null);
instance.Execute(new Window());
instance.Execute(5);
}
}
}
| using System;
using System.Windows;
using System.Windows.Input;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Commands;
using ThScoreFileConverterTests.Models;
namespace ThScoreFileConverterTests.Commands
{
[TestClass]
public class CloseWindowCommandTests
{
[TestMethod]
public void InstanceTest()
{
var instance = CloseWindowCommand.Instance;
Assert.IsTrue(instance is ICommand);
}
[TestMethod]
public void CanExecuteTest()
{
var instance = CloseWindowCommand.Instance;
var window = new Window();
Assert.IsTrue(instance.CanExecute(window));
}
[TestMethod]
public void CanExecuteTestNull()
{
var instance = CloseWindowCommand.Instance;
Assert.IsFalse(instance.CanExecute(null));
}
[TestMethod]
public void CanExecuteTestInvalid()
{
var instance = CloseWindowCommand.Instance;
Assert.IsFalse(instance.CanExecute(5));
}
[TestMethod]
public void ExecuteTest()
{
var instance = CloseWindowCommand.Instance;
instance.Execute(new Window());
}
[TestMethod]
public void ExecuteTestNull()
{
var instance = CloseWindowCommand.Instance;
instance.Execute(null);
}
[TestMethod]
public void ExecuteTestInvalid()
{
var instance = CloseWindowCommand.Instance;
instance.Execute(5);
}
[TestMethod]
public void CanExecuteChangedTest()
{
var instance = CloseWindowCommand.Instance;
instance.CanExecuteChanged += (sender, e) => Assert.Fail(TestUtils.Unreachable);
instance.Execute(null);
instance.Execute(new Window());
instance.Execute(5);
}
}
}
| bsd-2-clause | C# |
2c9df53c35f0c6cf53acf44b6c56e3ff400ab2e3 | Fix Sleep of the test program | badgio/XboxOneController,badgio/XboxOneController,badgio/XboxOneController | PadReaderTest/Program.cs | PadReaderTest/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XboxOnePadReader;
namespace PadReaderTest
{
class Program
{
static void Main(string[] args)
{
ControllerReader myController = ControllerReader.Instance;
int x = 0;
while (x < 5)
{
Thread.Sleep(1000);
++x;
}
myController.CloseController();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XboxOnePadReader;
namespace PadReaderTest
{
class Program
{
static void Main(string[] args)
{
ControllerReader myController = ControllerReader.Instance;
int x = 0;
while (x < 5)
{
Thread.Sleep(1);
++x;
}
myController.CloseController();
}
}
}
| apache-2.0 | C# |
52ed00c76cc1c586fc2fd37d90ae5644d2d9afe6 | Write Log message for test | rexph/UnityPractice | Project1/Assets/Test1.cs | Project1/Assets/Test1.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test1 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Condole.Log("This log is added by Suzuki");
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test1 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| mit | C# |
50538283ab60336fca1b9b3cc4a19c748ab65b57 | hide userId in editingPopUp | KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem | VotingSystem.Web/Areas/User/ViewModels/UserVotesViewModel.cs | VotingSystem.Web/Areas/User/ViewModels/UserVotesViewModel.cs | namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
public class UserVotesViewModel : IMapFrom<Vote>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public bool IsPublic { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[HiddenInput(DisplayValue = false)]
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Vote, UserVotesViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
} | namespace VotingSystem.Web.Areas.User.ViewModels
{
using System;
using System.Web.Mvc;
using VotingSystem.Models;
using VotingSystem.Web.Infrastructure.Mapping;
public class UserVotesViewModel : IMapFrom<Vote>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[HiddenInput(DisplayValue = false)]
public string Author { get; set; }
public bool IsPublic { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string UserId { get; set; }
public void CreateMappings(AutoMapper.IConfiguration configuration)
{
configuration.CreateMap<Vote, UserVotesViewModel>()
.ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName));
}
}
} | mit | C# |
814900a42f80aceac5eb2e21fea1ec63745bde35 | update assembly product name | telerik/JustMockLite | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | /*
JustMock Lite
Copyright © 2010-2015 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
#if LITE_EDITION
[assembly: AssemblyProduct("Progress® Telerik® JustMock Lite")]
#else
[assembly: AssemblyProduct("Progress® Telerik® JustMock")]
#endif
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCompany("Telerik AD")]
[assembly: AssemblyCopyright("Copyright © 2010-2015 Telerik AD")]
[assembly: AssemblyVersion("2013.3.1021.0")]
[assembly: AssemblyFileVersion("2013.3.1021.0")]
| /*
JustMock Lite
Copyright © 2010-2015 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
#if LITE_EDITION
[assembly: AssemblyProduct("Telerik JustMock Lite")]
#else
[assembly: AssemblyProduct("Telerik JustMock")]
#endif
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCompany("Telerik AD")]
[assembly: AssemblyCopyright("Copyright © 2010-2015 Telerik AD")]
[assembly: AssemblyVersion("2013.3.1021.0")]
[assembly: AssemblyFileVersion("2013.3.1021.0")]
| apache-2.0 | C# |
754aa13890690948c871cf0bc20238f99de61f86 | bump version | Fody/Virtuosity | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Virtuosity")]
[assembly: AssemblyProduct("Virtuosity")]
[assembly: AssemblyVersion("1.19.8")]
[assembly: AssemblyFileVersion("1.19.8")]
| using System.Reflection;
[assembly: AssemblyTitle("Virtuosity")]
[assembly: AssemblyProduct("Virtuosity")]
[assembly: AssemblyVersion("1.19.7")]
[assembly: AssemblyFileVersion("1.19.7")]
| mit | C# |
71bcaa0386aad9f69e9dc35287de898beb0b78b0 | Add comment | timokorkalainen/Unity-GeoJSONObject | Core/GeoJSONObject.cs | Core/GeoJSONObject.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GeoJSON {
public class GeoJSONObject {
public string type;
public GeoJSONObject(JSONObject jsonObject) {
type = jsonObject ["type"].str;
}
public GeoJSONObject() {
}
//Will always return a FeatureCollection...
static public FeatureCollection Deserialize(string encodedString) {
FeatureCollection collection;
JSONObject jsonObject = new JSONObject (encodedString);
if (jsonObject ["type"].str == "FeatureCollection") {
collection = new GeoJSON.FeatureCollection (jsonObject);
} else {
collection = new GeoJSON.FeatureCollection ();
collection.features.Add (new GeoJSON.FeatureObject (jsonObject));
}
return collection;
}
virtual public JSONObject Serialize () {
JSONObject rootObject = new JSONObject (JSONObject.Type.OBJECT);
rootObject.AddField ("type", type);
SerializeContent (rootObject);
return rootObject;
}
protected virtual void SerializeContent(JSONObject rootObject) {}
}
} | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GeoJSON {
public class GeoJSONObject {
public string type;
public GeoJSONObject(JSONObject jsonObject) {
type = jsonObject ["type"].str;
}
public GeoJSONObject() {
}
static public FeatureCollection Deserialize(string encodedString) {
FeatureCollection collection;
JSONObject jsonObject = new JSONObject (encodedString);
if (jsonObject ["type"].str == "FeatureCollection") {
collection = new GeoJSON.FeatureCollection (jsonObject);
} else {
collection = new GeoJSON.FeatureCollection ();
collection.features.Add (new GeoJSON.FeatureObject (jsonObject));
}
return collection;
}
virtual public JSONObject Serialize () {
JSONObject rootObject = new JSONObject (JSONObject.Type.OBJECT);
rootObject.AddField ("type", type);
SerializeContent (rootObject);
return rootObject;
}
protected virtual void SerializeContent(JSONObject rootObject) {}
}
} | mit | C# |
b2d1a154b0b5ed99201204b27ece7bc29e6f6693 | Fix FindByFieldSetStrategy | YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata,atata-framework/atata | src/Atata/ScopeSearch/Strategies/FindByFieldSetStrategy.cs | src/Atata/ScopeSearch/Strategies/FindByFieldSetStrategy.cs | using System.Text;
namespace Atata
{
public class FindByFieldSetStrategy : XPathComponentScopeLocateStrategy
{
public FindByFieldSetStrategy()
: base(useIndex: IndexUsage.None)
{
}
protected override void BuildXPath(StringBuilder builder, ComponentScopeLocateOptions options)
{
string legendCondition = options.GetTermsXPathCondition();
builder.Insert(0, "fieldset[legend[{0}]]{1}/descendant-or-self::".FormatWith(legendCondition, options.GetPositionWrappedXPathConditionOrNull()));
}
}
}
| using System.Text;
namespace Atata
{
public class FindByFieldSetStrategy : XPathComponentScopeLocateStrategy
{
public FindByFieldSetStrategy()
: base(useIndex: IndexUsage.None)
{
}
protected override void BuildXPath(StringBuilder builder, ComponentScopeLocateOptions options)
{
string legendCondition = options.GetTermsXPathCondition();
builder.Insert(0, "fieldset[legend[{0}]]{1}//".FormatWith(legendCondition, options.GetPositionWrappedXPathConditionOrNull()));
}
}
}
| apache-2.0 | C# |
1e1dc9153dc7738fd8a7b98662964e8ee3ff1965 | Bump version to 3.0 | CodefoundryDE/LegacyWrapper,CodefoundryDE/LegacyWrapper | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyDescription("LegacyWrapper uses a x86 wrapper to call legacy dlls from a 64 bit process.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("codefoundry.de")]
[assembly: AssemblyCopyright("Copyright (c) 2017, Franz Wimmer. (MIT License)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyDescription("LegacyWrapper uses a x86 wrapper to call legacy dlls from a 64 bit process.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("codefoundry.de")]
[assembly: AssemblyCopyright("Copyright (c) 2017, Franz Wimmer. (MIT License)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("2.0.1.0")]
[assembly: AssemblyFileVersion("2.0.1.0")]
| mit | C# |
01bc71acd2a24c3fa5993aab6487f4fdee7d7062 | Improve ability to parse xmldoc of `SkinnableTargetWrapper` | NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu | osu.Game/Skinning/SkinnableTargetWrapper.cs | osu.Game/Skinning/SkinnableTargetWrapper.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A container which groups the elements of a <see cref="SkinnableTargetContainer"/> into a single object.
/// Optionally also applies a default layout to the elements.
/// </summary>
[Serializable]
public class SkinnableTargetWrapper : Container, ISkinnableDrawable
{
public bool IsEditable => false;
private readonly Action<Container> applyDefaults;
/// <summary>
/// Construct a wrapper with defaults that should be applied once.
/// </summary>
/// <param name="applyDefaults">A function to apply the default layout.</param>
public SkinnableTargetWrapper(Action<Container> applyDefaults)
: this()
{
this.applyDefaults = applyDefaults;
}
[JsonConstructor]
public SkinnableTargetWrapper()
{
RelativeSizeAxes = Axes.Both;
}
protected override void LoadComplete()
{
base.LoadComplete();
// schedule is required to allow children to run their LoadComplete and take on their correct sizes.
ScheduleAfterChildren(() => applyDefaults?.Invoke(this));
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A container which is serialised and can encapsulate multiple skinnable elements into a single return type (for consumption via <see cref="ISkin.GetDrawableComponent"/>.
/// Will also optionally apply default cross-element layout dependencies when initialised from a non-deserialised source.
/// </summary>
[Serializable]
public class SkinnableTargetWrapper : Container, ISkinnableDrawable
{
public bool IsEditable => false;
private readonly Action<Container> applyDefaults;
/// <summary>
/// Construct a wrapper with defaults that should be applied once.
/// </summary>
/// <param name="applyDefaults">A function to apply the default layout.</param>
public SkinnableTargetWrapper(Action<Container> applyDefaults)
: this()
{
this.applyDefaults = applyDefaults;
}
[JsonConstructor]
public SkinnableTargetWrapper()
{
RelativeSizeAxes = Axes.Both;
}
protected override void LoadComplete()
{
base.LoadComplete();
// schedule is required to allow children to run their LoadComplete and take on their correct sizes.
ScheduleAfterChildren(() => applyDefaults?.Invoke(this));
}
}
}
| mit | C# |
12531d4976721ba0b04d2bbd7dba5eea25dff311 | Rename route. | beta-tank/TicTacToe,beta-tank/TicTacToe,beta-tank/TicTacToe | TicTacToe/App_Start/RouteConfig.cs | TicTacToe/App_Start/RouteConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace TicTacToe
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Game", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace TicTacToe
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| mit | C# |
32fe1f196e9bc955194c176ed49f74909a081ed0 | Remove unused line of code | Xeeynamo/KingdomHearts | OpenKh.Game/Global.cs | OpenKh.Game/Global.cs | namespace OpenKh.Game
{
public class Global
{
public const int ResolutionWidth = 512;
public const int ResolutionHeight = 416;
public const int ResolutionRemixWidth = 684;
public const float ResolutionReMixRatio = 0.925f;
}
}
| namespace OpenKh.Game
{
public class Global
{
public const int ResolutionWidth = 512;
public const int ResolutionHeight = 416;
public const int ResolutionRemixWidth = 684;
public const float ResolutionReMixRatio = 0.925f;
public const float ResolutionBoostRatio = 2;
}
}
| mit | C# |
d8cffda73a9155b35d81bde096464e222ccf1059 | fix ws | Saltarelle/SaltarelleNodeJS | NodeJS/OSModule/OS.cs | NodeJS/OSModule/OS.cs | using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace NodeJS.OSModule {
[Imported]
[GlobalMethods]
[ModuleName("os")]
public static class OS {
public static string TmpDir { [ScriptName("tmpDir")] get { return null; } }
public static string Hostname { [ScriptName("hostname")] get { return null; } }
public static string Type { [ScriptName("type")] get { return null; } }
public static string Platform { [ScriptName("platform")] get { return null; } }
public static string Arch { [ScriptName("arch")] get { return null; } }
public static string Release { [ScriptName("release")] get { return null; } }
public static double Uptime { [ScriptName("uptime")] get { return 0; } }
public static double[] LoadAvg { [ScriptName("loadavg")] get { return null; } }
public static long TotalMem { [ScriptName("totalmem")] get { return 0; } }
public static long FreeMem { [ScriptName("freemem")] get { return 0; } }
public static CpuInfo[] Cpus { [ScriptName("cpus")] get { return null; } }
public static JsDictionary<string, NetworkInterfaceInfo[]> NetworkInterfaces { [ScriptName("networkInterfaces")] get { return null; } }
[IntrinsicProperty]
public static string Eol { get { return null; } }
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace NodeJS.OSModule {
[Imported]
[GlobalMethods]
[ModuleName("os")]
public static class OS {
public static string TmpDir { [ScriptName("tmpDir")] get { return null; } }
public static string Hostname { [ScriptName("hostname")] get { return null; } }
public static string Type { [ScriptName("type")] get { return null; } }
public static string Platform { [ScriptName("platform")] get { return null; } }
public static string Arch { [ScriptName("arch")] get { return null; } }
public static string Release { [ScriptName("release")] get { return null; } }
public static double Uptime { [ScriptName("uptime")] get { return 0; } }
public static double[] LoadAvg { [ScriptName("loadavg")] get { return null; } }
public static long TotalMem { [ScriptName("totalmem")] get { return 0; } }
public static long FreeMem { [ScriptName("freemem")] get { return 0; } }
public static CpuInfo[] Cpus { [ScriptName("cpus")] get { return null; } }
public static JsDictionary<string, NetworkInterfaceInfo[]> NetworkInterfaces { [ScriptName("networkInterfaces")] get { return null; } }
[IntrinsicProperty]
public static string Eol { get { return null; } }
}
}
| apache-2.0 | C# |
2cfcaf1176e34eaccc0bb019e91c3918779938c2 | Fix line endings... | smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,default0/osu-framework,paparony03/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,naoey/osu-framework,naoey/osu-framework,ppy/osu-framework,default0/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,paparony03/osu-framework,ZLima12/osu-framework,Tom94/osu-framework | osu.Framework/Graphics/Transforms/TransformEdgeEffectColour.cs | osu.Framework/Graphics/Transforms/TransformEdgeEffectColour.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.MathUtils;
namespace osu.Framework.Graphics.Transforms
{
public class TransformEdgeEffectColour : Transform<Color4>
{
/// <summary>
/// Current value of the transformed colour in linear colour space.
/// </summary>
public override Color4 CurrentValue
{
get
{
double time = Time?.Current ?? 0;
if (time < StartTime) return StartValue;
if (time >= EndTime) return EndValue;
return Interpolation.ValueAt(time, StartValue, EndValue, StartTime, EndTime, Easing);
}
}
public override void Apply(Drawable d)
{
base.Apply(d);
Container c = (Container)d;
EdgeEffect e = c.EdgeEffect;
e.Colour = CurrentValue;
c.EdgeEffect = e;
}
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.MathUtils;
namespace osu.Framework.Graphics.Transforms
{
public class TransformEdgeEffectColour : Transform<Color4>
{
/// <summary>
/// Current value of the transformed colour in linear colour space.
/// </summary>
public override Color4 CurrentValue
{
get
{
double time = Time?.Current ?? 0;
if (time < StartTime) return StartValue;
if (time >= EndTime) return EndValue;
return Interpolation.ValueAt(time, StartValue, EndValue, StartTime, EndTime, Easing);
}
}
public override void Apply(Drawable d)
{
base.Apply(d);
Container c = (Container)d;
EdgeEffect e = c.EdgeEffect;
e.Colour = CurrentValue;
c.EdgeEffect = e;
}
}
} | mit | C# |
eadd7ce9138403f189d9ad06871dcce3c1d2d93f | Update catch dfificulty test | johnneijzen/osu,DrabWeb/osu,DrabWeb/osu,2yangk23/osu,peppy/osu-new,ppy/osu,ZLima12/osu,2yangk23/osu,smoogipooo/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,DrabWeb/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu | osu.Game.Rulesets.Catch.Tests/CatchDifficultyCalculatorTest.cs | osu.Game.Rulesets.Catch.Tests/CatchDifficultyCalculatorTest.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Difficulty;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Catch.Tests
{
public class CatchDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Catch";
[TestCase(4.2058561036909863d, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new CatchDifficultyCalculator(new CatchRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new CatchRuleset();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Difficulty;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Catch.Tests
{
public class CatchDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Catch";
[TestCase(4.2038001515546597d, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new CatchDifficultyCalculator(new CatchRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new CatchRuleset();
}
}
| mit | C# |
c1a4f2e6afd823b9e36c73f76f16ea4445da0a88 | Update expected SR in test | NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,ppy/osu,smoogipoo/osu | osu.Game.Rulesets.Taiko.Tests/TaikoDifficultyCalculatorTest.cs | osu.Game.Rulesets.Taiko.Tests/TaikoDifficultyCalculatorTest.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Taiko.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko";
[TestCase(2.2905937546434592d, "diffcalc-test")]
[TestCase(2.2905937546434592d, "diffcalc-test-strong")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Taiko.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko";
[TestCase(2.9811338051242915d, "diffcalc-test")]
[TestCase(2.9811338051242915d, "diffcalc-test-strong")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
| mit | C# |
d8ee231f650f9fbd96a6c3c0aa6bf689210497b7 | test that we truncate long messages | Cayan-LLC/syslog4net,jbeats/syslog4net,akramsaleh/syslog4net,merchantwarehouse/syslog4net | src/test/unit/syslog4net.Tests/Layout/SyslogLayoutTests.cs | src/test/unit/syslog4net.Tests/Layout/SyslogLayoutTests.cs | using System;
using System.Text;
using System.IO;
using syslog4net.Layout;
using log4net.Core;
using log4net.Util;
using log4net.Filter;
using log4net.Repository;
using NUnit.Framework;
using NSubstitute;
namespace syslog4net.Tests.Layout
{
[TestFixture]
class SyslogLayoutTests
{
[Test]
public void ActivateOptionsTestNoStructuredDataPrefixSet()
{
SyslogLayout layout = new SyslogLayout();
Assert.That(
() => layout.ActivateOptions(),
Throws.Exception
.TypeOf<ArgumentNullException>()
.With.Property("ParamName").EqualTo("StructuredDataPrefix")
);
}
[Test]
public void TestFormat()
{
SyslogLayout layout = new SyslogLayout();
layout.StructuredDataPrefix = "TEST@12345";
layout.ActivateOptions();
var exception = new ArgumentNullException();
ILoggerRepository logRepository = Substitute.For<ILoggerRepository>();
var evt = new LoggingEvent(typeof(SyslogLayoutTests), logRepository, "test logger", Level.Debug, "test message", exception);
StringWriter writer = new StringWriter();
layout.Format(writer, evt);
string result = writer.ToString();
// it's hard to test the whole message, because it depends on your machine name, process id, time & date, etc.
// just test the message's invariant portions
Assert.IsTrue(result.StartsWith("<135>1 "));
Assert.IsTrue(result.Contains("[TEST@12345 EventSeverity=\"DEBUG\" ExceptionType=\"System.ArgumentNullException\" ExceptionMessage=\"Value cannot be null.\"]"));
Assert.IsTrue(result.EndsWith("test message" + Environment.NewLine));
}
[Test]
public void TestThatWeTruncateLongMessages()
{
SyslogLayout layout = new SyslogLayout();
layout.StructuredDataPrefix = "TEST@12345";
layout.ActivateOptions();
StringBuilder longMessage = new StringBuilder();
for (int i = 0; i < 2048; i++)
{
longMessage.Append("test message");
}
var exception = new ArgumentNullException();
ILoggerRepository logRepository = Substitute.For<ILoggerRepository>();
var evt = new LoggingEvent(typeof(SyslogLayoutTests), logRepository, "test logger", Level.Debug, longMessage.ToString(), exception);
StringWriter writer = new StringWriter();
layout.Format(writer, evt);
string result = writer.ToString();
Assert.AreEqual(2048, result.Length);
}
}
}
| using System;
using System.IO;
using syslog4net.Layout;
using log4net.Core;
using log4net.Util;
using log4net.Filter;
using log4net.Repository;
using NUnit.Framework;
using NSubstitute;
namespace syslog4net.Tests.Layout
{
[TestFixture]
class SyslogLayoutTests
{
[Test]
public void ActivateOptionsTestNoStructuredDataPrefixSet()
{
SyslogLayout layout = new SyslogLayout();
Assert.That(
() => layout.ActivateOptions(),
Throws.Exception
.TypeOf<ArgumentNullException>()
.With.Property("ParamName").EqualTo("StructuredDataPrefix")
);
}
[Test]
public void TestFormat()
{
SyslogLayout layout = new SyslogLayout();
layout.StructuredDataPrefix = "TEST@12345";
layout.ActivateOptions();
var exception = new ArgumentNullException();
ILoggerRepository logRepository = Substitute.For<ILoggerRepository>();
var evt = new LoggingEvent(typeof(SyslogLayoutTests), logRepository, "test logger", Level.Debug, "test message", exception);
StringWriter writer = new StringWriter();
layout.Format(writer, evt);
string result = writer.ToString();
// it's hard to test the whole message, because it depends on your machine name, process id, time & date, etc.
// just test the message's invariant portions
Assert.IsTrue(result.StartsWith("<135>1 "));
Assert.IsTrue(result.Contains("[TEST@12345 EventSeverity=\"DEBUG\" ExceptionType=\"System.ArgumentNullException\" ExceptionMessage=\"Value cannot be null.\"]"));
Assert.IsTrue(result.EndsWith("test message" + Environment.NewLine));
}
}
}
| apache-2.0 | C# |
7489f455cc2c1336f24560c08cf0423323a0e5b2 | Bump version to 2.0.1 | mj1856/TimeZoneNames | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © Matt Johnson")]
[assembly: AssemblyVersion("2.0.1.*")]
[assembly: AssemblyInformationalVersion("2.0.1")]
| using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © Matt Johnson")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyInformationalVersion("2.0.0")]
| mit | C# |
86a61c088a094d40715fdf75985728e825f9a00a | Add ReplaceKnownWords | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Utilities/String.Replace.cs | source/Nuke.Common/Utilities/String.Replace.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
[PublicAPI]
[DebuggerNonUserCode]
[DebuggerStepThrough]
public static partial class StringExtensions
{
[Pure]
public static string ReplaceRegex(
this string str,
[RegexPattern] string pattern,
MatchEvaluator matchEvaluator,
RegexOptions options = RegexOptions.None)
{
return Regex.Replace(str, pattern, matchEvaluator, options);
}
private static readonly Regex s_unicodeRegex = new Regex(@"\\u(?<Value>[a-zA-Z0-9]{4})", RegexOptions.Compiled);
[Pure]
public static string ReplaceUnicode(this string str)
{
return s_unicodeRegex.Replace(str, m => ((char) int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString());
}
[Pure]
public static string ReplaceKnownWords(this string str)
{
return Constants.KnownWords.Aggregate(str, (s, r) => s.ReplaceRegex(r, _ => r, RegexOptions.IgnoreCase));
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
[PublicAPI]
[DebuggerNonUserCode]
[DebuggerStepThrough]
public static partial class StringExtensions
{
[Pure]
public static string ReplaceRegex(
this string str,
[RegexPattern] string pattern,
MatchEvaluator matchEvaluator,
RegexOptions options = RegexOptions.None)
{
return Regex.Replace(str, pattern, matchEvaluator, options);
}
private static readonly Regex s_unicodeRegex = new Regex(@"\\u(?<Value>[a-zA-Z0-9]{4})", RegexOptions.Compiled);
[Pure]
public static string ReplaceUnicode(this string str)
{
return s_unicodeRegex.Replace(str, m => ((char) int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString());
}
}
}
| mit | C# |
deaf97f3827e888892d9b81cf56f835322a2ee46 | Set DataContract Attribute for NotificationObject class | yas-mnkornym/TaihaToolkit | source/TaihaToolkit.Core/NotificationObject.cs | source/TaihaToolkit.Core/NotificationObject.cs | using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace Studiotaiha.Toolkit
{
[DataContract]
public class NotificationObject : Dispatchable, INotifyPropertyChanged
{
public NotificationObject(IDispatcher dispatcher = null)
: base(dispatcher)
{ }
/// <summary>
/// Sets the value to the variable and trigger property changed event.
/// </summary>
/// <typeparam name="T">Type of the value</typeparam>
/// <param name="dst">Target variable to set the value</param>
/// <param name="value">Value to be set</param>
/// <param name="actBeforeChange">Action object that will be invoked before the value is changed</param>
/// <param name="actAfterChange">Action object that will be invoked before the value is changed</param>
/// <param name="propertyName">Name of the property</param>
/// <returns>True if the value is changed.</returns>
protected virtual bool SetValue<T>(
ref T dst,
T value,
Action<T> actBeforeChange = null,
Action<T> actAfterChange = null,
[CallerMemberName]string propertyName = null)
{
var isChanged = dst == null
? value != null
: !dst.Equals(value);
if (isChanged) {
actBeforeChange?.Invoke(dst);
dst = value;
actAfterChange?.Invoke(dst);
RaisePropertyChanged(propertyName);
return true;
}
return false;
}
/// <summary>
/// Notify that a property value is changed.
/// </summary>
/// <param name="propertyName"></param>
protected virtual void RaisePropertyChanged([CallerMemberName]string propertyName = null)
{
if (PropertyChanged != null) {
Dispatch(() => {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
});
}
}
/// <summary>
/// -Gets a member name from an exception syntax.
/// </summary>
/// <typeparam name="MemberType">メンバの型</typeparam>
/// <param name="expression">式</param>
/// <returns>メンバ名</returns>
public string GetMemberName<MemberType>(Expression<Func<MemberType>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
namespace Studiotaiha.Toolkit
{
public class NotificationObject : Dispatchable, INotifyPropertyChanged
{
public NotificationObject(IDispatcher dispatcher = null)
: base(dispatcher)
{ }
/// <summary>
/// Sets the value to the variable and trigger property changed event.
/// </summary>
/// <typeparam name="T">Type of the value</typeparam>
/// <param name="dst">Target variable to set the value</param>
/// <param name="value">Value to be set</param>
/// <param name="actBeforeChange">Action object that will be invoked before the value is changed</param>
/// <param name="actAfterChange">Action object that will be invoked before the value is changed</param>
/// <param name="propertyName">Name of the property</param>
/// <returns>True if the value is changed.</returns>
protected virtual bool SetValue<T>(
ref T dst,
T value,
Action<T> actBeforeChange = null,
Action<T> actAfterChange = null,
[CallerMemberName]string propertyName = null)
{
var isChanged = dst == null
? value != null
: !dst.Equals(value);
if (isChanged) {
actBeforeChange?.Invoke(dst);
dst = value;
actAfterChange?.Invoke(dst);
RaisePropertyChanged(propertyName);
return true;
}
return false;
}
/// <summary>
/// Notify that a property value is changed.
/// </summary>
/// <param name="propertyName"></param>
protected virtual void RaisePropertyChanged([CallerMemberName]string propertyName = null)
{
if (PropertyChanged != null) {
Dispatch(() => {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
});
}
}
/// <summary>
/// -Gets a member name from an exception syntax.
/// </summary>
/// <typeparam name="MemberType">メンバの型</typeparam>
/// <param name="expression">式</param>
/// <returns>メンバ名</returns>
public string GetMemberName<MemberType>(Expression<Func<MemberType>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| mit | C# |
8a3a5c972f9b1fb1b7a08f66ade1d560b9338c1d | fix SLuaSetting some codes require using UnityEditor on player. | Roland0511/slua,haolly/slua_source_note,mr-kelly/slua,yaukeywang/slua,jiangzhhhh/slua,haolly/slua_source_note,pangweiwei/slua,pangweiwei/slua,Roland0511/slua,luzexi/slua-3rd,shrimpz/slua,pangweiwei/slua,shrimpz/slua,pangweiwei/slua,Roland0511/slua,luzexi/slua-3rd-lib,yaukeywang/slua,soulgame/slua,luzexi/slua-3rd,yaukeywang/slua,luzexi/slua-3rd-lib,luzexi/slua-3rd-lib,mr-kelly/slua,mr-kelly/slua,luzexi/slua-3rd,mr-kelly/slua,yaukeywang/slua,luzexi/slua-3rd,yaukeywang/slua,soulgame/slua,luzexi/slua-3rd-lib,jiangzhhhh/slua,haolly/slua_source_note,jiangzhhhh/slua,haolly/slua_source_note,haolly/slua_source_note,luzexi/slua-3rd,haolly/slua_source_note,luzexi/slua-3rd-lib,soulgame/slua,Roland0511/slua,soulgame/slua,luzexi/slua-3rd-lib,jiangzhhhh/slua,jiangzhhhh/slua,soulgame/slua,jiangzhhhh/slua,soulgame/slua,pangweiwei/slua,Roland0511/slua,Roland0511/slua,mr-kelly/slua,luzexi/slua-3rd,mr-kelly/slua,yaukeywang/slua | Assets/Plugins/Slua_Managed/SLuaSetting.cs | Assets/Plugins/Slua_Managed/SLuaSetting.cs | // The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei [email protected]
//
// 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 UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace SLua{
public enum EOL{
Native,
CRLF,
CR,
LF,
}
public class SLuaSetting : ScriptableObject {
public EOL eol = EOL.Native;
public bool exportExtensionMethod = true;
public string UnityEngineGeneratePath = "Assets/Slua/LuaObject/";
public int debugPort=10240;
public string debugIP="0.0.0.0";
private static SLuaSetting _instance;
public static SLuaSetting Instance{
get{
if(_instance == null){
string path = "Assets/Slua/setting.asset";
_instance = Resources.Load<SLuaSetting>(path);
#if UNITY_EDITOR
if(_instance == null){
_instance = SLuaSetting.CreateInstance<SLuaSetting>();
AssetDatabase.CreateAsset(_instance,path);
}
#endif
}
return _instance;
}
}
#if UNITY_EDITOR
[MenuItem("SLua/Setting")]
public static void Open(){
Selection.activeObject = Instance;
}
#endif
}
}
| // The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei [email protected]
//
// 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 UnityEngine;
using System.Collections;
using UnityEditor;
namespace SLua{
public enum EOL{
Native,
CRLF,
CR,
LF,
}
public class SLuaSetting : ScriptableObject {
public EOL eol = EOL.Native;
public bool exportExtensionMethod = true;
public string UnityEngineGeneratePath = "Assets/Slua/LuaObject/";
public int debugPort=10240;
public string debugIP="0.0.0.0";
private static SLuaSetting _instance;
public static SLuaSetting Instance{
get{
if(_instance == null){
string path = "Assets/Slua/setting.asset";
#if UNITY_5
_instance = AssetDatabase.LoadAssetAtPath<SLuaSetting>(path);
#else
_instance = (SLuaSetting)AssetDatabase.LoadAssetAtPath(path,typeof(SLuaSetting));
#endif
if(_instance == null){
_instance = SLuaSetting.CreateInstance<SLuaSetting>();
AssetDatabase.CreateAsset(_instance,path);
}
}
return _instance;
}
}
#if UNITY_EDITOR
[MenuItem("SLua/Setting")]
public static void Open(){
Selection.activeObject = Instance;
}
#endif
}
}
| mit | C# |
d092dad7d61ae6f8325d9702ae0a3b9cb0bb8202 | Add the missing Bind() override | ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework | osu.Framework/Graphics/OpenGL/Buffers/TriangleVertexBuffer.cs | osu.Framework/Graphics/OpenGL/Buffers/TriangleVertexBuffer.cs | using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.OpenGL.Vertices;
using osuTK.Graphics.ES30;
using System;
namespace osu.Framework.Graphics.OpenGL.Buffers
{
internal static class TriangleIndexData
{
static TriangleIndexData()
{
GL.GenBuffers(1, out EBO_ID);
}
public static readonly int EBO_ID;
public static int MaxAmountIndices;
}
public class TriangleVertexBuffer<T> : VertexBuffer<T>
where T : struct, IEquatable<T>, IVertex
{
private readonly int amountTriangles;
internal TriangleVertexBuffer(int amountTriangles, BufferUsageHint usage)
: base(amountTriangles * TextureGLSingle.VERTICES_PER_TRIANGLE, usage)
{
this.amountTriangles = amountTriangles;
}
protected override void Initialise()
{
base.Initialise();
int amountIndices = amountTriangles * 6;
if (amountIndices > TriangleIndexData.MaxAmountIndices)
{
ushort[] indices = new ushort[amountIndices];
for (ushort i = 0, j = 0; j < amountIndices; i += TextureGLSingle.VERTICES_PER_TRIANGLE, j += 6)
{
indices[j] = i;
indices[j + 1] = (ushort)(i + 1);
indices[j + 2] = (ushort)(i + 2);
indices[j + 3] = i;
indices[j + 4] = (ushort)(i + 2);
indices[j + 5] = (ushort)(i + 3);
}
}
}
public override void Bind(bool forRendering)
{
base.Bind(forRendering);
if (forRendering)
GLWrapper.BindBuffer(BufferTarget.ElementArrayBuffer, TriangleIndexData.EBO_ID);
}
protected override int ToElements(int vertices) => 3 * vertices / 2;
protected override int ToElementIndex(int vertexIndex) => 3 * vertexIndex / 2;
protected override PrimitiveType Type => PrimitiveType.Triangles;
}
}
| using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.OpenGL.Vertices;
using osuTK.Graphics.ES30;
using System;
namespace osu.Framework.Graphics.OpenGL.Buffers
{
internal static class TriangleIndexData
{
static TriangleIndexData()
{
GL.GenBuffers(1, out EBO_ID);
}
public static readonly int EBO_ID;
public static int MaxAmountIndices;
}
public class TriangleVertexBuffer<T> : VertexBuffer<T>
where T : struct, IEquatable<T>, IVertex
{
private readonly int amountTriangles;
internal TriangleVertexBuffer(int amountTriangles, BufferUsageHint usage)
: base(amountTriangles * TextureGLSingle.VERTICES_PER_TRIANGLE, usage)
{
this.amountTriangles = amountTriangles;
}
protected override void Initialise()
{
base.Initialise();
int amountIndices = amountTriangles * 6;
if (amountIndices > TriangleIndexData.MaxAmountIndices)
{
ushort[] indices = new ushort[amountIndices];
for (ushort i = 0, j = 0; j < amountIndices; i += TextureGLSingle.VERTICES_PER_TRIANGLE, j += 6)
{
indices[j] = i;
indices[j + 1] = (ushort)(i + 1);
indices[j + 2] = (ushort)(i + 2);
indices[j + 3] = i;
indices[j + 4] = (ushort)(i + 2);
indices[j + 5] = (ushort)(i + 3);
}
}
}
protected override int ToElements(int vertices) => 3 * vertices / 2;
protected override int ToElementIndex(int vertexIndex) => 3 * vertexIndex / 2;
protected override PrimitiveType Type => PrimitiveType.Triangles;
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.