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 |
---|---|---|---|---|---|---|---|---|
bd3c3d50274106ddb9fc8a05112f7dd397295d30
|
update version info: v1.0.4 -> v1.0.5
|
Treer/ip4
|
src/Properties/AssemblyInfo.cs
|
src/Properties/AssemblyInfo.cs
|
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2015 — 2021 by Primoz Licen, Glenn Fisher")]
[assembly: AssemblyDescription("Lists all the IPs")]
[assembly: AssemblyFileVersion("1.0.0.5")]
[assembly: AssemblyVersion("1.0.0.5")]
[assembly: AssemblyProduct("ip4")]
[assembly: AssemblyTitle("ip4")]
[assembly: AssemblyTrademark("")]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: ComVisible(false)]
[assembly: Guid("9146ccd0-954f-43c8-8e86-14ed72982b35")]
|
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2015 — 2019 by Primoz Licen, Glenn Fisher")]
[assembly: AssemblyDescription("Lists all the IPs")]
[assembly: AssemblyFileVersion("1.0.0.4")]
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyProduct("ip4")]
[assembly: AssemblyTitle("ip4")]
[assembly: AssemblyTrademark("")]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: ComVisible(false)]
[assembly: Guid("9146ccd0-954f-43c8-8e86-14ed72982b35")]
|
mit
|
C#
|
5bd1b6712ed138b3e207e91d941594d63f2ae397
|
Implement Any in terms of All.
|
iainholder/edulinq,jskeet/edulinq,zhangz/edulinq,jskeet/edulinq,iainholder/edulinq,zhangz/edulinq,pyaria/edulinq,jskeet/edulinq,pyaria/edulinq
|
src/Edulinq/Any.cs
|
src/Edulinq/Any.cs
|
#region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
#if IMPLEMENT_ANY_USING_ALL
public static bool Any<TSource>(
this IEnumerable<TSource> source)
{
return source.Any(x => true);
}
public static bool Any<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
return !source.All(x => !predicate(x));
}
#else
public static bool Any<TSource>(
this IEnumerable<TSource> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
using (IEnumerator<TSource> iterator = source.GetEnumerator())
{
return iterator.MoveNext();
}
}
public static bool Any<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
foreach (TSource item in source)
{
if (predicate(item))
{
return true;
}
}
return false;
}
#endif
}
}
|
#region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
public static bool Any<TSource>(
this IEnumerable<TSource> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
using (IEnumerator<TSource> iterator = source.GetEnumerator())
{
return iterator.MoveNext();
}
}
public static bool Any<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
foreach (TSource item in source)
{
if (predicate(item))
{
return true;
}
}
return false;
}
}
}
|
apache-2.0
|
C#
|
f922983e1193727d34e81d0db7c08fa28173caf7
|
Update MagnetToggleKeyBehaviour.cs
|
maritaria/terratech-mod,Nuterra/Nuterra,Exund/nuterra
|
src/Nuterra/Maritaria/MagnetToggleKeyBehaviour.cs
|
src/Nuterra/Maritaria/MagnetToggleKeyBehaviour.cs
|
using System;
using UnityEngine;
namespace Maritaria
{
public class MagnetToggleKeyBehaviour : MonoBehaviour
{
private GUIContent _content;
private GUIStyle _style;
public static readonly string DisplayFormat = "<color=white><b>Magnets: </b>{0}</color>";
public static readonly string OfflineStatus = "<color=#ff2828>OFFLINE</color>";
public static readonly string OnlineStatus = "<color=#28ff28>ONLINE</color>";
public void Update()
{
if (Input.GetKeyDown(MaritariaMod.Instance.Config.MagnetToggleKey))
{
Modules.Magnet.DisabledForPlayerControlledTank = !Modules.Magnet.DisabledForPlayerControlledTank;
}
}
public MagnetToggleKeyBehaviour()
{
_style = new GUIStyle();
_style.richText=(true);
_style.alignment=(TextAnchor)(4);
_content = new GUIContent();
}
public void OnGUI()
{
if (Singleton.playerTank && !(Singleton.playerTank.blockman.IterateBlockComponents<ModuleItemHolderMagnet>().FirstOrDefault() == null) && !Singleton.Manager<ManPauseGame>.inst.IsPaused)
{
//No tank or no magnet blocks
return;
}
if (Modules.Magnet.DisabledForPlayerControlledTank)
{
_content.text=(string.Format(MagnetToggleKeyBehaviour.DisplayFormat, MagnetToggleKeyBehaviour.OfflineStatus));
}
else
{
_content.text=(string.Format(MagnetToggleKeyBehaviour.DisplayFormat, MagnetToggleKeyBehaviour.OnlineStatus));
}
_style.fontSize=(Screen.height / 60);
Vector2 vector=new Vector2((float)Screen.width * 0.5f, (float)Screen.height * 0.95f);
Vector2 vector2 = _style.CalcSize(_content);
vector.y -= vector2.y * 0.5f;
vector.x -= vector2.x * 0.5f;
GUI.Label(new Rect(vector, vector2), _content, _style);
}
}
}
|
using System;
using UnityEngine;
namespace Maritaria
{
public class MagnetToggleKeyBehaviour : MonoBehaviour
{
private GUIContent _content;
private GUIStyle _style;
public static readonly string DisplayFormat = "<color=white><b>Magnets: </b>{0}</color>";
public static readonly string OfflineStatus = "<color=#ff2828>OFFLINE</color>";
public static readonly string OnlineStatus = "<color=#28ff28>ONLINE</color>";
public void Update()
{
if (Input.GetKeyDown(MaritariaMod.Instance.Config.MagnetToggleKey))
{
Modules.Magnet.DisabledForPlayerControlledTank = !Modules.Magnet.DisabledForPlayerControlledTank;
}
}
public MagnetToggleKeyBehaviour()
{
_style = new GUIStyle();
_style.richText=(true);
_style.alignment=(TextAnchor)(4);
_content = new GUIContent();
}
public void OnGUI()
{
if (!Singleton.playerTank || Singleton.playerTank.blockman.IterateBlockComponents<ModuleItemHolderMagnet>().FirstOrDefault() == null || Singleton.Manager<ManPauseGame>.inst.IsPaused)
{
//No tank or no magnet blocks
return;
}
if (Modules.Magnet.DisabledForPlayerControlledTank)
{
_content.text=(string.Format(MagnetToggleKeyBehaviour.DisplayFormat, MagnetToggleKeyBehaviour.OfflineStatus));
}
else
{
_content.text=(string.Format(MagnetToggleKeyBehaviour.DisplayFormat, MagnetToggleKeyBehaviour.OnlineStatus));
}
_style.fontSize=(Screen.height / 60);
Vector2 vector=new Vector2((float)Screen.width * 0.5f, (float)Screen.height * 0.95f);
Vector2 vector2 = _style.CalcSize(_content);
vector.y -= vector2.y * 0.5f;
vector.x -= vector2.x * 0.5f;
GUI.Label(new Rect(vector, vector2), _content, _style);
}
}
}
|
mit
|
C#
|
5ea0dad3f8dbf26ed7e1f01f9e5fd71d3e2830e3
|
Add LimitCpu/CurrentCpuLimit to IContainer
|
cloudfoundry-incubator/IronFrame,cloudfoundry/IronFrame,stefanschneider/IronFrame,cloudfoundry/IronFrame,stefanschneider/IronFrame,cloudfoundry-incubator/IronFrame
|
IronFrame/IContainer.cs
|
IronFrame/IContainer.cs
|
using System;
using System.Collections.Generic;
using System.IO;
namespace IronFrame
{
public interface IContainer : IDisposable
{
string Id { get; }
string Handle { get; }
IContainerDirectory Directory { get; }
ContainerInfo GetInfo();
void Stop(bool kill);
int ReservePort(int requestedPort);
IContainerProcess Run(ProcessSpec spec, IProcessIO io);
void LimitMemory(ulong limitInBytes);
ulong CurrentMemoryLimit();
void LimitCpu(int weight);
int CurrentCpuLimit();
void SetProperty(string name, string value);
string GetProperty(string name);
Dictionary<string, string> GetProperties();
void RemoveProperty(string name);
void Destroy();
//ContainerState State { get; }
//void BindMounts(IEnumerable<BindMount> mounts);
//void CreateTarFile(string sourcePath, string tarFilePath, bool compress);
//void CopyFileIn(string sourceFilePath, string destinationFilePath);
//void CopyFileOut(string sourceFilePath, string destinationFilePath);
//void ExtractTarFile(string tarFilePath, string destinationPath, bool decompress);
}
public interface IProcessIO
{
TextWriter StandardOutput { get; }
TextWriter StandardError { get; }
TextReader StandardInput { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace IronFrame
{
public interface IContainer : IDisposable
{
string Id { get; }
string Handle { get; }
IContainerDirectory Directory { get; }
ContainerInfo GetInfo();
void Stop(bool kill);
int ReservePort(int requestedPort);
IContainerProcess Run(ProcessSpec spec, IProcessIO io);
void LimitMemory(ulong limitInBytes);
ulong CurrentMemoryLimit();
void SetProperty(string name, string value);
string GetProperty(string name);
Dictionary<string, string> GetProperties();
void RemoveProperty(string name);
void Destroy();
//ContainerState State { get; }
//void BindMounts(IEnumerable<BindMount> mounts);
//void CreateTarFile(string sourcePath, string tarFilePath, bool compress);
//void CopyFileIn(string sourceFilePath, string destinationFilePath);
//void CopyFileOut(string sourceFilePath, string destinationFilePath);
//void ExtractTarFile(string tarFilePath, string destinationPath, bool decompress);
}
public interface IProcessIO
{
TextWriter StandardOutput { get; }
TextWriter StandardError { get; }
TextReader StandardInput { get; }
}
}
|
apache-2.0
|
C#
|
ee4da3c38d37767180b26bf88cb7112cdc90ce11
|
Remove unused construction arg from AgentProfiler
|
mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype
|
src/Glimpse.Agent.Web/Broker/AgentProfiler.cs
|
src/Glimpse.Agent.Web/Broker/AgentProfiler.cs
|
using Glimpse.Web;
using Microsoft.Framework.Logging;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Web
{
public class AgentProfiler : IRequestProfiler
{
private readonly string _requestIdKey = "RequestId";
private readonly IAgentBroker _messageBus;
public AgentProfiler(IAgentBroker messageBus)
{
_messageBus = messageBus;
}
public async Task Begin(IHttpContext newContext)
{
var message = new BeginRequestMessage(newContext.Request);
// TODO: Full out message more
await _messageBus.SendMessage(message);
}
public async Task End(IHttpContext newContext)
{
var message = new EndRequestMessage(newContext.Request);
// TODO: Full out message more
await _messageBus.SendMessage(message);
}
}
}
|
using Glimpse.Web;
using Microsoft.Framework.Logging;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Web
{
public class AgentProfiler : IRequestProfiler
{
private readonly string _requestIdKey = "RequestId";
private readonly IAgentBroker _messageBus;
public AgentProfiler(IAgentBroker messageBus, ILoggerFactory loggingFactory)
{
_messageBus = messageBus;
}
public async Task Begin(IHttpContext newContext)
{
var message = new BeginRequestMessage(newContext.Request);
// TODO: Full out message more
await _messageBus.SendMessage(message);
}
public async Task End(IHttpContext newContext)
{
var message = new EndRequestMessage(newContext.Request);
// TODO: Full out message more
await _messageBus.SendMessage(message);
}
}
}
|
mit
|
C#
|
a8700bb250c7d6b22bbefbd9e312dc18a6025e8a
|
add internal modifier
|
ksirg/KMLib,ksirg/KMLib,ksirg/KMLib,ksirg/KMLib
|
KMLib/Helpers/Vector.cs
|
KMLib/Helpers/Vector.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KMLib.Helpers
{
internal class Vector
{
public int Dim;
public int[] Indices;
public float[] Values;
public Vector(int dim, ICollection<int> indexes, ICollection<float> vals)
{
Dim = dim;
if (indexes.Count != vals.Count)
{
throw new ArgumentOutOfRangeException("collections have different sizes");
}
Indices = new int[indexes.Count];
Values = new float[vals.Count];
var enumerator1 = indexes.GetEnumerator();
var enumerator2 = vals.GetEnumerator();
int k = 0;
while (enumerator1.MoveNext() && enumerator2.MoveNext())
{
Indices[k] = enumerator1.Current;
Values[k] = enumerator2.Current;
k++;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KMLib.Helpers
{
class Vector
{
public int Dim;
public int[] Indices;
public float[] Values;
public Vector(int dim, ICollection<int> indexes, ICollection<float> vals)
{
Dim = dim;
if (indexes.Count != vals.Count)
{
throw new ArgumentOutOfRangeException("collections have different sizes");
}
Indices = new int[indexes.Count];
Values = new float[vals.Count];
var enumerator1 = indexes.GetEnumerator();
var enumerator2 = vals.GetEnumerator();
int k = 0;
while (enumerator1.MoveNext() && enumerator2.MoveNext())
{
Indices[k] = enumerator1.Current;
Values[k] = enumerator2.Current;
k++;
}
}
}
}
|
mit
|
C#
|
8ca4f5b662b538fb54749623ac88f42025ee2ad0
|
Reduce allocations in IOQueue (#7219)
|
ElanHasson/orleans,ibondy/orleans,waynemunro/orleans,veikkoeeva/orleans,amccool/orleans,amccool/orleans,dotnet/orleans,galvesribeiro/orleans,ibondy/orleans,waynemunro/orleans,dotnet/orleans,galvesribeiro/orleans,hoopsomuah/orleans,hoopsomuah/orleans,ElanHasson/orleans,jthelin/orleans,amccool/orleans
|
src/Orleans.Core/Networking/Shared/IOQueue.cs
|
src/Orleans.Core/Networking/Shared/IOQueue.cs
|
using System;
using System.Collections.Concurrent;
using System.IO.Pipelines;
using System.Threading;
namespace Orleans.Networking.Shared
{
internal sealed class IOQueue : PipeScheduler, IThreadPoolWorkItem
{
private readonly object _workSync = new object();
private readonly ConcurrentQueue<Work> _workItems = new();
private bool _doingWork;
public override void Schedule(Action<object> action, object state)
{
var work = new Work(action, state);
_workItems.Enqueue(work);
lock (_workSync)
{
if (!_doingWork)
{
System.Threading.ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false);
_doingWork = true;
}
}
}
public void Execute()
{
while (true)
{
while (_workItems.TryDequeue(out var item))
{
item.Callback(item.State);
}
lock (_workSync)
{
if (_workItems.IsEmpty)
{
_doingWork = false;
return;
}
}
}
}
private readonly struct Work
{
public readonly Action<object> Callback;
public readonly object State;
public Work(Action<object> callback, object state)
{
Callback = callback;
State = state;
}
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.IO.Pipelines;
namespace Orleans.Networking.Shared
{
internal sealed class IOQueue : PipeScheduler
{
private readonly object _workSync = new object();
private readonly ConcurrentQueue<Work> _workItems = new ConcurrentQueue<Work>();
private static readonly Action<IOQueue> Callback = ctx => ctx.Execute();
private bool _doingWork;
public override void Schedule(Action<object> action, object state)
{
var work = new Work(action, state);
_workItems.Enqueue(work);
lock (_workSync)
{
if (!_doingWork)
{
System.Threading.ThreadPool.QueueUserWorkItem(Callback, this, preferLocal: false);
_doingWork = true;
}
}
}
private void Execute()
{
while (true)
{
while (_workItems.TryDequeue(out var item))
{
item.Callback(item.State);
}
lock (_workSync)
{
if (_workItems.IsEmpty)
{
_doingWork = false;
return;
}
}
}
}
private readonly struct Work
{
public readonly Action<object> Callback;
public readonly object State;
public Work(Action<object> callback, object state)
{
Callback = callback;
State = state;
}
}
}
}
|
mit
|
C#
|
accc60d81973f6a307215fdda59bb391927daa31
|
Add some test tracing to Index action
|
davidebbo-test/Mvc52Application,davidebbo-test/Mvc52Application,davidebbo-test/Mvc52Application
|
Mvc52Application/Controllers/HomeController.cs
|
Mvc52Application/Controllers/HomeController.cs
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mvc52Application.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Trace.TraceInformation("{0}: This is an informational trace message", DateTime.Now);
Trace.TraceWarning("{0}: Here is trace warning", DateTime.Now);
Trace.TraceError("{0}: Something is broken; tracing an error!", DateTime.Now);
return View();
}
public ActionResult About()
{
string foo = ConfigurationManager.AppSettings["foo"];
ViewBag.Message = String.Format("The value of setting foo is: '{0}'", foo);
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mvc52Application.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
string foo = ConfigurationManager.AppSettings["foo"];
ViewBag.Message = String.Format("The value of setting foo is: '{0}'", foo);
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
apache-2.0
|
C#
|
b1d7c2a69b7de8e778a4dd81a3583c0d2730565f
|
fix test
|
user1568891/PropertyChanged,Fody/PropertyChanged
|
PropertyChangedTests/RecursiveIlFinderTests.cs
|
PropertyChangedTests/RecursiveIlFinderTests.cs
|
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
[TestFixture]
public class RecursiveIlFinderTests
{
[Test]
public void Run()
{
var typeDefinition = DefinitionFinder.FindType<InnerClass>();
var recursiveIlFinder = new RecursiveIlFinder(typeDefinition);
var methodDefinition = typeDefinition.Methods.First(x => x.Name == "Method1");
recursiveIlFinder.Execute(methodDefinition);
#if(DEBUG)
Assert.AreEqual(25, recursiveIlFinder.Instructions.Count);
#else
Assert.AreEqual(22, recursiveIlFinder.Instructions.Count);
#endif
}
public abstract class InnerClass
{
public abstract string AbstractMethod();
public void Method1()
{
Property = "aString";
Method2();
}
void Method2()
{
AbstractMethod();
Method3();
Method1();
}
void Method3()
{
Debug.WriteLine("a");
}
public string Property { get; set; }
}
}
|
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
[TestFixture]
public class RecursiveIlFinderTests
{
[Test]
public void Run()
{
var typeDefinition = DefinitionFinder.FindType<InnerClass>();
var recursiveIlFinder = new RecursiveIlFinder(typeDefinition);
var methodDefinition = typeDefinition.Methods.First(x => x.Name == "Method1");
recursiveIlFinder.Execute(methodDefinition);
#if(DEBUG)
Assert.AreEqual(25, recursiveIlFinder.Instructions.Count);
#else
Assert.AreEqual(15, recursiveIlFinder.Instructions.Count);
#endif
}
public abstract class InnerClass
{
public abstract string AbstractMethod();
public void Method1()
{
Property = "aString";
Method2();
}
void Method2()
{
AbstractMethod();
Method3();
Method1();
}
void Method3()
{
Debug.WriteLine("a");
}
public string Property { get; set; }
}
}
|
mit
|
C#
|
5adf47eefd6c4c777f0ec6c1a699753a3174c5fe
|
refactor ScreenshotManager
|
OlegKleyman/Omego.Selenium
|
core/Omego.Selenium/ScreenshotManager.cs
|
core/Omego.Selenium/ScreenshotManager.cs
|
namespace Omego.Selenium
{
using System;
using System.Diagnostics;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.Extensions;
/// <summary>
/// Represents a screenshot manager.
/// </summary>
public class ScreenshotManager : IScreenshotManager
{
private readonly IWebDriver driver;
/// <summary>
/// Initializes a new instance of the <see cref="ScreenshotManager"/> class.
/// </summary>
/// <param name="driver">The <see cref="IWebDriver"/> object to use to retrieve the screenshot.</param>
public ScreenshotManager(IWebDriver driver)
{
if (driver == null) throw new ArgumentNullException(nameof(driver));
this.driver = driver;
}
/// <summary>
/// Gets a <see cref="WebScreenshot"/>.
/// </summary>
/// <param name="timeLimit">The time limit to get the screenshot.</param>
/// <returns>A <see cref="WebScreenshot"/> object.</returns>
/// <exception cref="TimeoutException">
/// Thrown when screenshot is unable to be retrieved within the specified time limit.
/// </exception>
/// <remarks>
/// This method will attempt to retrieve the screenshot at least once irrelevant
/// of the time limit specified. Additionally, the time limit is not a gaurantee
/// if an internal call to get the screenshot takes longer than the time limit
/// then the total time will exceed the time limit.
/// </remarks>
public WebScreenshot GetScreenshot(int timeLimit)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
Screenshot screenshot;
const int invalidScreenshotLength = 0;
Func<Screenshot, bool> isNotRetrieved =
(screen) => (screen == null) || (screen.AsByteArray.Length == invalidScreenshotLength);
do
{
screenshot = driver.TakeScreenshot();
}
while (stopWatch.ElapsedMilliseconds < timeLimit && (isNotRetrieved(screenshot)));
stopWatch.Stop();
if (isNotRetrieved(screenshot))
{
throw new TimeoutException(
$"Unable to get screenshot after trying for {stopWatch.ElapsedMilliseconds}ms.");
}
return new WebScreenshot(screenshot);
}
}
}
|
namespace Omego.Selenium
{
using System;
using System.Diagnostics;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.Extensions;
/// <summary>
/// Represents a screenshot manager.
/// </summary>
public class ScreenshotManager : IScreenshotManager
{
private readonly IWebDriver driver;
/// <summary>
/// Initializes a new instance of the <see cref="ScreenshotManager"/> class.
/// </summary>
/// <param name="driver">The <see cref="IWebDriver"/> object to use to retrieve the screenshot.</param>
public ScreenshotManager(IWebDriver driver)
{
if (driver == null) throw new ArgumentNullException(nameof(driver));
this.driver = driver;
}
/// <summary>
/// Gets a <see cref="WebScreenshot"/>.
/// </summary>
/// <param name="timeLimit">The time limit to get the screenshot.</param>
/// <returns>A <see cref="WebScreenshot"/> object.</returns>
/// <exception cref="TimeoutException">
/// Thrown when screenshot is unable to be retrieved within the specified time limit.
/// </exception>
/// <remarks>
/// This method will attempt to retrieve the screenshot at least once irrelevant
/// of the time limit specified. Additionally, the time limit is not a gaurantee
/// if an internal call to get the screenshot takes longer than the time limit
/// then the total time will exceed the time limit.
/// </remarks>
public WebScreenshot GetScreenshot(int timeLimit)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
Screenshot screenshot;
const int invalidScreenshotLength = 0;
do
{
screenshot = driver.TakeScreenshot();
}
while (stopWatch.ElapsedMilliseconds < timeLimit
&& ((screenshot == null) || (screenshot.AsByteArray.Length == invalidScreenshotLength)));
stopWatch.Stop();
if (screenshot == null || screenshot.AsByteArray.Length == invalidScreenshotLength)
{
throw new TimeoutException(
$"Unable to get screenshot after trying for {stopWatch.ElapsedMilliseconds}ms.");
}
return new WebScreenshot(screenshot);
}
}
}
|
unlicense
|
C#
|
c929b64bee12aaaa0107c174c63e2bd5814933dd
|
improve JODConvert Demo
|
oldrev/maltreport
|
Sandwych.Reporting.JODConverterDemo/Program.cs
|
Sandwych.Reporting.JODConverterDemo/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using org.artofsolving.jodconverter;
using org.artofsolving.jodconverter.office;
namespace Sandwych.Reporting.JODConverterDemo
{
class Program
{
static void Main(string[] args)
{
//Make sure your LibreOffice/OpenOffice home is correct
var officeHome = @"C:\LibreOffice3.5";
var officePaths =
Path.Combine(officeHome, "URE", "bin") + ";" + Path.Combine(officeHome, "program");
var path = Environment.GetEnvironmentVariable("PATH");
if (!path.EndsWith(";"))
{
path += ';';
}
path += officePaths;
Environment.SetEnvironmentVariable("PATH", path);
var officeManager = new DefaultOfficeManagerConfiguration()
.setOfficeHome(officeHome)
.buildOfficeManager();
officeManager.start();
var converter = new OfficeDocumentConverter(officeManager);
//Do some document converting job
converter.convert(new java.io.File("demo.odt"), new java.io.File("test.pdf"));
officeManager.stop();
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using org.artofsolving.jodconverter;
using org.artofsolving.jodconverter.office;
namespace Sandwych.Reporting.JODConverterDemo
{
class Program
{
static void Main(string[] args)
{
//Make sure your LibreOffice/OpenOffice home is correct
var officeHome = @"C:\LibreOffice3.5";
var officePaths =
Path.Combine(officeHome, "URE", "bin") + ";" + Path.Combine(officeHome, "program");
var path = Environment.GetEnvironmentVariable("PATH");
path += ";" + officePaths;
Environment.SetEnvironmentVariable("PATH", path);
var officeManager = new DefaultOfficeManagerConfiguration()
.setOfficeHome(officeHome)
.buildOfficeManager();
officeManager.start();
var converter = new OfficeDocumentConverter(officeManager);
//Do some document converting job
converter.convert(new java.io.File("demo.odt"), new java.io.File("test.pdf"));
officeManager.stop();
Console.ReadKey();
}
}
}
|
mit
|
C#
|
a9c61f4b552727fc8a06d430c28f44ab78a09cc4
|
Set page data in the appropriate LoadState method instead of OnNavigatedTo
|
peruukki/PremierLeague
|
PremierLeague/MainPage.xaml.cs
|
PremierLeague/MainPage.xaml.cs
|
using PremierLeague.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace PremierLeague
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : LayoutAwarePage
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
var teams = new Data.DataSource().Items;
var result = from t in teams
orderby t.PositionDifference descending
group t by GetGroupName(t.PositionDifference) into g
select new { Key = string.Format("{0} ({1})", g.Key, g.ToList().Count), Items = g }; ;
groupData.Source = result;
}
private string GetGroupName(int difference)
{
if (difference > 4) return "Fantastic season";
else if (difference > 1) return "Exceeding expectations";
else if (difference < -4) return "Nightmare season";
else if (difference < -1) return "Disappointing";
else return "Doing OK";
}
}
}
|
using PremierLeague.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace PremierLeague
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : LayoutAwarePage
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var teams = new Data.DataSource().Items;
var result = from t in teams
orderby t.PositionDifference descending
group t by GetGroupName(t.PositionDifference) into g
select new { Key = string.Format("{0} ({1})", g.Key, g.ToList().Count), Items = g }; ;
groupData.Source = result;
}
private string GetGroupName(int difference)
{
if (difference > 4) return "Fantastic season";
else if (difference > 1) return "Exceeding expectations";
else if (difference < -4) return "Nightmare season";
else if (difference < -1) return "Disappointing";
else return "Doing OK";
}
}
}
|
mit
|
C#
|
4d09872f21c5791d4fcbee65d325fe188a65da08
|
Bump version to 0.32.0
|
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
|
common/SolutionInfo.cs
|
common/SolutionInfo.cs
|
#pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.32.0";
}
}
|
#pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.31.8";
}
}
|
mit
|
C#
|
7175ad2b3c088e9861e6b1820bf08c872d747b3e
|
Bump version to 1.3.1
|
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
|
common/SolutionInfo.cs
|
common/SolutionInfo.cs
|
#pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
private const string GitHubForUnityVersion = "1.3.1";
internal const string VersionForAssembly = GitHubForUnityVersion;
// If this is an alpha, beta or other pre-release, mark it as such as shown below
internal const string Version = GitHubForUnityVersion; // GitHubForUnityVersion + "-beta1"
}
}
|
#pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
private const string GitHubForUnityVersion = "1.3.0";
internal const string VersionForAssembly = GitHubForUnityVersion;
// If this is an alpha, beta or other pre-release, mark it as such as shown below
internal const string Version = GitHubForUnityVersion; // GitHubForUnityVersion + "-beta1"
}
}
|
mit
|
C#
|
7a2e0044316acb1d89d5baaecad3dd0ea5aa3d0b
|
Support driver constructor standing parameter for season list request
|
Krusen/ErgastApi.Net
|
src/ErgastApi/Requests/Standard/SeasonListRequest.cs
|
src/ErgastApi/Requests/Standard/SeasonListRequest.cs
|
using ErgastApi.Client.Attributes;
using ErgastApi.Responses;
namespace ErgastApi.Requests
{
public class SeasonListRequest : StandardRequest<SeasonResponse>
{
[UrlSegment("constructorStandings")]
public int? ConstructorStanding { get; set; }
[UrlSegment("driverStandings")]
public int? DriverStanding { get; set; }
// Value not used
// ReSharper disable once UnassignedGetOnlyAutoProperty
[UrlTerminator, UrlSegment("seasons")]
protected object Seasons { get; }
}
}
|
using ErgastApi.Client.Attributes;
using ErgastApi.Responses;
namespace ErgastApi.Requests
{
public class SeasonListRequest : StandardRequest<SeasonResponse>
{
// Value not used
// ReSharper disable once UnassignedGetOnlyAutoProperty
[UrlTerminator, UrlSegment("seasons")]
protected object Seasons { get; }
}
}
|
unlicense
|
C#
|
e3a1bb490a5b9177a7433322387a946c67a7a9ad
|
Add logging to ScheduledTasksController
|
BarryFogarty/Merchello,BluefinDigital/Merchello,BluefinDigital/Merchello,MindfireTechnology/Merchello,Merchello/Merchello.Bazaar,doronuziel71/Merchello,rasmusjp/Merchello,Merchello/Merchello,BarryFogarty/Merchello,Merchello/Merchello.Bazaar,bjarnef/Merchello,rasmusjp/Merchello,clausjensen/Merchello,ProNotion/Merchello,Merchello/Merchello,Merchello/Merchello.Bazaar,BluefinDigital/Merchello,bjarnef/Merchello,clausjensen/Merchello,BluefinDigital/Merchello,clausjensen/Merchello,MindfireTechnology/Merchello,BarryFogarty/Merchello,Merchello/Merchello,ProNotion/Merchello,doronuziel71/Merchello,doronuziel71/Merchello,MindfireTechnology/Merchello,BarryFogarty/Merchello,ProNotion/Merchello,bjarnef/Merchello,rasmusjp/Merchello
|
src/Merchello.Web/WebApi/ScheduledTasksController.cs
|
src/Merchello.Web/WebApi/ScheduledTasksController.cs
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Linq;
using Umbraco.Web.Mvc;
using Merchello.Core;
using Merchello.Core.Models;
using Merchello.Core.Services;
using Merchello.Core.Configuration;
using Merchello.Web.WebApi;
using Umbraco.Web;
using Merchello.Web.Models.ContentEditing;
using Examine;
using Umbraco.Web.WebApi;
using Umbraco.Core.Logging;
namespace Merchello.Web.WebApi
{
/// <summary>
/// Schedule Tasks
/// </summary>
//[PluginController("Merchello")]
public class ScheduledTasksApiController : UmbracoApiController
{
/// <summary>
/// Delete all customers older than the date in the setting
///
/// GET /umbraco/Merchello/ScheduledTasksApi/RemoveAnonymousCustomers
/// </summary>
[AcceptVerbs("GET", "POST")]
public int RemoveAnonymousCustomers()
{
int maxDays = MerchelloConfiguration.Current.AnonymousCustomersMaxDays;
var repo = new AnonymousCustomerService();
var anonymousCustomers = repo.GetAnonymousCustomersCreatedBefore(DateTime.Now); //.AddDays(-maxDays));
repo.Delete(anonymousCustomers);
LogHelper.Info<string>(string.Format("RemoveAnonymousCustomers - Removed Count {0}", anonymousCustomers.Count()));
return anonymousCustomers.Count();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Linq;
using Umbraco.Web.Mvc;
using Merchello.Core;
using Merchello.Core.Models;
using Merchello.Core.Services;
using Merchello.Core.Configuration;
using Merchello.Web.WebApi;
using Umbraco.Web;
using Merchello.Web.Models.ContentEditing;
using Examine;
using Umbraco.Web.WebApi;
namespace Merchello.Web.WebApi
{
/// <summary>
/// Schedule Tasks
/// </summary>
//[PluginController("Merchello")]
public class ScheduledTasksApiController : UmbracoApiController
{
/// <summary>
/// Delete all customers older than the date in the setting
///
/// GET /umbraco/Merchello/ScheduledTasksApi/RemoveAnonymousCustomers
/// </summary>
[AcceptVerbs("GET", "POST")]
public int RemoveAnonymousCustomers()
{
int maxDays = MerchelloConfiguration.Current.AnonymousCustomersMaxDays;
var repo = new AnonymousCustomerService();
var anonymousCustomers = repo.GetAnonymousCustomersCreatedBefore(DateTime.Now); //.AddDays(-maxDays));
repo.Delete(anonymousCustomers);
return anonymousCustomers.Count();
}
}
}
|
mit
|
C#
|
4059c8e9a0956d0b85773f8beddcaa21602713ae
|
Add generic definiton
|
FireCube-/HarvesterBot
|
TexasHoldEm/Chromosome.cs
|
TexasHoldEm/Chromosome.cs
|
using System;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Chromosome<Type, Size> {
public Chromosome() {
//
// TODO: Add constructor logic here
//
}
}
|
using System;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Chromosome {
public Chromosome() {
//
// TODO: Add constructor logic here
//
}
}
|
mit
|
C#
|
c7c2f7c6dbfabaeb0a06f220ad8c757cb9b6d322
|
Update PrimitiveObjectValueConverter.cs
|
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
|
main/Smartsheet/Api/Internal/Json/PrimitiveObjectValueConverter.cs
|
main/Smartsheet/Api/Internal/Json/PrimitiveObjectValueConverter.cs
|
// #[ license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2017 SmartsheetClient
// %%
// 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.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Smartsheet.Api.Models;
namespace Smartsheet.Api.Internal.Json
{
class PrimitiveObjectValueConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
bool isPrimitiveObjectValue = objectType.GetInterfaces().Any(x =>
x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IPrimitiveObjectValue<>));
return isPrimitiveObjectValue;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
object objectToDeserialize = Activator.CreateInstance(objectType);
serializer.Populate(reader, objectToDeserialize);
return objectToDeserialize;
}
public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
}
else
{
Type type = value.GetType();
object[] args = new object[] { writer };
type.GetMethod("Serialize").Invoke(value, args);
}
}
}
}
|
// #[ license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2017 SmartsheetClient
// %%
// 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.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Smartsheet.Api.Models;
namespace Smartsheet.Api.Internal.Json
{
class PrimitiveObjectValueConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
bool isPrimitiveObjectValue = objectType.GetInterfaces().Any(x =>
x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IPrimitiveObjectValue<>));
return isPrimitiveObjectValue;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
object objectToDeserialize = Activator.CreateInstance(objectType);
serializer.Populate(reader, objectToDeserialize);
return objectToDeserialize;
}
public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
}
else
{
Type type = value.GetType();
object[] args = new object[] { writer };
type.GetMethod("Serialize").Invoke(value, args);
}
}
}
}
|
apache-2.0
|
C#
|
c18360860f7a9a62db516bfbb3c6c41dc11fefcd
|
Fix bug in conversion from Color3 to Color3b
|
rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary
|
CSharpGameLibrary/Graphics/Color3b.cs
|
CSharpGameLibrary/Graphics/Color3b.cs
|
using System;
using System.Runtime.InteropServices;
namespace CSGL.Graphics {
public struct Color3b : IEquatable<Color3b> {
public byte r, g, b;
public Color3b(byte r, byte g, byte b) {
this.r = r;
this.g = g;
this.b = b;
}
public Color3b(int r, int g, int b) : this((byte)r, (byte)g, (byte)b) { }
public Color3b(Color3 color) {
r = (byte)System.Math.Min(System.Math.Max(color.r * 255, 0), 255);
g = (byte)System.Math.Min(System.Math.Max(color.g * 255, 0), 255);
b = (byte)System.Math.Min(System.Math.Max(color.b * 255, 0), 255);
}
public uint ToUint() {
uint result = 0;
result &= r;
result &= (uint)g << 8;
result &= (uint)b << 16;
return result;
}
public bool Equals(Color3b other) {
return r == other.r &&
g == other.g &&
b == other.b;
}
public static bool operator ==(Color3b a, Color3b b) {
return a.Equals(b);
}
public static bool operator !=(Color3b a, Color3b b) {
return !a.Equals(b);
}
public override bool Equals(object other) {
if (other is Color3b) {
return Equals((Color3b)other);
}
return false;
}
public override int GetHashCode() {
return r.GetHashCode() ^
g.GetHashCode() ^
b.GetHashCode();
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace CSGL.Graphics {
public struct Color3b : IEquatable<Color3b> {
public byte r, g, b;
public Color3b(byte r, byte g, byte b) {
this.r = r;
this.g = g;
this.b = b;
}
public Color3b(int r, int g, int b) : this((byte)r, (byte)g, (byte)b) { }
public Color3b(Color3 color) {
r = (byte)(color.r * 255);
g = (byte)(color.g * 255);
b = (byte)(color.b * 255);
}
public uint ToUint() {
uint result = 0;
result &= r;
result &= (uint)g << 8;
result &= (uint)b << 16;
return result;
}
public bool Equals(Color3b other) {
return r == other.r &&
g == other.g &&
b == other.b;
}
public static bool operator ==(Color3b a, Color3b b) {
return a.Equals(b);
}
public static bool operator !=(Color3b a, Color3b b) {
return !a.Equals(b);
}
public override bool Equals(object other) {
if (other is Color3b) {
return Equals((Color3b)other);
}
return false;
}
public override int GetHashCode() {
return r.GetHashCode() ^
g.GetHashCode() ^
b.GetHashCode();
}
}
}
|
mit
|
C#
|
8658132ced1024ed8c4313b6e93f7667ce950679
|
fix code
|
autumn009/TanoCSharpSamples
|
Chap35/AllowNull/AllowNull/Program.cs
|
Chap35/AllowNull/AllowNull/Program.cs
|
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
private static string s = string.Empty;
[AllowNull]
public static string MyProperty
{
get { return s; }
set { s = value ?? string.Empty; }
}
public static void ShowStringLength(string? s)
{
Console.WriteLine((s ?? "").Length);
}
static void Main()
{
MyProperty = null;
ShowStringLength(MyProperty);
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
private static string s = string.Empty;
[AllowNull]
public static string MyProperty
{
get { return s; }
set { s = value ?? string.Empty; }
}
public static void ShowStringLength(string s)
{
Console.WriteLine(s.Length);
}
static void Main(string[] args)
{
// safe because [AllowNull]
MyProperty = null;
// safe becase MyProperty is 'string' type
ShowStringLength(MyProperty);
}
}
|
mit
|
C#
|
4994f157ace9b5df0443ea780eae678fbff3803a
|
Remove an absolute path
|
vain0/EnumerableTest
|
EnumerableTest.Runner.Wpf/TestTree/TestTreeView.xaml.cs
|
EnumerableTest.Runner.Wpf/TestTree/TestTreeView.xaml.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace EnumerableTest.Runner.Wpf
{
/// <summary>
/// TestTreeView.xaml の相互作用ロジック
/// </summary>
public partial class TestTreeView : UserControl
{
readonly TestTree testTree = new TestTree();
public TestTreeView()
{
InitializeComponent();
var args = Environment.GetCommandLineArgs();
#if DEBUG
args = new[] { @"..\..\..\EnumerableTest.Sandbox\bin\Debug\EnumerableTest.Sandbox.dll" };
#endif
foreach (var arg in args)
{
testTree.LoadFile(new FileInfo(arg));
}
DataContext = testTree;
Unloaded += (sender, e) => testTree.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace EnumerableTest.Runner.Wpf
{
/// <summary>
/// TestTreeView.xaml の相互作用ロジック
/// </summary>
public partial class TestTreeView : UserControl
{
readonly TestTree testTree = new TestTree();
public TestTreeView()
{
InitializeComponent();
var args = Environment.GetCommandLineArgs();
#if DEBUG
args = new[] { @"D:\repo\EnumerableTest\EnumerableTest.Sandbox\bin\Debug\EnumerableTest.Sandbox.dll" };
#endif
foreach (var arg in args)
{
testTree.LoadFile(new FileInfo(arg));
}
DataContext = testTree;
Unloaded += (sender, e) => testTree.Dispose();
}
}
}
|
mit
|
C#
|
3025bea195bad51bcc41a3e8c258984d5c31010a
|
Remove API route trailing slash to avoid AWS API Gateway modification
|
sinch/nuget-serversdk
|
src/Sinch.ServerSdk/Callouts/ICalloutApiEndpoints.cs
|
src/Sinch.ServerSdk/Callouts/ICalloutApiEndpoints.cs
|
using System.Threading.Tasks;
using Sinch.ServerSdk.Callouts;
using Sinch.WebApiClient;
public interface ICalloutApiEndpoints
{
[HttpPost("calling/v1/callouts")]
Task<CalloutResponse> Callout([ToBody] CalloutRequest request);
}
|
using System.Threading.Tasks;
using Sinch.ServerSdk.Callouts;
using Sinch.WebApiClient;
public interface ICalloutApiEndpoints
{
[HttpPost("calling/v1/callouts/")]
Task<CalloutResponse> Callout([ToBody] CalloutRequest request);
}
|
mit
|
C#
|
4e7d37932378eb4350fca09c0413bfea02f14779
|
Remove namespaces
|
Litee/SolutionCop
|
src/SolutionCop.CommandLine/CommandLineParameters.cs
|
src/SolutionCop.CommandLine/CommandLineParameters.cs
|
namespace SolutionCop.CommandLine
{
using global::CommandLine;
using global::CommandLine.Text;
internal enum BuildServer
{
None,
TeamCity
}
// ReSharper disable UnusedAutoPropertyAccessor.Global
internal sealed class CommandLineParameters
{
[Option('s', "solution", Required = true, HelpText = "Path to the Visual Studio solution file to analyze.")]
public string PathToSolution { get; set; }
[Option('c', "config", Required = false, HelpText = "Path to the configuration file with rule settings.")]
public string PathToConfigFile { get; set; }
[Option('b', "build-server", Required = false, HelpText = "Specify this parameter if you want additional information to be sent to CI server via console interaction. Supported value: TeamCity")]
public BuildServer BuildServerType { get; set; }
[Option("suppress-success-status-message", DefaultValue = false, HelpText = "Hide success messages on TeamCity", Required = false)]
public bool HideSuccessStatus { get; set; }
[HelpOption]
// ReSharper disable once UnusedMember.Global
public string GetUsage()
{
return HelpText.AutoBuild(this);
}
}
}
|
using System.Net;
using System.Runtime.InteropServices.ComTypes;
namespace SolutionCop.CommandLine
{
using global::CommandLine;
using global::CommandLine.Text;
internal enum BuildServer
{
None,
TeamCity
}
// ReSharper disable UnusedAutoPropertyAccessor.Global
internal sealed class CommandLineParameters
{
[Option('s', "solution", Required = true, HelpText = "Path to the Visual Studio solution file to analyze.")]
public string PathToSolution { get; set; }
[Option('c', "config", Required = false, HelpText = "Path to the configuration file with rule settings.")]
public string PathToConfigFile { get; set; }
[Option('b', "build-server", Required = false, HelpText = "Specify this parameter if you want additional information to be sent to CI server via console interaction. Supported value: TeamCity")]
public BuildServer BuildServerType { get; set; }
[Option("suppress-success-status-message", DefaultValue = false, HelpText = "Hide success messages on TeamCity", Required = false)]
public bool HideSuccessStatus { get; set; }
[HelpOption]
// ReSharper disable once UnusedMember.Global
public string GetUsage()
{
return HelpText.AutoBuild(this);
}
}
}
|
apache-2.0
|
C#
|
c359c1d6ca372b9b7aad67a5ca9b667f45f85b5c
|
Fix bug that prevents adding of master comments
|
leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net
|
JoinRpg.Domain/SubscribeExtensions.cs
|
JoinRpg.Domain/SubscribeExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class SubscribeExtensions
{
public static IEnumerable<User> GetSubscriptions(this ForumThread claim, [CanBeNull] IEnumerable<User> extraRecepients, bool isVisibleToPlayer)
{
return
claim.Subscriptions //get subscriptions on forum
.Select(u => u.User) //Select users
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.VerifySubscriptions(isVisibleToPlayer, claim);
}
public static IEnumerable<User> GetSubscriptions(
this Claim claim,
Func<UserSubscription, bool> predicate,
[CanBeNull] IEnumerable<User> extraRecepients,
bool isVisibleToPlayer)
{
return claim.GetTarget().GetGroupsPartOf() //Get all groups for claim
.SelectMany(g => g.Subscriptions) //get subscriptions on groups
.Union(claim.Subscriptions) //subscribtions on claim
.Union(claim.Character?.Subscriptions ?? new UserSubscription[] {}) //and on characters
.Where(predicate) //type of subscribe (on new comments, on new claims etc.)
.Select(u => u.User) //Select users
.Union(claim.ResponsibleMasterUser) //Responsible master is always subscribed on everything
.Union(claim.Player) //...and player himself also
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.VerifySubscriptions(isVisibleToPlayer, claim)
;
}
private static IEnumerable<User> VerifySubscriptions<TEntity>(this IEnumerable<User> users, bool isVisibleToPlayer, TEntity entity)
where TEntity : IProjectEntity
{
return users
.Where(u => u != null)
.Where(u => isVisibleToPlayer || entity.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class SubscribeExtensions
{
public static IEnumerable<User> GetSubscriptions(this ForumThread claim, [CanBeNull] IEnumerable<User> extraRecepients, bool isVisibleToPlayer)
{
return
claim.Subscriptions //get subscriptions on forum
.Select(u => u.User) //Select users
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
}
public static IEnumerable<User> GetSubscriptions(
this Claim claim,
Func<UserSubscription, bool> predicate,
[CanBeNull] IEnumerable<User> extraRecepients,
bool isVisibleToPlayer)
{
return claim.GetTarget().GetGroupsPartOf() //Get all groups for claim
.SelectMany(g => g.Subscriptions) //get subscriptions on groups
.Union(claim.Subscriptions) //subscribtions on claim
.Union(claim.Character?.Subscriptions ?? new UserSubscription[] {}) //and on characters
.Where(predicate) //type of subscribe (on new comments, on new claims etc.)
.Select(u => u.User) //Select users
.Union(claim.ResponsibleMasterUser) //Responsible master is always subscribed on everything
.Union(claim.Player) //...and player himself also
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
;
}
}
}
|
mit
|
C#
|
26ccb790b8cd2fcf362f8a6b02a1085aa7e3f828
|
Add Name field to GameDefinition class.
|
rmcardle/LazerTagHost,rmcardle/LazerTagHost
|
LazerTagHostLibrary/GameDefinition.cs
|
LazerTagHostLibrary/GameDefinition.cs
|
namespace LazerTagHostLibrary
{
public class GameDefinition
{
public GameDefinition()
{
CountdownTimeSeconds = 30;
ResendCountdownTimeSeconds = 10;
HuntDirection = false;
Name = new LazerTagString();
}
public GameType GameType
{
get { return _gameTypeInfo.Type; }
set { _gameTypeInfo = GameTypes.GetInfo(value); }
}
private GameTypeInfo _gameTypeInfo;
public GameTypeInfo GameTypeInfo
{
get { return _gameTypeInfo; }
}
public byte GameId { get; set; }
public int GameTimeMinutes { get; set; }
public int Tags { get; set; }
private int _reloads;
public int Reloads
{
get { return _reloads; }
set
{
_reloads = value;
_limitedReloads = (_reloads != 0xff);
}
}
public int Shields { get; set; }
private int _mega;
public int Mega
{
get
{
return _mega;
}
set
{
_mega = value;
LimitedMega = (_mega != 0xff);
}
}
public bool ExtendedTagging { get; set; }
private bool _limitedReloads;
public bool LimitedReloads
{
get { return _limitedReloads; }
set
{
_limitedReloads = value;
if (value)
{
if (_reloads == 0xff) _reloads = 99;
}
else
{
_reloads = 0xff;
}
}
}
private bool _limitedMega;
public bool LimitedMega
{
get { return _limitedMega; }
set
{
_limitedMega = value;
if (value)
{
if (_mega == 0xff) _mega = 99;
}
else
{
_mega = 0xff;
}
}
}
public bool TeamTags { get; set; }
public bool MedicMode { get; set; }
public bool SlowTags { get; set; }
public bool HuntDirection { get; set; }
public bool IsZoneGame
{
get { return GameTypeInfo.Zones || GameTypeInfo.TeamZones || GameTypeInfo.ZonesRevivePlayers || GameTypeInfo.HospitalZones || GameTypeInfo.ZonesTagPlayers; }
}
public int TeamCount
{
get { return GameTypeInfo.TeamCount; }
}
public bool IsTeamGame
{
get { return (TeamCount > 1); }
}
public LazerTagString Name { get; set; }
public int CountdownTimeSeconds { get; set; }
public int ResendCountdownTimeSeconds { get; set; }
}
}
|
namespace LazerTagHostLibrary
{
public class GameDefinition
{
public GameDefinition()
{
CountdownTimeSeconds = 30;
ResendCountdownTimeSeconds = 10;
HuntDirection = false;
}
public GameType GameType
{
get { return _gameTypeInfo.Type; }
set { _gameTypeInfo = GameTypes.GetInfo(value); }
}
private GameTypeInfo _gameTypeInfo;
public GameTypeInfo GameTypeInfo
{
get { return _gameTypeInfo; }
}
public byte GameId { get; set; }
public int GameTimeMinutes { get; set; }
public int Tags { get; set; }
private int _reloads;
public int Reloads
{
get { return _reloads; }
set
{
_reloads = value;
_limitedReloads = (_reloads != 0xff);
}
}
public int Shields { get; set; }
private int _mega;
public int Mega
{
get
{
return _mega;
}
set
{
_mega = value;
LimitedMega = (_mega != 0xff);
}
}
public bool ExtendedTagging { get; set; }
private bool _limitedReloads;
public bool LimitedReloads
{
get { return _limitedReloads; }
set
{
_limitedReloads = value;
if (value)
{
if (_reloads == 0xff) _reloads = 99;
}
else
{
_reloads = 0xff;
}
}
}
private bool _limitedMega;
public bool LimitedMega
{
get { return _limitedMega; }
set
{
_limitedMega = value;
if (value)
{
if (_mega == 0xff) _mega = 99;
}
else
{
_mega = 0xff;
}
}
}
public bool TeamTags { get; set; }
public bool MedicMode { get; set; }
public bool SlowTags { get; set; }
public bool HuntDirection { get; set; }
public bool IsZoneGame
{
get { return GameTypeInfo.Zones || GameTypeInfo.TeamZones || GameTypeInfo.ZonesRevivePlayers || GameTypeInfo.HospitalZones || GameTypeInfo.ZonesTagPlayers; }
}
public int TeamCount
{
get { return GameTypeInfo.TeamCount; }
}
public bool IsTeamGame
{
get { return (TeamCount > 1); }
}
public LazerTagString Name { get; set; }
public int CountdownTimeSeconds { get; set; }
public int ResendCountdownTimeSeconds { get; set; }
}
}
|
mit
|
C#
|
aae394d5fbdc7555a0d8bbe24b390b87a955bc84
|
Refactor Convert logic in DateTimeConverterBase
|
thomasgalliker/ValueConverters.NET
|
ValueConverters.NetFx/DateTimeConverterBase.cs
|
ValueConverters.NetFx/DateTimeConverterBase.cs
|
using System;
using System.Globalization;
#if NETFX || WINDOWS_PHONE
using System.Windows;
using System.Windows.Data;
#elif (WINDOWS_APP || WINDOWS_PHONE_APP)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
#endif
namespace ValueConverters
{
public abstract class DateTimeConverterBase : ConverterBase
{
protected const string DefaultFormat = "g";
protected const string DefaultMinValueString = "";
public abstract string Format { get; set; }
public abstract string MinValueString { get; set; }
protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
if (value is DateTime)
{
var dateTime = (DateTime)value;
if (dateTime == DateTime.MinValue)
{
return this.MinValueString;
}
return dateTime.ToLocalTime().ToString(this.Format, culture);
}
}
return UnsetValue;
}
protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
if (value is DateTime)
{
return (DateTime)value;
}
var str = value as string;
if (str != null)
{
DateTime resultDateTime;
DateTime.TryParse(str, out resultDateTime);
return resultDateTime;
}
}
return null;
}
}
}
|
using System;
using System.Globalization;
#if NETFX || WINDOWS_PHONE
using System.Windows;
using System.Windows.Data;
#elif (WINDOWS_APP || WINDOWS_PHONE_APP)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
#endif
namespace ValueConverters
{
public abstract class DateTimeConverterBase : ConverterBase
{
protected const string DefaultFormat = "g";
protected const string DefaultMinValueString = "";
public abstract string Format { get; set; }
public abstract string MinValueString { get; set; }
protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || (DateTime)value == DateTime.MinValue)
{
return this.MinValueString;
}
if (targetType == typeof(string))
{
return ((DateTime)value).ToLocalTime().ToString(this.Format, culture);
}
return UnsetValue;
}
}
}
|
mit
|
C#
|
f0a1c2902a1b5a990012375fc40901160abc63de
|
Fix unit test.
|
JohnThomson/libpalaso,gtryus/libpalaso,marksvc/libpalaso,hatton/libpalaso,sillsdev/libpalaso,chrisvire/libpalaso,darcywong00/libpalaso,tombogle/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,darcywong00/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,gtryus/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,chrisvire/libpalaso,gmartin7/libpalaso,hatton/libpalaso,ddaspit/libpalaso,JohnThomson/libpalaso,darcywong00/libpalaso,tombogle/libpalaso,marksvc/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,hatton/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,mccarthyrb/libpalaso
|
PalasoUIWindowsForms.Tests/FontTests/FontHelperTests.cs
|
PalasoUIWindowsForms.Tests/FontTests/FontHelperTests.cs
|
using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[Test]
public void MakeFont_FontName_ValidFont()
{
using (var sourceFont = SystemFonts.DefaultFont)
{
using (var returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
}
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// find a bold font
var family = FontFamily.Families.FirstOrDefault(f => (f.IsStyleAvailable(FontStyle.Regular) && f.IsStyleAvailable(FontStyle.Bold)));
Assert.IsNotNull(family, "No font was found on this system that supports the Bold style");
Console.Out.WriteLine("Using the " + family.Name + " font for this test.");
using (var sourceFont = new Font(family, 10f, FontStyle.Regular))
{
using (var returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
}
}
}
[Test]
public void MakeFont_InvalidFontName_ValidFont()
{
const string invalidName = "SomeInvalidName";
using (var returnFont = FontHelper.MakeFont(invalidName))
{
Assert.AreNotEqual(invalidName, returnFont.FontFamily.Name);
}
}
}
}
|
using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[Test]
public void MakeFont_FontName_ValidFont()
{
using (var sourceFont = SystemFonts.DefaultFont)
{
using (var returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
}
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// find a bold font
var family = FontFamily.Families.FirstOrDefault(f => f.IsStyleAvailable(FontStyle.Bold));
Assert.IsNotNull(family, "No font was found on this system that supports the Bold style");
Console.Out.WriteLine("Using the " + family.Name + " font for this test.");
using (var sourceFont = new Font(family, 10f, FontStyle.Regular))
{
using (var returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold))
{
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
}
}
}
[Test]
public void MakeFont_InvalidFontName_ValidFont()
{
const string invalidName = "SomeInvalidName";
using (var returnFont = FontHelper.MakeFont(invalidName))
{
Assert.AreNotEqual(invalidName, returnFont.FontFamily.Name);
}
}
}
}
|
mit
|
C#
|
8e9ac3a7571b7d426df3218c0d183608e1a62822
|
Tweak player movement
|
Goat-Improvement-Suite/The-Chinese-Room
|
Assets/Scripts/CharacterMovement.cs
|
Assets/Scripts/CharacterMovement.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour {
public float speed; //Floating point variable to store the player's movement speed.
public float maxSpeed;
public int playerNo;
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
// Use this for initialization
void Start () {
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
}
private void FixedUpdate() {
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxisRaw("Horizontal" + "_" + playerNo);
//Store the current vertical input in the float moveVertical.
float moveVertical = Input.GetAxisRaw("Vertical" + "_" + playerNo);
//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
if (rb2d.velocity.magnitude < maxSpeed && movement != Vector2.zero) {
rb2d.AddForce(movement * speed);
}
//Debug.DrawLine(transform.position, transform.position + (Vector3)movement, Color.red);
//Debug.DrawLine(transform.position, transform.position + (Vector3)rb2d.velocity);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour {
public float speed; //Floating point variable to store the player's movement speed.
public int playerNo;
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
// Use this for initialization
void Start () {
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
}
private void FixedUpdate(){
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxis("Horizontal" + "_" + playerNo);
//Store the current vertical input in the float moveVertical.
float moveVertical = Input.GetAxis("Vertical" + "_" + playerNo);
//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
rb2d.AddForce(movement * speed);
}
}
|
mit
|
C#
|
28cc60d0070032075c5f0dbb66b52dbd8d08bc7f
|
Tweak CommandLineArgsParser to slightly improve reliability with quoted strings
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
Core/Utils/CommandLineArgsParser.cs
|
Core/Utils/CommandLineArgsParser.cs
|
using System.Text.RegularExpressions;
namespace TweetDck.Core.Utils{
static class CommandLineArgsParser{
private static Regex splitRegex;
private static Regex SplitRegex{
get{
return splitRegex ?? (splitRegex = new Regex(@"([^=\s]+(?:=(?:[^ ]*""[^""]*?""[^ ]*|[^ ]*))?)", RegexOptions.Compiled));
}
}
public static CommandLineArgs ReadCefArguments(string argumentString){
CommandLineArgs args = new CommandLineArgs();
if (string.IsNullOrWhiteSpace(argumentString)){
return args;
}
foreach(Match match in SplitRegex.Matches(argumentString)){
string matchValue = match.Value;
int indexEquals = matchValue.IndexOf('=');
string key, value;
if (indexEquals == -1){
key = matchValue.TrimStart('-');
value = "1";
}
else{
key = matchValue.Substring(0, indexEquals).TrimStart('-');
value = matchValue.Substring(indexEquals+1).Trim('"');
}
if (key.Length != 0){
args.SetValue(key, value);
}
}
return args;
}
}
}
|
using System.Text.RegularExpressions;
namespace TweetDck.Core.Utils{
static class CommandLineArgsParser{
private static Regex splitRegex;
private static Regex SplitRegex{
get{
return splitRegex ?? (splitRegex = new Regex(@"([^=\s]+(?:=(?:""[^""]*?""|[^ ]*))?)", RegexOptions.Compiled));
}
}
public static CommandLineArgs ReadCefArguments(string argumentString){
CommandLineArgs args = new CommandLineArgs();
if (string.IsNullOrWhiteSpace(argumentString)){
return args;
}
foreach(Match match in SplitRegex.Matches(argumentString)){
string matchValue = match.Value;
int indexEquals = matchValue.IndexOf('=');
string key, value;
if (indexEquals == -1){
key = matchValue.TrimStart('-');
value = "1";
}
else{
key = matchValue.Substring(0, indexEquals).TrimStart('-');
value = matchValue.Substring(indexEquals+1).Trim('"');
}
if (key.Length != 0){
args.SetValue(key, value);
}
}
return args;
}
}
}
|
mit
|
C#
|
69aadd2597bae84e2f6fa6c7323ccea2ca098d51
|
Change assembly version
|
githubpermutation/skylines-scaleui,githubpermutation/skylines-scaleui
|
ScaleUI/AssemblyInfo.cs
|
ScaleUI/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("ScaleUI1.21")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("permutation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.21.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("ScaleUI1.2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("permutation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.2.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
mit
|
C#
|
0ec2077545305ef0f39344cf032f85fada9800ad
|
Combine namespace name with child namespace name.
|
AndresTraks/DotNetWrapperGen,AndresTraks/DotNetWrapperGen
|
Writer/CSharpFileWriter.cs
|
Writer/CSharpFileWriter.cs
|
using DotNetWrapperGen.CodeModel;
using DotNetWrapperGen.CodeStructure;
using DotNetWrapperGen.Parser;
using System.IO;
using System.Linq;
namespace DotNetWrapperGen.Writer
{
public class CSharpFileWriter
{
private HeaderDefinition _header;
private StreamWriter _writer;
public CSharpFileWriter(HeaderDefinition header)
{
_header = header;
}
public void Write()
{
var namespaceTree = HeaderNamespaceTree.GetTree(_header);
using (var stream = File.Create(_header.FullPath))
{
using (_writer = new StreamWriter(stream))
{
WriteNamespace(namespaceTree);
}
}
}
private void WriteNamespace(NamespaceTreeNode node)
{
string name;
if (node.Children.Count == 1 && node.Nodes.Count == 0)
{
var child = node.Children[0];
if (node.Namespace.IsGlobal)
{
name = child.Namespace.Name;
}
else
{
name = $"{node.Namespace.Name}.{child.Namespace.Name}";
}
node = child;
}
else
{
name = node.Namespace.Name;
}
var @namespace = node.Namespace;
_writer.Write("namespace ");
_writer.WriteLine(name);
_writer.WriteLine("{");
_writer.WriteLine("}");
foreach (var childNamespace in node.Children)
{
WriteNamespace(childNamespace);
}
}
}
}
|
using DotNetWrapperGen.CodeStructure;
using DotNetWrapperGen.Parser;
using System.IO;
namespace DotNetWrapperGen.Writer
{
public class CSharpFileWriter
{
private HeaderDefinition _header;
private StreamWriter _writer;
public CSharpFileWriter(HeaderDefinition header)
{
_header = header;
}
public void Write()
{
var namespaceTree = HeaderNamespaceTree.GetTree(_header);
using (var stream = File.Create(_header.FullPath))
{
using (_writer = new StreamWriter(stream))
{
WriteNamespace(namespaceTree);
}
}
}
private void WriteNamespace(NamespaceTreeNode node)
{
var @namespace = node.Namespace;
if (!@namespace.IsGlobal)
{
_writer.Write("namespace ");
_writer.WriteLine(@namespace.Name);
_writer.WriteLine("{");
_writer.WriteLine("}");
}
foreach (var childNamespace in node.Children)
{
WriteNamespace(childNamespace);
}
}
}
}
|
mit
|
C#
|
d164302633e0c1379e98343e87ad378572acdbd3
|
update copyright year
|
prodot/ReCommended-Extension
|
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
|
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
|
using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2021 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("5.3.2.0")]
[assembly: AssemblyFileVersion("5.3.2")]
|
using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("5.3.2.0")]
[assembly: AssemblyFileVersion("5.3.2")]
|
apache-2.0
|
C#
|
6073c6ec0f756db7396d4e78bb2a611554832cf9
|
Add DebugBox for debugging issues in popup windows
|
zwcloud/ImGui,zwcloud/ImGui,zwcloud/ImGui
|
src/ImGui/Development/GUIDebug.cs
|
src/ImGui/Development/GUIDebug.cs
|
using ImGui.Rendering;
namespace ImGui.Development
{
public class GUIDebug
{
public static void SetWindowPosition(string windowName, Point position)
{
var possibleWindow = Application.ImGuiContext.WindowManager.Windows.Find(window => window.Name == windowName);
if (possibleWindow != null)
{
possibleWindow.Position = position;
}
}
}
}
namespace ImGui
{
public partial class GUI
{
public static void DebugBox(int id, Rect rect, Color color)
{
var window = GetCurrentWindow();
if (window.SkipItems)
return;
//get or create the root node
var container = window.AbsoluteVisualList;
var node = (Node)container.Find(visual => visual.Id == id);
if (node == null)
{
//create node
node = new Node(id, $"DebugBox<{id}>");
node.UseBoxModel = true;
node.RuleSet.Replace(GUISkin.Current[GUIControlName.Box]);
node.RuleSet.BackgroundColor = color;
container.Add(node);
}
node.ActiveSelf = true;
// last item state
window.TempData.LastItemState = node.State;
// rect
node.Rect = window.GetRect(rect);
using (var dc = node.RenderOpen())
{
dc.DrawBoxModel(node.RuleSet, node.Rect);
}
}
}
}
|
namespace ImGui.Development
{
public class GUIDebug
{
public static void SetWindowPosition(string windowName, Point position)
{
var possibleWindow = Application.ImGuiContext.WindowManager.Windows.Find(window => window.Name == windowName);
if (possibleWindow != null)
{
possibleWindow.Position = position;
}
}
}
}
|
agpl-3.0
|
C#
|
613cbdfd274ee0d9d0e19afe1b20a5d275bd4dfa
|
fix paths
|
nessos/Vagabond,mbraceproject/Vagabond,nessos/Vagabond,mbraceproject/Vagabond
|
samples/ThunkServer/thunkServer.csx
|
samples/ThunkServer/thunkServer.csx
|
#r "bin/Debug/netcoreapp3.1/FsPickler.dll"
#r "bin/Debug/netcoreapp3.1/Vagabond.AssemblyParser.dll"
#r "bin/Debug/netcoreapp3.1/Vagabond.dll"
#r "bin/Debug/netcoreapp3.1/ThunkServer.exe"
// before running sample, don't forget to set binding redirects to FSharp.Core in InteractiveHost.exe
using System.Linq;
using ThunkServer;
ThunkClient.Executable = "bin/Debug/net45/ThunkServer.exe";
var client = ThunkClient.InitLocal();
client.EvaluateDelegate(() => Console.WriteLine("C# Interactive, meet Vagabond!"));
client.EvaluateDelegate(() => System.Diagnostics.Process.GetCurrentProcess().Id);
client.EvaluateDelegate(() => Enumerable.Range(0, 10).Select(x => x + 1).Where(x => x % 2 == 0).Sum());
int x = 1;
for (int i = 0; i < 10; i++)
x = client.EvaluateDelegate(() => x + x);
x;
|
#r "bin/Debug/netstandard2.0/FsPickler.dll"
#r "bin/Debug/netstandard2.0/Vagabond.AssemblyParser.dll"
#r "bin/Debug/netstandard2.0/Vagabond.dll"
#r "bin/Debug/netstandard2.0/ThunkServer.exe"
// before running sample, don't forget to set binding redirects to FSharp.Core in InteractiveHost.exe
using System.Linq;
using ThunkServer;
ThunkClient.Executable = "bin/Debug/net45/ThunkServer.exe";
var client = ThunkClient.InitLocal();
client.EvaluateDelegate(() => Console.WriteLine("C# Interactive, meet Vagabond!"));
client.EvaluateDelegate(() => System.Diagnostics.Process.GetCurrentProcess().Id);
client.EvaluateDelegate(() => Enumerable.Range(0, 10).Select(x => x + 1).Where(x => x % 2 == 0).Sum());
int x = 1;
for (int i = 0; i < 10; i++)
x = client.EvaluateDelegate(() => x + x);
x;
|
mit
|
C#
|
978b87887518a950b1b3f9772f9317a279f4f7fb
|
Fix InitTests.cs
|
or-tools/or-tools,google/or-tools,google/or-tools,google/or-tools,google/or-tools,or-tools/or-tools,or-tools/or-tools,google/or-tools,or-tools/or-tools,or-tools/or-tools,google/or-tools,or-tools/or-tools
|
examples/tests/InitTests.cs
|
examples/tests/InitTests.cs
|
// Copyright 2010-2021 Google LLC
// 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 Xunit;
using Google.OrTools.Init;
using static Google.OrTools.Init.operations_research_init;
namespace Google.OrTools.Tests
{
public class InitTest
{
[Fact]
public void CheckLogging()
{
Init.CppBridge.InitLogging("init");
Init.CppBridge.ShutdownLogging();
}
[Fact]
public void CheckFlags()
{
Init.CppFlags cpp_flags = new Init.CppFlags();
cpp_flags.logtostderr = true;
cpp_flags.log_prefix = true;
cpp_flags.cp_model_dump_prefix = "init";
cpp_flags.cp_model_dump_models = true;
cpp_flags.cp_model_dump_lns = true;
cpp_flags.cp_model_dump_response = true;
Init.CppBridge.SetFlags(cpp_flags);
}
[Fact]
public void CheckOrToolsVersion()
{
int major = OrToolsVersion.MajorNumber();
int minor = OrToolsVersion.MinorNumber();
int patch = OrToolsVersion.PatchNumber();
string version = OrToolsVersion.VersionString();
Assert.Equal($"{major}.{minor}.{patch}", version);
}
}
} // namespace Google.OrTools.Tests
|
// Copyright 2010-2021 Google LLC
// 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 Xunit;
using Google.OrTools.Init;
using static Google.OrTools.Init.operations_research_init;
namespace Google.OrTools.Tests
{
public class InitTest
{
[Fact]
public void CheckFlags()
{
var cpp_flags = Init.CppFlags();
cpp_flags.logtostderr = true;
cpp_flags.log_prefix = true;
cpp_flags.cp_model_dump_prefix = "init";
cpp_flags.cp_model_dump_model = true;
cpp_flags.cp_model_dump_lns = true;
cpp_flags.cp_model_dump_response = true;
Init.CppBridge.SetFlags(cpp_flags);
}
[Fact]
public void CheckFlags()
{
Init.CppBridge.InitLogging("init");
Init.CppBridge.ShutdownLogging();
}
[Fact]
public void CheckOrToolsVersion()
{
int[] input = { 5, 11, 17 };
Assert.Equal(17, intput[2]);
}
}
} // namespace Google.OrTools.Tests
|
apache-2.0
|
C#
|
9c911187a5cd4a637d49c0ee43bb08d585fb61b5
|
test commit
|
Pellared/TddKataWorkshop
|
Game/Game/Game.cs
|
Game/Game/Game.cs
|
namespace Game
{
public class Game
{
public int Add(int first, int second)
{
return first + second;
}
}
}
sadsdsd
|
namespace Game
{
public class Game
{
public int Add(int first, int second)
{
return first + second;
}
}
}
|
mit
|
C#
|
2a3360c992abcb2bfac5bf4fb395218a4e30cbb9
|
Change link and the basic layout
|
mchaloupka/DotNetR2RMLEndpoint,mchaloupka/EVI-SampleServer,mchaloupka/DotNetR2RMLEndpoint,mchaloupka/EVI-SampleServer
|
src/Slp.Evi.Server/Slp.Evi.Server/Views/Shared/_BasicLayout.cshtml
|
src/Slp.Evi.Server/Slp.Evi.Server/Views/Shared/_BasicLayout.cshtml
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta name="description" content="SPARQL Query testing page" />
<title>@ViewBag.Title</title>
@Scripts.Render("~/Content/js/jquery")
@Scripts.Render("~/Content/js/bootstrap")
@Scripts.Render("~/Content/js/base")
@Styles.Render("~/Content/css/bootstrap")
@Styles.Render("~/Content/css/style")
</head>
<body>
<div class="container">
<div class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="https://github.com/mchaloupka/EVI" target="_blank">EVI: Virtual Endpoint</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="@Url.Action("Query", "Main")">Endpoint</a></li>
<li><a href="@Url.Action("Dump", "Json")">Data Dump</a></li>
<li><a href="@Url.Action("Mapping", "Main")">R2RML Mapping</a></li>
<li><a href="@Url.Action("Sample", "Main")">Sample Queries</a></li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</div>
<div>
@RenderBody()
</div>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta name="description" content="SPARQL Query testing page" />
<title>@ViewBag.Title</title>
@Scripts.Render("~/Content/js/jquery")
@Scripts.Render("~/Content/js/bootstrap")
@Scripts.Render("~/Content/js/base")
@Styles.Render("~/Content/css/bootstrap")
@Styles.Render("~/Content/css/style")
</head>
<body>
<div class="container">
<div class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="https://bitbucket.org/slupka/dotnetr2rmlstore" target="_blank">R2RMLStore</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="@Url.Action("Query", "Main")">Endpoint</a></li>
<li><a href="@Url.Action("Dump", "Json")">Data Dump</a></li>
<li><a href="@Url.Action("Mapping", "Main")">R2RML Mapping</a></li>
<li><a href="@Url.Action("Sample", "Main")">Sample Queries</a></li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</div>
<div>
@RenderBody()
</div>
</div>
</body>
</html>
|
mit
|
C#
|
79687321d7ee2d9c01e433058cf9a8b5fba1c9a8
|
Add a check statement to stop the timer if it finishes typing
|
Parthas-Menethil/AutoTyper
|
AutoTyper/Form1.cs
|
AutoTyper/Form1.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoTyper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string Content = "``I think that it's extraordinarily important that we in computer science keep fun in computing. When it started out, it was an awful lot of fun. Of course, the paying customers got shafted every now and then, and after a while we began to take their complaints seriously. We began to feel as if we really were responsible for the successful, error-free perfect use of these machines. I don't think we are. I think we're responsible for stretching them, setting them off in new directions, and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all, I hope we don't become missionaries. Don't feel as if you're Bible salesmen. The world has too many of those already. What you know about computing other people will learn. Don't feel as if the key to successful computing is only in your hands. What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more.''\r\n\r\nAlan J. Perlis (April 1, 1922-February 7, 1990)";
private int Pointer = 0;
private void timerTyper_Tick(object sender, EventArgs e)
{
txtDemoBox.Text += Content.Substring(Pointer++, 1);
txtDemoBox.Select(txtDemoBox.Text.Length, 0);
if (Pointer >= Content.Length)
timerTyper.Enabled = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoTyper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string Content = "``I think that it's extraordinarily important that we in computer science keep fun in computing. When it started out, it was an awful lot of fun. Of course, the paying customers got shafted every now and then, and after a while we began to take their complaints seriously. We began to feel as if we really were responsible for the successful, error-free perfect use of these machines. I don't think we are. I think we're responsible for stretching them, setting them off in new directions, and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all, I hope we don't become missionaries. Don't feel as if you're Bible salesmen. The world has too many of those already. What you know about computing other people will learn. Don't feel as if the key to successful computing is only in your hands. What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more.''\r\n\r\nAlan J. Perlis (April 1, 1922-February 7, 1990)";
private int Pointer = 0;
private void timerTyper_Tick(object sender, EventArgs e)
{
txtDemoBox.Text += Content.Substring(Pointer++, 1);
txtDemoBox.Select(txtDemoBox.Text.Length, 0);
}
}
}
|
mit
|
C#
|
582e1489ffecf8ed906e784413acfd3465350e50
|
Fix Namespace on DisconnectionServiceHandler
|
HelloKitty/GladNet2,HelloKitty/GladNet2.0,HelloKitty/GladNet2,HelloKitty/GladNet2.0
|
src/GladNet.Common/Network/Peer/Connection/DefaultDisconnectionServiceHandler.cs
|
src/GladNet.Common/Network/Peer/Connection/DefaultDisconnectionServiceHandler.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GladNet.Common
{
//Stole this implementation from GladNet.PhotonServer's adapter.
//Should serve well as a simple implementation in-lieu of custom implementations
//for specific net libs.
/// <summary>
/// Default simple implementation of the <see cref="IDisconnectionServiceHandler"/> interface.
/// </summary>
public class DefaultDisconnectionServiceHandler : IDisconnectionServiceHandler
{
//TODO: Make this thread safe
/// <summary>
/// Indicates if the connection is disconnected.
/// </summary>
public bool isDisconnected { get; private set; }
/// <summary>
/// Publisher of <see cref="OnNetworkDisconnect"/> events to subscribers.
/// </summary>
public event OnNetworkDisconnect DisconnectionEventHandler;
/// <summary>
/// Creates a new adapter for the <see cref="IDisconnectionServiceHandler"/> interface.
/// </summary>
public DefaultDisconnectionServiceHandler()
{
isDisconnected = false;
}
/// <summary>
/// Disconnects the connection.
/// </summary>
public void Disconnect()
{
isDisconnected = true;
//Call subscribers for the disconnection event.
if (DisconnectionEventHandler != null)
DisconnectionEventHandler.Invoke();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GladNet.Common.Network
{
//Stole this implementation from GladNet.PhotonServer's adapter.
//Should serve well as a simple implementation in-lieu of custom implementations
//for specific net libs.
/// <summary>
/// Default simple implementation of the <see cref="IDisconnectionServiceHandler"/> interface.
/// </summary>
public class DefaultDisconnectionServiceHandler : IDisconnectionServiceHandler
{
//TODO: Make this thread safe
/// <summary>
/// Indicates if the connection is disconnected.
/// </summary>
public bool isDisconnected { get; private set; }
/// <summary>
/// Publisher of <see cref="OnNetworkDisconnect"/> events to subscribers.
/// </summary>
public event OnNetworkDisconnect DisconnectionEventHandler;
/// <summary>
/// Creates a new adapter for the <see cref="IDisconnectionServiceHandler"/> interface.
/// </summary>
public DefaultDisconnectionServiceHandler()
{
isDisconnected = false;
}
/// <summary>
/// Disconnects the connection.
/// </summary>
public void Disconnect()
{
isDisconnected = true;
//Call subscribers for the disconnection event.
if (DisconnectionEventHandler != null)
DisconnectionEventHandler.Invoke();
}
}
}
|
bsd-3-clause
|
C#
|
c9f506d4eaf002a1a67b487f900daddc1cf0530a
|
Fix #6542 - correct namespace of [TempData]
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Microsoft.AspNetCore.Mvc.ViewFeatures/TempDataAttribute.cs
|
src/Microsoft.AspNetCore.Mvc.ViewFeatures/TempDataAttribute.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;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// Properties decorated with <see cref="TempDataAttribute"/> will have their values stored in
/// and loaded from the <see cref="ViewFeatures.TempDataDictionary"/>. <see cref="TempDataAttribute"/>
/// is supported on properties of Controllers, Razor Pages, and Razor Page Page Models.
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class TempDataAttribute : Attribute
{
}
}
|
// 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;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
/// <summary>
/// Properties with the <see cref="TempDataAttribute"/> are stored in the <see cref="TempDataDictionary"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class TempDataAttribute : Attribute
{
}
}
|
apache-2.0
|
C#
|
430ce6e1e7d8579f880cafeeed1878524798e6c2
|
Remove double constructor
|
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
|
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs
|
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs
|
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; set; }
public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) : base(factory)
{
Transaction = session.BeginTransaction(isolationLevel);
}
}
}
|
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; set; }
public UnitOfWork(IDbFactory factory, ISession session) : base(factory)
{
Transaction = session.BeginTransaction();
}
public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel) : base(factory)
{
Transaction = session.BeginTransaction(isolationLevel);
}
}
}
|
mit
|
C#
|
bf4bf1c02288b8060dab0eed2f16269e4f474fee
|
clean up content repo
|
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
|
src/StockportWebapp/Repositories/ProcessedContentRepository.cs
|
src/StockportWebapp/Repositories/ProcessedContentRepository.cs
|
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using StockportWebapp.Config;
using StockportWebapp.ContentFactory;
using StockportWebapp.Http;
using StockportWebapp.Models;
using StockportWebapp.Utils;
namespace StockportWebapp.Repositories
{
public class ProcessedContentRepository : IProcessedContentRepository
{
private readonly ContentTypeFactory _contentTypeFactory;
private readonly IHttpClient _httpClient;
private readonly IStubToUrlConverter _urlGenerator;
private readonly IApplicationConfiguration _config;
private readonly Dictionary<string, string> authenticationHeaders;
public ProcessedContentRepository(IStubToUrlConverter urlGenerator, IHttpClient httpClient, ContentTypeFactory contentTypeFactory, IApplicationConfiguration config)
{
_urlGenerator = urlGenerator;
_httpClient = httpClient;
_contentTypeFactory = contentTypeFactory;
_config = config;
authenticationHeaders = new Dictionary<string, string> { { "Authorization", _config.GetContentApiAuthenticationKey() }, { "X-ClientId", _config.GetWebAppClientId() } };
}
public async Task<HttpResponse> Get<T>(string slug = "", List<Query> queries = null)
{
var url = _urlGenerator.UrlFor<T>(slug, queries);
var httpResponse = await _httpClient.Get(url, authenticationHeaders);
if (!httpResponse.IsSuccessful())
{
return httpResponse;
}
var model = HttpResponse.Build<T>(httpResponse);
var processedModel = _contentTypeFactory.Build((T)model.Content);
return HttpResponse.Successful(200, processedModel);
}
}
}
|
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using StockportWebapp.Config;
using StockportWebapp.ContentFactory;
using StockportWebapp.Http;
using StockportWebapp.Models;
using StockportWebapp.Utils;
namespace StockportWebapp.Repositories
{
public class ProcessedContentRepository : IProcessedContentRepository
{
private readonly ContentTypeFactory _contentTypeFactory;
private readonly IHttpClient _httpClient;
private readonly IStubToUrlConverter _urlGenerator;
private readonly IApplicationConfiguration _config;
private readonly Dictionary<string, string> authenticationHeaders;
public ProcessedContentRepository(IStubToUrlConverter urlGenerator, IHttpClient httpClient, ContentTypeFactory contentTypeFactory, IApplicationConfiguration config)
{
_urlGenerator = urlGenerator;
_httpClient = httpClient;
_contentTypeFactory = contentTypeFactory;
_config = config;
authenticationHeaders = new Dictionary<string, string> { { "Authorization", _config.GetContentApiAuthenticationKey() }, { "X-ClientId", _config.GetWebAppClientId() } };
}
public async Task<HttpResponse> Get<T>(string slug = "", List<Query> queries = null)
{
//var testClientHandeler = new HttpClientHandler { Proxy = null };
//var testClient = new System.Net.Http.HttpClient(testClientHandeler);
var url = _urlGenerator.UrlFor<T>(slug, queries);
var httpResponse = await _httpClient.Get(url, authenticationHeaders);
if (!httpResponse.IsSuccessful()) {
return httpResponse;
}
var model = HttpResponse.Build<T>(httpResponse);
var processedModel = _contentTypeFactory.Build((T)model.Content);
return HttpResponse.Successful(200, processedModel);
}
}
}
|
mit
|
C#
|
e01443b18e32244685f3da0c698c986513571af2
|
revert showing exceptions
|
ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian
|
test/Obsidian.Persistence.Test/Repositories/MongoRepositoryTest.cs
|
test/Obsidian.Persistence.Test/Repositories/MongoRepositoryTest.cs
|
using MongoDB.Driver;
using Obsidian.Foundation.Modeling;
using System;
namespace Obsidian.Persistence.Test.Repositories
{
public abstract class MongoRepositoryTest<TAggregate> : RepositoryTest<TAggregate> where TAggregate : class, IAggregateRoot
{
private const string dbUri = "mongodb://127.0.0.1:27017";
private readonly string testDbName = "ObsidianTest_" + Guid.NewGuid();
private IMongoClient client;
private IMongoDatabase _db;
private void InitializeDatabase()
{
client = new MongoClient(dbUri);
_db = client.GetDatabase(testDbName);
}
protected override void InitializeContext()
{
InitializeDatabase();
base.InitializeContext();
}
protected IMongoDatabase Database => _db;
protected override void CleanupDatabase() => client.DropDatabase(testDbName);
}
}
|
using MongoDB.Driver;
using Obsidian.Foundation.Modeling;
using System;
namespace Obsidian.Persistence.Test.Repositories
{
public abstract class MongoRepositoryTest<TAggregate> : RepositoryTest<TAggregate> where TAggregate : class, IAggregateRoot
{
private const string dbUri = "mongodb://127.0.0.1:27017";
private readonly string testDbName = "ObsidianTest_" + Guid.NewGuid();
private IMongoClient client;
private IMongoDatabase _db;
private void InitializeDatabase()
{
client = new MongoClient(dbUri);
_db = client.GetDatabase(testDbName);
}
protected override void InitializeContext()
{
InitializeDatabase();
base.InitializeContext();
}
protected IMongoDatabase Database => _db;
protected override void CleanupDatabase()
{
try
{
client.Cluster.Initialize();
client.DropDatabase(testDbName);
}
catch (TimeoutException ex)
{
Console.WriteLine(ex.InnerException?.ToString() ?? "[No InnerException]");
throw;
}
}
}
}
|
apache-2.0
|
C#
|
54fc9f725d18df58795eab329997a384c13f6dbd
|
rephrase comment
|
StefanoFiumara/Harry-Potter-Unity
|
Assets/Scripts/HarryPotterUnity/Cards/BaseSpell.cs
|
Assets/Scripts/HarryPotterUnity/Cards/BaseSpell.cs
|
using System.Collections.Generic;
using HarryPotterUnity.Enums;
using HarryPotterUnity.Game;
using HarryPotterUnity.Tween;
using HarryPotterUnity.Utils;
using UnityEngine;
namespace HarryPotterUnity.Cards
{
public abstract class BaseSpell : BaseCard {
private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f);
protected sealed override void OnClickAction(List<BaseCard> targets)
{
Enable();
PreviewSpell();
Player.Discard.Add(this);
SpellAction(targets);
}
protected abstract void SpellAction(List<BaseCard> targets);
private void PreviewSpell()
{
//TODO: Why is the State set here and in the callback?
State = State.Discarded;
var rotateType = Player.OppositePlayer.IsLocalPlayer ? TweenRotationType.Rotate180 : TweenRotationType.NoRotate;
var tween = new MoveTween
{
Target = gameObject,
Position = SpellOffset,
Time = 0.5f,
Flip = FlipState.FaceUp,
Rotate = rotateType,
OnCompleteCallback = () => State = State.Discarded,
TimeUntilNextTween = 0.6f
};
GameManager.TweenQueue.AddTweenToQueue(tween);
}
protected override Type GetCardType()
{
return Type.Spell;
}
}
}
|
using System.Collections.Generic;
using HarryPotterUnity.Enums;
using HarryPotterUnity.Game;
using HarryPotterUnity.Tween;
using HarryPotterUnity.Utils;
using UnityEngine;
namespace HarryPotterUnity.Cards
{
public abstract class BaseSpell : BaseCard {
private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f);
protected sealed override void OnClickAction(List<BaseCard> targets)
{
Enable();
PreviewSpell();
Player.Discard.Add(this);
SpellAction(targets);
}
protected abstract void SpellAction(List<BaseCard> targets);
private void PreviewSpell()
{
//TODO: Investigate why we're setting the state once here and in the callback
State = State.Discarded;
var rotateType = Player.OppositePlayer.IsLocalPlayer ? TweenRotationType.Rotate180 : TweenRotationType.NoRotate;
var tween = new MoveTween
{
Target = gameObject,
Position = SpellOffset,
Time = 0.5f,
Flip = FlipState.FaceUp,
Rotate = rotateType,
OnCompleteCallback = () => State = State.Discarded,
TimeUntilNextTween = 0.6f
};
GameManager.TweenQueue.AddTweenToQueue(tween);
}
protected override Type GetCardType()
{
return Type.Spell;
}
}
}
|
mit
|
C#
|
3234eeb05ac35be530e0f6333c2e39549961f815
|
fix exception documentation bug
|
OBeautifulCode/OBeautifulCode.AccountingTime
|
OBeautifulCode.AccountingTime/ReportingPeriod/ReportingPeriod{T}.cs
|
OBeautifulCode.AccountingTime/ReportingPeriod/ReportingPeriod{T}.cs
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReportingPeriod{T}.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
// ReSharper disable CheckNamespace
namespace OBeautifulCode.AccountingTime
{
using System;
/// <summary>
/// Represents a range of time over which to report.
/// </summary>
/// <typeparam name="T">The unit-of-time used to define the start and end of the reporting period.</typeparam>
public abstract class ReportingPeriod<T>
where T : UnitOfTime
{
/// <summary>
/// Initializes a new instance of the <see cref="ReportingPeriod{T}"/> class.
/// </summary>
/// <param name="start">The start of the reporting period.</param>
/// <param name="end">The end of the reporting period.</param>
/// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> are null.</exception>
/// <exception cref="ArgumentException"><paramref name="start"/> and <paramref name="end"/> are not of the same type.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> is greater than <paramref name="end"/>.</exception>
protected ReportingPeriod(T start, T end)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
if (end == null)
{
throw new ArgumentNullException(nameof(end));
}
if (start.GetType() != end.GetType())
{
throw new ArgumentException("start and end are different kinds of units-of-time");
}
if ((dynamic)start > (dynamic)end)
{
throw new ArgumentOutOfRangeException(nameof(start), "start is great than end");
}
this.Start = start;
this.End = end;
}
/// <summary>
/// Gets the start of the reporting period.
/// </summary>
public T Start { get; private set; }
/// <summary>
/// Gets the end of the reporting period.
/// </summary>
public T End { get; private set; }
}
}
// ReSharper restore CheckNamespace
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReportingPeriod{T}.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
// ReSharper disable CheckNamespace
namespace OBeautifulCode.AccountingTime
{
using System;
/// <summary>
/// Represents a range of time over which to report.
/// </summary>
/// <typeparam name="T">The unit-of-time used to define the start and end of the reporting period.</typeparam>
public abstract class ReportingPeriod<T>
where T : UnitOfTime
{
/// <summary>
/// Initializes a new instance of the <see cref="ReportingPeriod{T}"/> class.
/// </summary>
/// <param name="start">The start of the reporting period.</param>
/// <param name="end">The end of the reporting period.</param>
/// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> are null.</exception>
/// <exception cref="ArgumentException"><paramref name="start"/> and <paramref name="end"/> are not of the same type.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> must be less than equal to <paramref name="end"/>.</exception>
protected ReportingPeriod(T start, T end)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
if (end == null)
{
throw new ArgumentNullException(nameof(end));
}
if (start.GetType() != end.GetType())
{
throw new ArgumentException("start and end are different kinds of units-of-time");
}
if ((dynamic)start > (dynamic)end)
{
throw new ArgumentOutOfRangeException(nameof(start), "start is great than end");
}
this.Start = start;
this.End = end;
}
/// <summary>
/// Gets the start of the reporting period.
/// </summary>
public T Start { get; private set; }
/// <summary>
/// Gets the end of the reporting period.
/// </summary>
public T End { get; private set; }
}
}
// ReSharper restore CheckNamespace
|
mit
|
C#
|
e23bc4cf29afc7f4cd9d15a02ae75326a3ca5d4f
|
allow overriding separator in ConcatenatedScript
|
WasimAhmad/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity
|
Serenity.Web/DynamicScript/DynamicScriptTypes/ConcatenatedScript.cs
|
Serenity.Web/DynamicScript/DynamicScriptTypes/ConcatenatedScript.cs
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Serenity.Web
{
public class ConcatenatedScript : DynamicScript
{
private string separator;
private IEnumerable<Func<string>> scriptParts;
public ConcatenatedScript(IEnumerable<Func<string>> scriptParts,
string separator = "\r\n;\r\n")
{
Check.NotNull(scriptParts, "scriptParts");
this.scriptParts = scriptParts;
this.separator = separator;
}
public override string GetScript()
{
StringBuilder sb = new StringBuilder();
foreach (var part in scriptParts)
{
string partSource = part();
sb.AppendLine(partSource);
if (!string.IsNullOrEmpty(separator))
sb.AppendLine(separator);
}
return sb.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Serenity.Web
{
public class ConcatenatedScript : DynamicScript
{
private IEnumerable<Func<string>> scriptParts;
public ConcatenatedScript(IEnumerable<Func<string>> scriptParts)
{
Check.NotNull(scriptParts, "scriptParts");
this.scriptParts = scriptParts;
}
public override string GetScript()
{
StringBuilder sb = new StringBuilder();
foreach (var part in scriptParts)
{
string partSource = part();
sb.AppendLine(partSource);
sb.AppendLine("\r\n;\r\n");
}
return sb.ToString();
}
}
}
|
mit
|
C#
|
0494f59f4d4c627c77910e3e2ca6c9380c68b95e
|
fix compile error
|
RyotaMurohoshi/unity_snippets
|
unity/Assets/Scripts/Examples/CustomYieldInstructionExample.cs
|
unity/Assets/Scripts/Examples/CustomYieldInstructionExample.cs
|
using UnityEngine;
using System.Collections;
using System;
public class CustomYieldInstructionExample : MonoBehaviour
{
[SerializeField]
bool waitUntil = false;
[SerializeField]
bool waitWhile = true;
void Start()
{
StartCoroutine(WaitUntilCoroutine());
StartCoroutine(WaitWhileCoroutine());
StartCoroutine(RepeatMyWaitForSecondsCoroutine(count: 3, seconds:1.0F));
}
IEnumerator WaitUntilCoroutine()
{
Debug.Log("WaitUntilCoroutine Begin");
yield return new WaitUntil(() => waitUntil);
Debug.Log("WaitUntilCoroutine Finish");
}
IEnumerator WaitWhileCoroutine()
{
Debug.Log("WaitWhileCoroutine Begin");
yield return new WaitWhile(() => waitWhile);
Debug.Log("WaitWhileCoroutine Finish");
}
IEnumerator MyWaitForSecondsCoroutine(float seconds)
{
Debug.Log("MyWaitForSecondsCoroutine Begin : " + System.DateTime.Now);
yield return new MyWaitForSeconds(seconds);
Debug.Log("MyWaitForSecondsCoroutine Finish : " + System.DateTime.Now);
}
IEnumerator RepeatMyWaitForSecondsCoroutine(int count, float seconds)
{
for(int i = 0; i < count; i++)
{
yield return MyWaitForSecondsCoroutine(seconds);
}
}
}
|
using UnityEngine;
using System.Collections;
using System;
public class CustomYieldInstructionExample : MonoBehaviour
{
[SerializeField]
bool waitUntil = false;
[SerializeField]
bool waitWhile = true;
void Start()
{
StartCoroutine(WaitUntilCoroutine());
StartCoroutine(WaitWhileCoroutine());
<<<<<<< 4c8db37d471b502ea05afde7ed54f4f7bcc2d007
StartCoroutine(MyWaitForSecondsCoroutine());
=======
StartCoroutine(RepeatMyWaitForSecondsCoroutine(count: 3, seconds:1.0F));
>>>>>>> created MyWaitForSeconds
}
IEnumerator WaitUntilCoroutine()
{
Debug.Log("WaitUntilCoroutine Begin");
yield return new WaitUntil(() => waitUntil);
Debug.Log("WaitUntilCoroutine Finish");
}
IEnumerator WaitWhileCoroutine()
{
Debug.Log("WaitWhileCoroutine Begin");
yield return new WaitWhile(() => waitWhile);
Debug.Log("WaitWhileCoroutine Finish");
}
<<<<<<< 4c8db37d471b502ea05afde7ed54f4f7bcc2d007
IEnumerator MyWaitForSecondsCoroutine()
{
Debug.Log("MyWaitForSecondsCoroutine Begin : " + System.DateTime.Now);
yield return new MyWaitForSeconds(5.0F);
Debug.Log("MyWaitForSecondsCoroutine Finish : " + System.DateTime.Now);
}
=======
IEnumerator MyWaitForSecondsCoroutine(float seconds)
{
Debug.Log("MyWaitForSecondsCoroutine Begin : " + System.DateTime.Now);
yield return new MyWaitForSeconds(seconds);
Debug.Log("MyWaitForSecondsCoroutine Finish : " + System.DateTime.Now);
}
IEnumerator RepeatMyWaitForSecondsCoroutine(int count, float seconds)
{
for(int i = 0; i < count; i++)
{
yield return MyWaitForSecondsCoroutine(seconds);
}
}
>>>>>>> created MyWaitForSeconds
}
|
mit
|
C#
|
4b6212d5b248e3a8738ee088b884ca77381a7720
|
Make File/DirInfo independent of current directory
|
bkoelman/TestableFileSystem
|
src/Fakes/FakeFileSystem.cs
|
src/Fakes/FakeFileSystem.cs
|
using System.IO;
using JetBrains.Annotations;
using TestableFileSystem.Interfaces;
namespace TestableFileSystem.Fakes
{
public sealed class FakeFileSystem : IFileSystem
{
[NotNull]
private readonly FileOperationLocker<FakeFile> innerFile;
public IDirectory Directory { get; }
public IFile File => innerFile;
[NotNull]
internal readonly object TreeLock = new object();
[NotNull]
internal CurrentDirectoryManager CurrentDirectory { get; }
public FakeFileSystem([NotNull] DirectoryEntry rootEntry)
{
Guard.NotNull(rootEntry, nameof(rootEntry));
CurrentDirectory = new CurrentDirectoryManager(rootEntry);
Directory = new DirectoryOperationLocker(this, new FakeDirectory(rootEntry, this));
innerFile = new FileOperationLocker<FakeFile>(this, new FakeFile(rootEntry, this));
}
public IFileInfo ConstructFileInfo(string fileName)
{
var absolutePath = ToAbsolutePath(fileName);
return new FakeFileInfo(this, absolutePath.GetText());
}
public IDirectoryInfo ConstructDirectoryInfo(string path)
{
var absolutePath = ToAbsolutePath(path);
return new FakeDirectoryInfo(this, absolutePath.GetText());
}
[NotNull]
internal AbsolutePath ToAbsolutePath([NotNull] string path)
{
// TODO: How to handle when caller passes a path like "e:file.txt"?
if (string.IsNullOrWhiteSpace(path))
{
throw ErrorFactory.PathIsNotLegal(nameof(path));
}
DirectoryEntry baseDirectory = CurrentDirectory.GetValue();
string basePath = baseDirectory.GetAbsolutePath();
string rooted = Path.Combine(basePath, path.TrimEnd());
return new AbsolutePath(rooted);
}
internal long GetFileSize([NotNull] string path)
{
return innerFile.ExecuteOnFile(f => f.GetSize(path));
}
}
}
|
using System.IO;
using JetBrains.Annotations;
using TestableFileSystem.Interfaces;
namespace TestableFileSystem.Fakes
{
public sealed class FakeFileSystem : IFileSystem
{
[NotNull]
private readonly FileOperationLocker<FakeFile> innerFile;
public IDirectory Directory { get; }
public IFile File => innerFile;
[NotNull]
internal readonly object TreeLock = new object();
[NotNull]
internal CurrentDirectoryManager CurrentDirectory { get; }
public FakeFileSystem([NotNull] DirectoryEntry rootEntry)
{
Guard.NotNull(rootEntry, nameof(rootEntry));
CurrentDirectory = new CurrentDirectoryManager(rootEntry);
Directory = new DirectoryOperationLocker(this, new FakeDirectory(rootEntry, this));
innerFile = new FileOperationLocker<FakeFile>(this, new FakeFile(rootEntry, this));
}
public IFileInfo ConstructFileInfo(string fileName)
{
// TODO: Convert to absolute path, so that destination does not change when current directory changes.
return new FakeFileInfo(this, fileName);
}
public IDirectoryInfo ConstructDirectoryInfo(string path)
{
// TODO: Convert to absolute path, so that destination does not change when current directory changes.
return new FakeDirectoryInfo(this, path);
}
[NotNull]
internal AbsolutePath ToAbsolutePath([NotNull] string path)
{
// TODO: How to handle when caller passes a path like "e:file.txt"?
if (string.IsNullOrWhiteSpace(path))
{
throw ErrorFactory.PathIsNotLegal(nameof(path));
}
DirectoryEntry baseDirectory = CurrentDirectory.GetValue();
string basePath = baseDirectory.GetAbsolutePath();
string rooted = Path.Combine(basePath, path.TrimEnd());
return new AbsolutePath(rooted);
}
internal long GetFileSize([NotNull] string path)
{
return innerFile.ExecuteOnFile(f => f.GetSize(path));
}
}
}
|
apache-2.0
|
C#
|
5de402c28d1c6a7b26127174032025649bf83324
|
Allow stats type 3 for status bar info. No support yet, just avoid showing an error.
|
uoinfusion/Infusion
|
Infusion/Packets/Server/StatusBarInfoPacket.cs
|
Infusion/Packets/Server/StatusBarInfoPacket.cs
|
using System;
using Infusion.IO;
namespace Infusion.Packets.Server
{
internal sealed class StatusBarInfoPacket : MaterializedPacket
{
private Packet rawPacket;
public ObjectId PlayerId { get; private set; }
public string PlayerName { get; private set; }
public ushort CurrentHealth { get; private set; }
public ushort MaxHealth { get; private set; }
public ushort CurrentStamina { get; private set; }
public ushort MaxStamina { get; private set; }
public ushort CurrentMana { get; private set; }
public ushort MaxMana { get; private set; }
public uint Gold { get; private set; }
public ushort Weight { get; private set; }
public ushort Strength { get; private set; }
public ushort Dexterity { get; private set; }
public ushort Intelligence { get; private set; }
public ushort Armor { get; private set; }
public bool CanRename { get; private set; }
public override Packet RawPacket => rawPacket;
public byte Status { get; private set; }
public override void Deserialize(Packet rawPacket)
{
this.rawPacket = rawPacket;
var reader = new ArrayPacketReader(rawPacket.Payload);
reader.Skip(3);
PlayerId = reader.ReadObjectId();
PlayerName = reader.ReadString(30);
CurrentHealth = reader.ReadUShort();
MaxHealth = reader.ReadUShort();
CanRename = reader.ReadBool();
var validStats = reader.ReadByte(); // status flag / valid stats
if (validStats == 0)
return;
if (validStats != 1 && validStats != 3 && validStats != 7 && validStats != 4 && validStats != 6 && validStats != 5)
throw new NotImplementedException($"unknown validStats {validStats}");
reader.ReadByte(); // sex + race
Strength = reader.ReadUShort();
Dexterity = reader.ReadUShort();
Intelligence = reader.ReadUShort();
CurrentStamina = reader.ReadUShort();
MaxStamina = reader.ReadUShort();
CurrentMana = reader.ReadUShort();
MaxMana = reader.ReadUShort();
Gold = reader.ReadUInt();
Armor = reader.ReadUShort();
Weight = reader.ReadUShort();
}
}
}
|
using System;
using Infusion.IO;
namespace Infusion.Packets.Server
{
internal sealed class StatusBarInfoPacket : MaterializedPacket
{
private Packet rawPacket;
public ObjectId PlayerId { get; private set; }
public string PlayerName { get; private set; }
public ushort CurrentHealth { get; private set; }
public ushort MaxHealth { get; private set; }
public ushort CurrentStamina { get; private set; }
public ushort MaxStamina { get; private set; }
public ushort CurrentMana { get; private set; }
public ushort MaxMana { get; private set; }
public uint Gold { get; private set; }
public ushort Weight { get; private set; }
public ushort Strength { get; private set; }
public ushort Dexterity { get; private set; }
public ushort Intelligence { get; private set; }
public ushort Armor { get; private set; }
public bool CanRename { get; private set; }
public override Packet RawPacket => rawPacket;
public byte Status { get; private set; }
public override void Deserialize(Packet rawPacket)
{
this.rawPacket = rawPacket;
var reader = new ArrayPacketReader(rawPacket.Payload);
reader.Skip(3);
PlayerId = reader.ReadObjectId();
PlayerName = reader.ReadString(30);
CurrentHealth = reader.ReadUShort();
MaxHealth = reader.ReadUShort();
CanRename = reader.ReadBool();
var validStats = reader.ReadByte(); // status flag / valid stats
if (validStats == 0)
return;
if (validStats != 1 && validStats != 7 && validStats != 4 && validStats != 6 && validStats != 5)
throw new NotImplementedException($"unknown validStats {validStats}");
reader.ReadByte(); // sex + race
Strength = reader.ReadUShort();
Dexterity = reader.ReadUShort();
Intelligence = reader.ReadUShort();
CurrentStamina = reader.ReadUShort();
MaxStamina = reader.ReadUShort();
CurrentMana = reader.ReadUShort();
MaxMana = reader.ReadUShort();
Gold = reader.ReadUInt();
Armor = reader.ReadUShort();
Weight = reader.ReadUShort();
}
}
}
|
mit
|
C#
|
ab5e973abac7afcdce0388cb497e59a4ac13d283
|
Debug NuGet on Jenkins
|
Hosch250/roslyn,balajikris/roslyn,MatthieuMEZIL/roslyn,MichalStrehovsky/roslyn,ljw1004/roslyn,KevinH-MS/roslyn,drognanar/roslyn,KiloBravoLima/roslyn,DustinCampbell/roslyn,tmeschter/roslyn,ErikSchierboom/roslyn,reaction1989/roslyn,physhi/roslyn,balajikris/roslyn,TyOverby/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,jaredpar/roslyn,VSadov/roslyn,agocke/roslyn,jasonmalinowski/roslyn,aelij/roslyn,eriawan/roslyn,vcsjones/roslyn,leppie/roslyn,cston/roslyn,bkoelman/roslyn,jhendrixMSFT/roslyn,akrisiun/roslyn,khyperia/roslyn,jamesqo/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,ericfe-ms/roslyn,jhendrixMSFT/roslyn,heejaechang/roslyn,basoundr/roslyn,MattWindsor91/roslyn,AnthonyDGreen/roslyn,a-ctor/roslyn,TyOverby/roslyn,CaptainHayashi/roslyn,Shiney/roslyn,budcribar/roslyn,AmadeusW/roslyn,jmarolf/roslyn,rgani/roslyn,mgoertz-msft/roslyn,jeffanders/roslyn,drognanar/roslyn,zooba/roslyn,mattscheffer/roslyn,Giftednewt/roslyn,swaroop-sridhar/roslyn,KiloBravoLima/roslyn,Shiney/roslyn,brettfo/roslyn,tmeschter/roslyn,AnthonyDGreen/roslyn,yeaicc/roslyn,VSadov/roslyn,amcasey/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,xoofx/roslyn,agocke/roslyn,basoundr/roslyn,khellang/roslyn,jasonmalinowski/roslyn,orthoxerox/roslyn,tmat/roslyn,AArnott/roslyn,khellang/roslyn,mavasani/roslyn,tvand7093/roslyn,kelltrick/roslyn,agocke/roslyn,xasx/roslyn,bkoelman/roslyn,SeriaWei/roslyn,bbarry/roslyn,ValentinRueda/roslyn,xasx/roslyn,aelij/roslyn,a-ctor/roslyn,orthoxerox/roslyn,tvand7093/roslyn,vslsnap/roslyn,tannergooding/roslyn,mattwar/roslyn,gafter/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,AmadeusW/roslyn,reaction1989/roslyn,jeffanders/roslyn,wvdd007/roslyn,heejaechang/roslyn,srivatsn/roslyn,weltkante/roslyn,xoofx/roslyn,SeriaWei/roslyn,vcsjones/roslyn,balajikris/roslyn,basoundr/roslyn,weltkante/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,natidea/roslyn,diryboy/roslyn,stephentoub/roslyn,physhi/roslyn,akrisiun/roslyn,gafter/roslyn,sharadagrawal/Roslyn,MichalStrehovsky/roslyn,Hosch250/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,ericfe-ms/roslyn,ericfe-ms/roslyn,tmat/roslyn,ljw1004/roslyn,budcribar/roslyn,genlu/roslyn,jkotas/roslyn,Giftednewt/roslyn,abock/roslyn,orthoxerox/roslyn,jasonmalinowski/roslyn,OmarTawfik/roslyn,natgla/roslyn,ErikSchierboom/roslyn,ValentinRueda/roslyn,khyperia/roslyn,diryboy/roslyn,robinsedlaczek/roslyn,robinsedlaczek/roslyn,mavasani/roslyn,tmeschter/roslyn,xasx/roslyn,mattscheffer/roslyn,sharwell/roslyn,nguerrera/roslyn,zooba/roslyn,weltkante/roslyn,kelltrick/roslyn,genlu/roslyn,jaredpar/roslyn,jamesqo/roslyn,eriawan/roslyn,khyperia/roslyn,wvdd007/roslyn,diryboy/roslyn,genlu/roslyn,budcribar/roslyn,pdelvo/roslyn,jeffanders/roslyn,bartdesmet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,nguerrera/roslyn,jamesqo/roslyn,lorcanmooney/roslyn,DustinCampbell/roslyn,Hosch250/roslyn,AlekseyTs/roslyn,cston/roslyn,AnthonyDGreen/roslyn,natgla/roslyn,yeaicc/roslyn,mattscheffer/roslyn,khellang/roslyn,mavasani/roslyn,mattwar/roslyn,robinsedlaczek/roslyn,vslsnap/roslyn,MichalStrehovsky/roslyn,xoofx/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,dpoeschl/roslyn,drognanar/roslyn,panopticoncentral/roslyn,Giftednewt/roslyn,wvdd007/roslyn,brettfo/roslyn,CaptainHayashi/roslyn,jkotas/roslyn,Pvlerick/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,TyOverby/roslyn,tannergooding/roslyn,natidea/roslyn,jkotas/roslyn,dotnet/roslyn,eriawan/roslyn,MattWindsor91/roslyn,KevinRansom/roslyn,paulvanbrenk/roslyn,akrisiun/roslyn,davkean/roslyn,MatthieuMEZIL/roslyn,vcsjones/roslyn,natgla/roslyn,sharadagrawal/Roslyn,bartdesmet/roslyn,mmitche/roslyn,dotnet/roslyn,bbarry/roslyn,OmarTawfik/roslyn,panopticoncentral/roslyn,srivatsn/roslyn,rgani/roslyn,vslsnap/roslyn,lorcanmooney/roslyn,jmarolf/roslyn,jcouv/roslyn,mmitche/roslyn,amcasey/roslyn,paulvanbrenk/roslyn,KirillOsenkov/roslyn,bbarry/roslyn,VSadov/roslyn,panopticoncentral/roslyn,KevinH-MS/roslyn,dotnet/roslyn,jaredpar/roslyn,KiloBravoLima/roslyn,MattWindsor91/roslyn,tannergooding/roslyn,dpoeschl/roslyn,jcouv/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,natidea/roslyn,jcouv/roslyn,Pvlerick/roslyn,AArnott/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,CaptainHayashi/roslyn,lorcanmooney/roslyn,OmarTawfik/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,cston/roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,leppie/roslyn,DustinCampbell/roslyn,mattwar/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,sharwell/roslyn,Shiney/roslyn,yeaicc/roslyn,aelij/roslyn,Pvlerick/roslyn,michalhosala/roslyn,reaction1989/roslyn,michalhosala/roslyn,pdelvo/roslyn,srivatsn/roslyn,sharadagrawal/Roslyn,kelltrick/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,amcasey/roslyn,tmat/roslyn,ljw1004/roslyn,pdelvo/roslyn,bkoelman/roslyn,KevinH-MS/roslyn,AArnott/roslyn,tvand7093/roslyn,MatthieuMEZIL/roslyn,physhi/roslyn,dpoeschl/roslyn,abock/roslyn,a-ctor/roslyn,mmitche/roslyn,paulvanbrenk/roslyn,rgani/roslyn,jhendrixMSFT/roslyn,michalhosala/roslyn,leppie/roslyn,ValentinRueda/roslyn,zooba/roslyn,brettfo/roslyn,abock/roslyn,SeriaWei/roslyn
|
src/Tools/Source/RunTests/Logger.cs
|
src/Tools/Source/RunTests/Logger.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RunTests
{
internal static class Logger
{
private static readonly List<string> s_lines = new List<string>();
internal static void Log(string line)
{
lock (s_lines)
{
Console.WriteLine(line);
s_lines.Add(line);
}
}
internal static void Finish()
{
var logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "runtests.text");
lock (s_lines)
{
File.WriteAllLines(logFilePath, s_lines.ToArray());
s_lines.Clear();
}
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RunTests
{
internal static class Logger
{
private static readonly List<string> s_lines = new List<string>();
internal static void Log(string line)
{
lock (s_lines)
{
s_lines.Add(line);
}
}
internal static void Finish()
{
var logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "runtests.text");
lock (s_lines)
{
File.WriteAllLines(logFilePath, s_lines.ToArray());
s_lines.Clear();
}
}
}
}
|
apache-2.0
|
C#
|
801b97703ddd4400d77c9e0ffb1915f59d04ecc5
|
Fix Triangle intersection test.
|
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
|
Triangle.cs
|
Triangle.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChamberLib
{
public struct Triangle
{
public Triangle(Vector3 v1, Vector3 v2, Vector3 v3)
{
V1 = v1;
V2 = v2;
V3 = v3;
}
public readonly Vector3 V1;
public readonly Vector3 V2;
public readonly Vector3 V3;
public Plane ToPlane()
{
return Plane.FromPoints(V1, V2, V3);
}
public float Area
{
get
{
var ab = V2 - V1;
var ac = V3 - V1;
return Vector3.Cross(ab, ac).Length() / 2;
}
}
public bool Intersects(Ray ray)
{
var p = this.ToPlane().Intersects(ray);
if (!p.HasValue) return false;
var n21 = V2 - V1;
var n31 = V3 - V1;
var pv = p.Value;
var np = pv - V1;
var s21 = np.Dot(n21) / n21.LengthSquared();
if (s21 < 0 || s21 > 1) return false;
var s31 = np.Dot(n31) / n31.LengthSquared();
if (s31 < 0 || s31 > 1) return false;
if (s21 + s31 > 1) return false;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChamberLib
{
public struct Triangle
{
public Triangle(Vector3 v1, Vector3 v2, Vector3 v3)
{
V1 = v1;
V2 = v2;
V3 = v3;
}
public readonly Vector3 V1;
public readonly Vector3 V2;
public readonly Vector3 V3;
public Plane ToPlane()
{
return Plane.FromPoints(V1, V2, V3);
}
public float Area
{
get
{
var ab = V2 - V1;
var ac = V3 - V1;
return Vector3.Cross(ab, ac).Length() / 2;
}
}
public bool Intersects(Ray ray)
{
var p = this.ToPlane().Intersects(ray);
if (!p.HasValue) return false;
var n21 = V2 - V1;
var n31 = V3 - V1;
var pv = p.Value;
var np = pv - V1;
var s21 = np.Dot(n21);
if (s21 < 0 || s21 > 1) return false;
var s31 = np.Dot(n31);
if (s31 < 0 || s31 > 1) return false;
if (s21 + s31 > 1) return false;
return true;
}
}
}
|
lgpl-2.1
|
C#
|
fca102655ea12961e18e03e616adc3bdff6c0817
|
Add ExitMode comments
|
jkoritzinsky/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex
|
src/Avalonia.Controls/ExitMode.cs
|
src/Avalonia.Controls/ExitMode.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.
namespace Avalonia
{
/// <summary>
/// Enum for ExitMode
/// </summary>
public enum ExitMode
{
/// <summary>
/// Indicates an implicit call to Application.Exit when the last window closes.
/// </summary>
OnLastWindowClose,
/// <summary>
/// Indicates an implicit call to Application.Exit when the main window closes.
/// </summary>
OnMainWindowClose,
/// <summary>
/// Indicates that the application only exits on an explicit call to Application.Exit.
/// </summary>
OnExplicitExit
}
}
|
// 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.
namespace Avalonia
{
public enum ExitMode
{
OnLastWindowClose,
OnMainWindowClose,
OnExplicitExit
}
}
|
mit
|
C#
|
21406bf1164fe163d1ee6c9a3171e8df7b47a618
|
Initialise abbreviations on a background thread
|
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
|
resharper/resharper-unity/src/CSharp/Psi/Naming/Settings/AbbreviationsSettingsProvider.cs
|
resharper/resharper-unity/src/CSharp/Psi/Naming/Settings/AbbreviationsSettingsProvider.cs
|
using System.IO;
using JetBrains.Application.Settings;
using JetBrains.Application.Settings.Implementation;
using JetBrains.Application.Threading;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Settings;
using JetBrains.ReSharper.Psi.CSharp.Naming2;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Naming.Settings
{
[SolutionComponent]
public class AbbreviationsSettingsProvider : IUnitySolutionSettingsProvider
{
private readonly ISettingsSchema mySettingsSchema;
private readonly IThreading myThreading;
private readonly ILogger myLogger;
public AbbreviationsSettingsProvider(ISettingsSchema settingsSchema, IThreading threading, ILogger logger)
{
mySettingsSchema = settingsSchema;
myThreading = threading;
myLogger = logger;
}
public void InitialiseSolutionSettings(ISettingsStorageMountPoint mountPoint)
{
// This is called on the main thread, load the settings and initialise in the background
myThreading.Tasks.Factory.StartNew(() =>
{
var streamName = GetType().Namespace + ".Abbreviations.txt";
var stream = GetType().Assembly.GetManifestResourceStream(streamName);
if (stream == null)
{
myLogger.Warn($"Cannot load resource stream: {streamName}");
return;
}
using (var streamReader = new StreamReader(stream))
{
var entry = mySettingsSchema.GetIndexedEntry((CSharpNamingSettings s) => s.Abbreviations);
string abbreviation;
while ((abbreviation = streamReader.ReadLine()) != null)
{
ScalarSettingsStoreAccess.SetIndexedValue(mountPoint, entry, abbreviation, null, abbreviation,
null, myLogger);
}
}
});
}
}
}
|
using System.IO;
using JetBrains.Application.Settings;
using JetBrains.Application.Settings.Implementation;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Settings;
using JetBrains.ReSharper.Psi.CSharp.Naming2;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Naming.Settings
{
[SolutionComponent]
public class AbbreviationsSettingsProvider : IUnitySolutionSettingsProvider
{
private readonly ISettingsSchema mySettingsSchema;
private readonly ILogger myLogger;
public AbbreviationsSettingsProvider(ISettingsSchema settingsSchema, ILogger logger)
{
mySettingsSchema = settingsSchema;
myLogger = logger;
}
public void InitialiseSolutionSettings(ISettingsStorageMountPoint mountPoint)
{
var streamName = GetType().Namespace + ".Abbreviations.txt";
var stream = GetType().Assembly.GetManifestResourceStream(streamName);
if (stream == null)
{
myLogger.Warn($"Cannot load resource stream: {streamName}");
return;
}
using (var streamReader = new StreamReader(stream))
{
var entry = mySettingsSchema.GetIndexedEntry((CSharpNamingSettings s) => s.Abbreviations);
string abbreviation;
while ((abbreviation = streamReader.ReadLine()) != null)
{
ScalarSettingsStoreAccess.SetIndexedValue(mountPoint, entry, abbreviation, null, abbreviation,
null, myLogger);
}
}
}
}
}
|
apache-2.0
|
C#
|
12db4788979312d4c4a449bbd7e98da491c27208
|
make it pretty
|
shiftkey/ReactiveGit
|
ReactiveGit.Tests/ObservableRepositoryTests.cs
|
ReactiveGit.Tests/ObservableRepositoryTests.cs
|
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using LibGit2Sharp;
using Xunit;
namespace ReactiveGit.Tests
{
public class ObservableRepositoryTests
{
[Fact]
public async Task CanPullSomeRepository()
{
Credentials credentials = new UsernamePasswordCredentials
{
Username = "shiftkey-tester",
Password = "haha-password"
};
var repository = new ObservableRepository(
@"C:\Users\brendanforster\Documents\GìtHūb\testing-pushspecs",
credentials);
Func<int, int> translate = x => x / 3;
var pullObserver = new ReplaySubject<Tuple<string, int>>();
var pushObserver = new ReplaySubject<Tuple<string, int>>();
var pullResult = await repository.Pull(pullObserver);
Assert.NotEqual(MergeStatus.Conflicts, pullResult.Status);
await repository.Push(pushObserver);
var list = await pullObserver.Select(x => translate(x.Item2) * 2)
.Concat(pushObserver.Select(x => 67 + translate(x.Item2)))
.ToList();
Assert.NotEmpty(list);
Assert.Equal(100, list.Last());
}
}
}
|
using System;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using LibGit2Sharp;
using Xunit;
namespace ReactiveGit.Tests
{
public class ObservableRepositoryTests
{
[Fact]
public async Task CanPullSomeRepository()
{
Credentials credentials = new UsernamePasswordCredentials
{
Username = "shiftkey-tester",
Password = "haha-password"
};
var repository = new ObservableRepository(
@"C:\Users\brendanforster\Documents\GìtHūb\testing-pushspecs",
credentials);
var progress = 0;
var pullObserver = Observer.Create<Tuple<string, int>>(
next =>
{
progress = (next.Item2 * 2) / 3;
});
var pullResult = await repository.Pull(pullObserver);
Assert.Equal(66, progress);
Assert.NotEqual(MergeStatus.Conflicts, pullResult.Status);
var pushObserver = Observer.Create<Tuple<string, int>>(
next =>
{
progress = 67 + (next.Item2 / 3);
});
await repository.Push(pushObserver);
Assert.Equal(100, progress);
}
}
}
|
mit
|
C#
|
626a5311159ee8a71306cee52b6d89be6dee803b
|
update new field to use readonly modifier
|
Haacked/SeeGit
|
SeeGitApp/Extensions/CommitTemplatedAdorner.cs
|
SeeGitApp/Extensions/CommitTemplatedAdorner.cs
|
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace SeeGit
{
/// <summary>
/// Custom Adorner hosting a ContentControl with a ContentTemplate
/// </summary>
internal class CommitTemplatedAdorner : Adorner
{
private readonly FrameworkElement _adornedElement;
/// <summary>
///
/// </summary>
/// <param name="adornedElement"></param>
/// <param name="frameworkElementAdorner"></param>
public CommitTemplatedAdorner(UIElement adornedElement, FrameworkElement frameworkElementAdorner)
: base(adornedElement)
{
_adornedElement = (FrameworkElement) adornedElement;
// Assure we get mouse hits
_frameworkElementAdorner = frameworkElementAdorner;
AddVisualChild(_frameworkElementAdorner);
AddLogicalChild(_frameworkElementAdorner);
}
/// <summary>
///
/// </summary>
protected override Visual GetVisualChild(int index)
{
return _frameworkElementAdorner;
}
/// <summary>
///
/// </summary>
protected override int VisualChildrenCount => 1;
/// <summary>
///
/// </summary>
/// <param name="constraint"></param>
/// <returns></returns>
protected override Size MeasureOverride(Size constraint)
{
//_frameworkElementAdorner.Width = constraint.Width;
//_frameworkElementAdorner.Height = constraint.Height;
_frameworkElementAdorner.Measure(constraint);
return _frameworkElementAdorner.DesiredSize;
}
/// <summary>
///
/// </summary>
/// <param name="finalSize"></param>
/// <returns></returns>
protected override Size ArrangeOverride(Size finalSize)
{
// Make sure to align to the right of the element being adorned
double xloc = _adornedElement.ActualWidth;
_frameworkElementAdorner.Arrange(new Rect(new Point(xloc, 0), finalSize));
return finalSize;
}
/// <summary>
///
/// </summary>
private readonly FrameworkElement _frameworkElementAdorner;
}
}
|
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace SeeGit
{
/// <summary>
/// Custom Adorner hosting a ContentControl with a ContentTemplate
/// </summary>
internal class CommitTemplatedAdorner : Adorner
{
private FrameworkElement _adornedElement;
/// <summary>
///
/// </summary>
/// <param name="adornedElement"></param>
/// <param name="frameworkElementAdorner"></param>
public CommitTemplatedAdorner(UIElement adornedElement, FrameworkElement frameworkElementAdorner)
: base(adornedElement)
{
_adornedElement = (FrameworkElement) adornedElement;
// Assure we get mouse hits
_frameworkElementAdorner = frameworkElementAdorner;
AddVisualChild(_frameworkElementAdorner);
AddLogicalChild(_frameworkElementAdorner);
}
/// <summary>
///
/// </summary>
protected override Visual GetVisualChild(int index)
{
return _frameworkElementAdorner;
}
/// <summary>
///
/// </summary>
protected override int VisualChildrenCount => 1;
/// <summary>
///
/// </summary>
/// <param name="constraint"></param>
/// <returns></returns>
protected override Size MeasureOverride(Size constraint)
{
//_frameworkElementAdorner.Width = constraint.Width;
//_frameworkElementAdorner.Height = constraint.Height;
_frameworkElementAdorner.Measure(constraint);
return _frameworkElementAdorner.DesiredSize;
}
/// <summary>
///
/// </summary>
/// <param name="finalSize"></param>
/// <returns></returns>
protected override Size ArrangeOverride(Size finalSize)
{
// Make sure to align to the right of the element being adorned
double xloc = _adornedElement.ActualWidth;
_frameworkElementAdorner.Arrange(new Rect(new Point(xloc, 0), finalSize));
return finalSize;
}
/// <summary>
///
/// </summary>
private readonly FrameworkElement _frameworkElementAdorner;
}
}
|
mit
|
C#
|
890ebd98166f2ac642ccd42a41883e81472cbfd7
|
Implement correct event sink
|
antmicro/xwt,hamekoz/xwt,mminns/xwt,TheBrainTech/xwt,residuum/xwt,hwthomas/xwt,steffenWi/xwt,mminns/xwt,cra0zy/xwt,sevoku/xwt,akrisiun/xwt,directhex/xwt,mono/xwt,lytico/xwt,iainx/xwt
|
Xwt/Xwt/Slider.cs
|
Xwt/Xwt/Slider.cs
|
//
// Slider.cs
//
// Author:
// Jérémie Laval <jeremie.laval@xamarin.com>
//
// 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.Backends;
namespace Xwt
{
[BackendType (typeof(ISliderBackend))]
public class Slider : Widget
{
public Slider ()
{
}
protected new class WidgetBackendHost: Widget.WidgetBackendHost, ISliderEventSink
{
public void ValueChanged ()
{
((Slider)Parent).OnValueChanged (EventArgs.Empty);
}
}
ISliderBackend Backend {
get { return (ISliderBackend) BackendHost.Backend; }
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
public double Value {
get { return Backend.Value; }
set { Backend.Value = value; }
}
public double MinimumValue {
get { return Backend.MinimumValue; }
set { Backend.MinimumValue = value; }
}
public double MaximumValue {
get { return Backend.MaximumValue; }
set { Backend.MaximumValue = value; }
}
protected virtual void OnValueChanged (EventArgs e)
{
if (valueChanged != null)
valueChanged (this, e);
}
EventHandler valueChanged;
public event EventHandler ValueChanged {
add {
BackendHost.OnBeforeEventAdd (SliderEvent.ValueChanged, valueChanged);
valueChanged += value;
}
remove {
valueChanged -= value;
BackendHost.OnAfterEventRemove (SliderEvent.ValueChanged, valueChanged);
}
}
}
}
|
//
// Slider.cs
//
// Author:
// Jérémie Laval <jeremie.laval@xamarin.com>
//
// 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.Backends;
namespace Xwt
{
[BackendType (typeof(ISliderBackend))]
public class Slider : Widget
{
public Slider ()
{
}
protected new class WidgetBackendHost: Widget.WidgetBackendHost, ISpinButtonEventSink
{
public void ValueChanged ()
{
((Slider)Parent).OnValueChanged (EventArgs.Empty);
}
}
ISliderBackend Backend {
get { return (ISliderBackend) BackendHost.Backend; }
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
public double Value {
get { return Backend.Value; }
set { Backend.Value = value; }
}
public double MinimumValue {
get { return Backend.MinimumValue; }
set { Backend.MinimumValue = value; }
}
public double MaximumValue {
get { return Backend.MaximumValue; }
set { Backend.MaximumValue = value; }
}
protected virtual void OnValueChanged (EventArgs e)
{
if (valueChanged != null)
valueChanged (this, e);
}
EventHandler valueChanged;
public event EventHandler ValueChanged {
add {
BackendHost.OnBeforeEventAdd (SliderEvent.ValueChanged, valueChanged);
valueChanged += value;
}
remove {
valueChanged -= value;
BackendHost.OnAfterEventRemove (SliderEvent.ValueChanged, valueChanged);
}
}
}
}
|
mit
|
C#
|
779a14140e824a1ddeadbec957e69494e151d7d2
|
Update IQueryRepository.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Data/IQueryRepository.cs
|
TIKSN.Core/Data/IQueryRepository.cs
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data
{
public interface IQueryRepository<TEntity, TIdentity>
where TEntity : IEntity<TIdentity>
where TIdentity : IEquatable<TIdentity>
{
Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken);
Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken);
Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken);
Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids, CancellationToken cancellationToken);
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data
{
public interface IQueryRepository<TEntity, TIdentity>
where TEntity : IEntity<TIdentity>
where TIdentity : IEquatable<TIdentity>
{
Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken);
Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken);
Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken);
Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids, CancellationToken cancellationToken);
}
}
|
mit
|
C#
|
524a5c12185f2f00fa2e18fdab953c5f8ddb9694
|
Disable German and Chinese due to no maintainers
|
Yuubari/LegacyKCV,KCV-Localisation/KanColleViewer
|
Grabacr07.KanColleViewer/Models/ResourceService.cs
|
Grabacr07.KanColleViewer/Models/ResourceService.cs
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Grabacr07.KanColleViewer.Properties;
using Livet;
namespace Grabacr07.KanColleViewer.Models
{
/// <summary>
/// 多言語化されたリソースへのアクセスを提供します。
/// </summary>
public class ResourceService : NotificationObject
{
#region static members
private static readonly ResourceService current = new ResourceService();
public static ResourceService Current
{
get { return current; }
}
#endregion
/// <summary>
/// サポートされているカルチャの名前。
/// </summary>
private readonly string[] supportedCultureNames =
{
"ja", // Resources.resx
"en",
// "de",
// "zh-CN",
"ko-KR",
};
private readonly Resources _Resources = new Resources();
private readonly IReadOnlyCollection<CultureInfo> _SupportedCultures;
/// <summary>
/// 多言語化されたリソースを取得します。
/// </summary>
public Resources Resources
{
get { return this._Resources; }
}
/// <summary>
/// サポートされているカルチャを取得します。
/// </summary>
public IReadOnlyCollection<CultureInfo> SupportedCultures
{
get { return this._SupportedCultures; }
}
private ResourceService()
{
this._SupportedCultures = this.supportedCultureNames
.Select(x =>
{
try
{
return CultureInfo.GetCultureInfo(x);
}
catch (CultureNotFoundException)
{
return null;
}
})
.Where(x => x != null)
.ToList();
}
/// <summary>
/// 指定されたカルチャ名を使用して、リソースのカルチャを変更します。
/// </summary>
/// <param name="name">カルチャの名前。</param>
public void ChangeCulture(string name)
{
Resources.Culture = this.SupportedCultures.SingleOrDefault(x => x.Name == name);
// リソースの変更を受けて設定に適切な値を適用します。
Settings.Current.Culture = Resources.Culture != null
? Resources.Culture.Name
: null;
this.RaisePropertyChanged("Resources");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Grabacr07.KanColleViewer.Properties;
using Livet;
namespace Grabacr07.KanColleViewer.Models
{
/// <summary>
/// 多言語化されたリソースへのアクセスを提供します。
/// </summary>
public class ResourceService : NotificationObject
{
#region static members
private static readonly ResourceService current = new ResourceService();
public static ResourceService Current
{
get { return current; }
}
#endregion
/// <summary>
/// サポートされているカルチャの名前。
/// </summary>
private readonly string[] supportedCultureNames =
{
"ja", // Resources.resx
"en",
"de",
"zh-CN",
"ko-KR",
};
private readonly Resources _Resources = new Resources();
private readonly IReadOnlyCollection<CultureInfo> _SupportedCultures;
/// <summary>
/// 多言語化されたリソースを取得します。
/// </summary>
public Resources Resources
{
get { return this._Resources; }
}
/// <summary>
/// サポートされているカルチャを取得します。
/// </summary>
public IReadOnlyCollection<CultureInfo> SupportedCultures
{
get { return this._SupportedCultures; }
}
private ResourceService()
{
this._SupportedCultures = this.supportedCultureNames
.Select(x =>
{
try
{
return CultureInfo.GetCultureInfo(x);
}
catch (CultureNotFoundException)
{
return null;
}
})
.Where(x => x != null)
.ToList();
}
/// <summary>
/// 指定されたカルチャ名を使用して、リソースのカルチャを変更します。
/// </summary>
/// <param name="name">カルチャの名前。</param>
public void ChangeCulture(string name)
{
Resources.Culture = this.SupportedCultures.SingleOrDefault(x => x.Name == name);
// リソースの変更を受けて設定に適切な値を適用します。
Settings.Current.Culture = Resources.Culture != null
? Resources.Culture.Name
: null;
this.RaisePropertyChanged("Resources");
}
}
}
|
mit
|
C#
|
850b959d132c5b03aab569b725555fee2e2a983a
|
Remove debug gui
|
nozols/ParkitectAutoSave
|
AutoSaveBehaviour.cs
|
AutoSaveBehaviour.cs
|
using UnityEngine;
using System.Collections;
namespace AutoSave
{
class AutoSaveBehaviour : MonoBehaviour
{
public void Awake() {
DontDestroyOnLoad(this);
}
public void Start() {
StartCoroutine("AutoSave");
}
public void onGUI() {
if (GameController.Instance.isSavingGame) {
GUI.Label(new Rect(Screen.width - 110, 10, 100, 100), "Autosaving game");
}
}
private IEnumerator AutoSave() {
for (;;) {
Debug.Log("Autosaving game.");
GameController.Instance.saveGame("Saves/Savegames/AutoSave-" + GameController.Instance.park.parkName + ".txt");
Debug.Log("Finished autosaving.");
yield return new WaitForSeconds(20);
}
}
}
}
|
using UnityEngine;
using System.Collections;
namespace AutoSave
{
class AutoSaveBehaviour : MonoBehaviour
{
public void Awake() {
DontDestroyOnLoad(this);
}
public void Start() {
StartCoroutine("AutoSave");
}
public void onGUI() {
GUI.Label(new Rect(Screen.width - 210, 10, 100, 100), "Autosaving game");
if (GameController.Instance.isSavingGame) {
GUI.Label(new Rect(Screen.width - 110, 10, 100, 100), "Autosaving game");
}
}
private IEnumerator AutoSave() {
for (;;) {
Debug.Log("Autosaving game.");
GameController.Instance.saveGame("Saves/Savegames/AutoSave-" + GameController.Instance.park.parkName + ".txt");
Debug.Log("Finished autosaving.");
yield return new WaitForSeconds(20);
}
}
}
}
|
mit
|
C#
|
af64d4e8d880730926aa02a50b6ce52082728ad9
|
Remove help mapping
|
noobot/noobot,Workshop2/noobot
|
src/Noobot.Core/MessagingPipeline/Middleware/StandardMiddleware/HelpMiddleware.cs
|
src/Noobot.Core/MessagingPipeline/Middleware/StandardMiddleware/HelpMiddleware.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noobot.Core.MessagingPipeline.Middleware.ValidHandles;
using Noobot.Core.MessagingPipeline.Request;
using Noobot.Core.MessagingPipeline.Response;
namespace Noobot.Core.MessagingPipeline.Middleware.StandardMiddleware
{
internal class HelpMiddleware : MiddlewareBase
{
private readonly INoobotCore _noobotCore;
public HelpMiddleware(IMiddleware next, INoobotCore noobotCore) : base(next)
{
_noobotCore = noobotCore;
HandlerMappings = new[]
{
new HandlerMapping
{
ValidHandles = new IValidHandle[]
{
new StartsWithHandle("help")
},
Description = "Returns supported commands and descriptions of how to use them",
EvaluatorFunc = HelpHandler
}
};
}
private IEnumerable<ResponseMessage> HelpHandler(IncomingMessage message, IValidHandle matchedHandle)
{
var builder = new StringBuilder();
builder.Append(">>>");
IEnumerable<CommandDescription> supportedCommands = GetSupportedCommands().OrderBy(x => x.Command);
foreach (CommandDescription commandDescription in supportedCommands)
{
string description = commandDescription.Description.Replace("@{bot}", $"@{_noobotCore.GetBotUserName()}");
builder.AppendFormat("{0}\t- {1}\n", commandDescription.Command, description);
}
yield return message.ReplyToChannel(builder.ToString());
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noobot.Core.MessagingPipeline.Middleware.ValidHandles;
using Noobot.Core.MessagingPipeline.Request;
using Noobot.Core.MessagingPipeline.Response;
namespace Noobot.Core.MessagingPipeline.Middleware.StandardMiddleware
{
internal class HelpMiddleware : MiddlewareBase
{
private readonly INoobotCore _noobotCore;
public HelpMiddleware(IMiddleware next, INoobotCore noobotCore) : base(next)
{
_noobotCore = noobotCore;
HandlerMappings = new[]
{
new HandlerMapping
{
ValidHandles = new IValidHandle[]
{
new StartsWithHandle("help"),
new ExactMatchHandle("yo tell me more")
},
Description = "Returns supported commands and descriptions of how to use them",
EvaluatorFunc = HelpHandler
}
};
}
private IEnumerable<ResponseMessage> HelpHandler(IncomingMessage message, IValidHandle matchedHandle)
{
var builder = new StringBuilder();
builder.Append(">>>");
IEnumerable<CommandDescription> supportedCommands = GetSupportedCommands().OrderBy(x => x.Command);
foreach (CommandDescription commandDescription in supportedCommands)
{
string description = commandDescription.Description.Replace("@{bot}", $"@{_noobotCore.GetBotUserName()}");
builder.AppendFormat("{0}\t- {1}\n", commandDescription.Command, description);
}
yield return message.ReplyToChannel(builder.ToString());
}
}
}
|
mit
|
C#
|
01ab58fe7c58215f60b5a78e92b33418505b5137
|
Change legal entity to include the CompanyNumber, RegisteredAddress and DateOfIncorporation
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerApprenticeshipsService.Domain/Entities/Account/LegalEntity.cs
|
src/SFA.DAS.EmployerApprenticeshipsService.Domain/Entities/Account/LegalEntity.cs
|
using System;
namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account
{
public class LegalEntity
{
public long Id { get; set; }
public string CompanyNumber { get; set; }
public string Name { get; set; }
public string RegisteredAddress { get; set; }
public DateTime DateOfIncorporation { get; set; }
}
}
|
namespace SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account
{
public class LegalEntity
{
public long Id { get; set; }
public string Name { get; set; }
}
}
|
mit
|
C#
|
be69b5a7b1e478ad0c5fdb29f949a6e2115766ee
|
Fix to work with new API.
|
jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos
|
test/TestApp/StreamTestsModule.cs
|
test/TestApp/StreamTestsModule.cs
|
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using Manos;
using Manos.IO;
using Manos.Http;
using System;
using System.Linq;
using System.Text;
namespace TestApp {
public class StreamTestsModule : ManosModule {
public void EchoLocalPath (IManosContext ctx)
{
ctx.Response.End (ctx.Request.Path);
}
public void EchoInt (IManosContext ctx, int the_int)
{
ctx.Response.End (the_int.ToString ());
}
public void EchoString (IManosContext ctx, string the_string)
{
ctx.Response.End (the_string);
}
public void ReverseString (IManosContext ctx, string the_string)
{
// This is intentionally awful, as its trying to test the stream
// Write it normally, then try to overwrite it with the new value
ctx.Response.Write (the_string);
ctx.Response.Stream.Position = 0;
byte [] data = Encoding.Default.GetBytes (the_string);
for (int i = data.Length; i >= 0; --i) {
ctx.Response.Stream.Write (data, i, 1);
}
ctx.Response.End ();
}
public void MultiplyString (IManosContext ctx, string the_string, int amount)
{
// Create all the data for the string, then do all the writing
long start = ctx.Response.Stream.Position;
ctx.Response.Write (the_string);
long len = ctx.Response.Stream.Position - start;
ctx.Response.Stream.SetLength (len * amount);
ctx.Response.Stream.Position = start;
for (int i = 0; i < amount; i++) {
ctx.Response.Write (the_string);
}
ctx.Response.End ();
}
public void SendFile (IManosContext ctx, string name)
{
ctx.Response.SendFile (name);
ctx.Response.End ();
}
public void UploadFile (IManosContext ctx, string name)
{
UploadedFile file = ctx.Request.Files.Values.First ();
byte [] data = new byte [file.Contents.Length];
file.Contents.Read (data, 0, data.Length);
ctx.Response.End (data);
}
}
}
|
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using Manos;
using Manos.IO;
using Manos.Http;
using System;
using System.Linq;
using System.Text;
namespace TestApp {
public class StreamTestsModule : ManosModule {
public void EchoLocalPath (IManosContext ctx)
{
ctx.Response.End (ctx.Request.LocalPath);
}
public void EchoInt (IManosContext ctx, int the_int)
{
ctx.Response.End (the_int.ToString ());
}
public void EchoString (IManosContext ctx, string the_string)
{
ctx.Response.End (the_string);
}
public void ReverseString (IManosContext ctx, string the_string)
{
// This is intentionally awful, as its trying to test the stream
// Write it normally, then try to overwrite it with the new value
ctx.Response.Write (the_string);
ctx.Response.Stream.Position = 0;
byte [] data = Encoding.Default.GetBytes (the_string);
for (int i = data.Length; i >= 0; --i) {
ctx.Response.Stream.Write (data, i, 1);
}
ctx.Response.End ();
}
public void MultiplyString (IManosContext ctx, string the_string, int amount)
{
// Create all the data for the string, then do all the writing
long start = ctx.Response.Stream.Position;
ctx.Response.Write (the_string);
long len = ctx.Response.Stream.Position - start;
ctx.Response.Stream.SetLength (len * amount);
ctx.Response.Stream.Position = start;
for (int i = 0; i < amount; i++) {
ctx.Response.Write (the_string);
}
ctx.Response.End ();
}
public void SendFile (IManosContext ctx, string name)
{
ctx.Response.SendFile (name);
ctx.Response.End ();
}
public void UploadFile (IManosContext ctx, string name)
{
UploadedFile file = ctx.Request.Files.Values.First ();
byte [] data = new byte [file.Contents.Length];
file.Contents.Read (data, 0, data.Length);
ctx.Response.End (data);
}
}
}
|
mit
|
C#
|
0c5c7bab97b82c2088e0c4f3b03d90a5ee563f20
|
Set a more sensible default for the screen mode.
|
spideyfusion/akiba
|
Akiba/Core/Configuration.cs
|
Akiba/Core/Configuration.cs
|
namespace Akiba.Core
{
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
internal class Configuration
{
public const string ConfigurationName = "configuration.yaml";
public enum ScreenModes : ushort
{
Windowed,
Fullscreen,
Borderless,
};
public ushort FramesPerSecond { get; private set; } = 60;
public ushort RenderingResolutionWidth { get; private set; } = 1920;
public ushort RenderingResolutionHeight { get; private set; } = 1080;
public ScreenModes ScreenMode { get; private set; } = ScreenModes.Borderless;
public bool VerticalSynchronization { get; private set; } = false;
public bool AntiAliasing { get; private set; } = false;
public bool HideCursor { get; private set; } = false;
public bool PreventSystemSleep { get; private set; } = true;
public bool DisableMovies { get; private set; } = false;
public Configuration Save()
{
var serializer = new SerializerBuilder().EmitDefaults().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamWriter = new StreamWriter(ConfigurationName))
{
serializer.Serialize(streamWriter, this);
}
return this;
}
public static Configuration LoadFromFile()
{
var deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamReader = new StreamReader(ConfigurationName))
{
return deserializer.Deserialize<Configuration>(streamReader);
}
}
}
}
|
namespace Akiba.Core
{
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
internal class Configuration
{
public const string ConfigurationName = "configuration.yaml";
public enum ScreenModes : ushort
{
Windowed,
Fullscreen,
Borderless,
};
public ushort FramesPerSecond { get; private set; } = 60;
public ushort RenderingResolutionWidth { get; private set; } = 1920;
public ushort RenderingResolutionHeight { get; private set; } = 1080;
public ScreenModes ScreenMode { get; private set; } = ScreenModes.Fullscreen;
public bool VerticalSynchronization { get; private set; } = false;
public bool AntiAliasing { get; private set; } = false;
public bool HideCursor { get; private set; } = false;
public bool PreventSystemSleep { get; private set; } = true;
public bool DisableMovies { get; private set; } = false;
public Configuration Save()
{
var serializer = new SerializerBuilder().EmitDefaults().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamWriter = new StreamWriter(ConfigurationName))
{
serializer.Serialize(streamWriter, this);
}
return this;
}
public static Configuration LoadFromFile()
{
var deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(new CamelCaseNamingConvention()).Build();
using (var streamReader = new StreamReader(ConfigurationName))
{
return deserializer.Deserialize<Configuration>(streamReader);
}
}
}
}
|
mit
|
C#
|
62f60004ea541c3ccfe8f52e5c6687489bc1b822
|
Remove useless code
|
dgarage/NBXplorer,dgarage/NBXplorer
|
NBXplorer/Configuration/ConfigurationExtensions.cs
|
NBXplorer/Configuration/ConfigurationExtensions.cs
|
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
namespace NBXplorer.Configuration
{
public static class ConfigurationExtensions
{
public static T GetOrDefault<T>(this IConfiguration configuration, string key, T defaultValue)
{
var str = configuration[key] ?? configuration[key.Replace(".", string.Empty)];
if(str == null)
return defaultValue;
if(typeof(T) == typeof(bool))
{
var trueValues = new[] { "1", "true" };
var falseValues = new[] { "0", "false" };
if(trueValues.Contains(str, StringComparer.OrdinalIgnoreCase))
return (T)(object)true;
if(falseValues.Contains(str, StringComparer.OrdinalIgnoreCase))
return (T)(object)false;
throw new FormatException();
}
else if(typeof(T) == typeof(Uri))
return (T)(object)new Uri(str, UriKind.Absolute);
else if(typeof(T) == typeof(string))
return (T)(object)str;
else if(typeof(T) == typeof(IPEndPoint))
{
var separator = str.LastIndexOf(":");
if(separator == -1)
throw new FormatException();
var ip = str.Substring(0, separator);
var port = str.Substring(separator + 1);
return (T)(object)new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
}
else if(typeof(T) == typeof(int))
{
return (T)(object)int.Parse(str, CultureInfo.InvariantCulture);
}
else
{
throw new NotSupportedException("Configuration value does not support time " + typeof(T).Name);
}
}
}
}
|
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
namespace NBXplorer.Configuration
{
public static class ConfigurationExtensions
{
class FallbackConfiguration : IConfiguration
{
private IConfiguration _Configuration;
private IConfiguration _Fallback;
public FallbackConfiguration(IConfiguration configuration, IConfiguration fallback)
{
_Configuration = configuration;
_Fallback = fallback;
}
public string this[string key] { get => _Configuration[key] ?? _Fallback[key]; set => throw new NotSupportedException(); }
public IEnumerable<IConfigurationSection> GetChildren()
{
return _Configuration.GetChildren();
}
public IChangeToken GetReloadToken()
{
return _Configuration.GetReloadToken();
}
public IConfigurationSection GetSection(string key)
{
return _Configuration.GetSection(key);
}
}
public static string[] GetAll(this IConfiguration config, string key)
{
var data = config.GetOrDefault<string>(key, null);
if(data == null)
return new string[0];
return new string[] { data };
}
public static IConfiguration AddFallback(this IConfiguration configuration, IConfiguration fallback)
{
return new FallbackConfiguration(configuration, fallback);
}
public static T GetOrDefault<T>(this IConfiguration configuration, string key, T defaultValue)
{
var str = configuration[key] ?? configuration[key.Replace(".", string.Empty)];
if(str == null)
return defaultValue;
if(typeof(T) == typeof(bool))
{
var trueValues = new[] { "1", "true" };
var falseValues = new[] { "0", "false" };
if(trueValues.Contains(str, StringComparer.OrdinalIgnoreCase))
return (T)(object)true;
if(falseValues.Contains(str, StringComparer.OrdinalIgnoreCase))
return (T)(object)false;
throw new FormatException();
}
else if(typeof(T) == typeof(Uri))
return (T)(object)new Uri(str, UriKind.Absolute);
else if(typeof(T) == typeof(string))
return (T)(object)str;
else if(typeof(T) == typeof(IPEndPoint))
{
var separator = str.LastIndexOf(":");
if(separator == -1)
throw new FormatException();
var ip = str.Substring(0, separator);
var port = str.Substring(separator + 1);
return (T)(object)new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
}
else if(typeof(T) == typeof(int))
{
return (T)(object)int.Parse(str, CultureInfo.InvariantCulture);
}
else
{
throw new NotSupportedException("Configuration value does not support time " + typeof(T).Name);
}
}
}
}
|
mit
|
C#
|
7e80db2ab5a5628ae51ed12bdb3166802a8b29bc
|
Revert "绘制渐变"
|
lindexi/lindexi_gd,lindexi/lindexi_gd,lindexi/lindexi_gd,lindexi/lindexi_gd,lindexi/lindexi_gd
|
SkiaSharp/RulawnaloyerKairjemhemwemlayca/RulawnaloyerKairjemhemwemlayca/Program.cs
|
SkiaSharp/RulawnaloyerKairjemhemwemlayca/RulawnaloyerKairjemhemwemlayca/Program.cs
|
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Graphics.Skia;
using SkiaSharp;
var skImageInfo = new SKImageInfo(1920, 1080, SKColorType.Bgra8888, SKAlphaType.Unpremul, SKColorSpace.CreateSrgb());
var fileName = $"xx.png";
using (var skImage = SKImage.Create(skImageInfo))
{
using (var skBitmap = SKBitmap.FromImage(skImage))
{
using (var skCanvas = new SKCanvas(skBitmap))
{
skCanvas.Clear(SKColors.Transparent);
var skiaCanvas = new SkiaCanvas();
skiaCanvas.Canvas = skCanvas;
ICanvas canvas = skiaCanvas;
canvas.Font = new Font("微软雅黑");
canvas.FontSize = 100;
canvas.DrawString("汉字", 100, 100, 500, 500, HorizontalAlignment.Left, VerticalAlignment.Top);
canvas.StrokeColor = Colors.Blue;
canvas.StrokeSize = 2;
canvas.DrawRectangle(100, 100, 500, 500);
skCanvas.Flush();
using (var skData = skBitmap.Encode(SKEncodedImageFormat.Png, 100))
{
var file = new FileInfo(fileName);
using (var fileStream = file.OpenWrite())
{
fileStream.SetLength(0);
skData.SaveTo(fileStream);
}
}
}
}
}
|
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Graphics.Skia;
using SkiaSharp;
var skImageInfo = new SKImageInfo(1920, 1080, SKColorType.Bgra8888, SKAlphaType.Unpremul, SKColorSpace.CreateSrgb());
var fileName = $"xx.jpg";
using (var skImage = SKImage.Create(skImageInfo))
{
using (var skBitmap = SKBitmap.FromImage(skImage))
{
using (var skCanvas = new SKCanvas(skBitmap))
{
skCanvas.Clear(SKColors.Transparent);
var skiaCanvas = new SkiaCanvas();
skiaCanvas.Canvas = skCanvas;
ICanvas canvas = skiaCanvas;
canvas.Font = new Font("微软雅黑");
var linearGradientPaint = new LinearGradientPaint(new PaintGradientStop[]
{
new PaintGradientStop(0,Colors.Blue),
new PaintGradientStop(100,Colors.Black),
})
{
StartPoint = new Point(),
EndPoint = new Point(1,1)
};
canvas.FillColor = Colors.Beige;
canvas.FillRectangle(new RectF(10, 10, 200, 200));
canvas.SetFillPaint(linearGradientPaint, new RectF(10, 10, 200, 200));
canvas.FillRectangle(new RectF(10, 10, 200, 200));
skCanvas.Flush();
using (var skData = skBitmap.Encode(SKEncodedImageFormat.Jpeg, 2))
{
var file = new FileInfo(fileName);
using (var fileStream = file.OpenWrite())
{
fileStream.SetLength(0);
skData.SaveTo(fileStream);
}
}
}
}
}
|
mit
|
C#
|
8a4f9abd8f6af6bcbca8b96a2dd86bca04ffc0f7
|
Add unhandled exception handling
|
aarondemarre/DRLeagueParser
|
DRLPTest/App.xaml.cs
|
DRLPTest/App.xaml.cs
|
using System.Windows;
namespace DRLPTest
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
}
private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.Exception.ToString());
}
}
}
|
using System.Windows;
namespace DRLPTest
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
|
mit
|
C#
|
eac9e7a81de4dc09474db2af4e0073788dad5ce3
|
Fix WPF TextLayoutBackendHandler.GetSize
|
antmicro/xwt,hwthomas/xwt,cra0zy/xwt,sevoku/xwt,directhex/xwt,mono/xwt,TheBrainTech/xwt,mminns/xwt,steffenWi/xwt,akrisiun/xwt,lytico/xwt,mminns/xwt,iainx/xwt,residuum/xwt,hamekoz/xwt
|
Xwt.WPF/Xwt.WPFBackend/TextLayoutBackendHandler.cs
|
Xwt.WPF/Xwt.WPFBackend/TextLayoutBackendHandler.cs
|
//
// TextLayoutBackendHandler.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using Xwt.Engine;
namespace Xwt.WPFBackend
{
public class TextLayoutBackendHandler
: ITextLayoutBackendHandler
{
public object Create (Context context)
{
var drawingContext = (DrawingContext)WidgetRegistry.GetBackend (context);
return new TextLayoutContext (drawingContext);
}
public void SetWidth (object backend, double value)
{
((TextLayoutContext) backend).Width = value;
}
public void SetText (object backend, string text)
{
((TextLayoutContext) backend).Text = text;
}
public void SetFont (object backend, Font font)
{
((TextLayoutContext) backend).Font = font.ToDrawingFont();
}
public Size GetSize (object backend)
{
return ((TextLayoutContext) backend).GetSize ();
}
}
}
|
//
// TextLayoutBackendHandler.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using Xwt.Engine;
namespace Xwt.WPFBackend
{
public class TextLayoutBackendHandler
: ITextLayoutBackendHandler
{
public object Create (Context context)
{
var drawingContext = (DrawingContext)WidgetRegistry.GetBackend (context);
return new TextLayoutContext (drawingContext);
}
public void SetWidth (object backend, double value)
{
((TextLayoutContext) backend).Width = value;
}
public void SetText (object backend, string text)
{
((TextLayoutContext) backend).Text = text;
}
public void SetFont (object backend, Font font)
{
((TextLayoutContext) backend).Font = font.ToDrawingFont();
}
public Size GetSize (object backend)
{
return new Size (0,0);
}
}
}
|
mit
|
C#
|
9e131b7acad949381a9b471a46c9c20afeeab844
|
Use I18N where possible. Added OpenUserFile() method.
|
Vicrelant/polutils,graspee/polutils,graspee/polutils,Vicrelant/polutils
|
PlayOnline.FFXI/Character.cs
|
PlayOnline.FFXI/Character.cs
|
using System;
using System.IO;
using Microsoft.Win32;
using PlayOnline.Core;
namespace PlayOnline.FFXI {
public class Character {
internal Character(string ContentID) {
this.ID_ = ContentID;
this.DataDir_ = Path.Combine(POL.GetApplicationPath(AppID.FFXI), Path.Combine("User", ContentID));
}
#region Data Members
public string ID { get { return this.ID_; } }
public string Name {
get {
string value = String.Format("Unknown Character ({0})", this.ID_);
RegistryKey NameMappings = Registry.LocalMachine.OpenSubKey(@"Software\Pebbles\POLUtils\Character Names");
if (NameMappings != null) {
value = NameMappings.GetValue(this.ID_, value) as string;
NameMappings.Close();
}
return value;
}
set {
RegistryKey NameMappings = Registry.LocalMachine.CreateSubKey(@"Software\Pebbles\POLUtils\Character Names");
if (NameMappings != null) {
if (value == null)
NameMappings.DeleteValue(this.ID_, false);
else
NameMappings.SetValue(this.ID_, value);
NameMappings.Close();
}
}
}
public MacroFolderCollection MacroBars {
get {
if (this.MacroBars_ == null)
this.LoadMacroBars();
return this.MacroBars_;
}
}
#region Private Fields
private string ID_;
private string DataDir_;
private MacroFolderCollection MacroBars_;
#endregion
#endregion
public override string ToString() { return this.Name; }
public FileStream OpenUserFile(string FileName, FileMode Mode, FileAccess Access) {
FileStream Result = null;
try {
Result = new FileStream(Path.Combine(this.DataDir_, FileName), Mode, Access, FileShare.Read);
} catch (Exception E) { Console.WriteLine("{0}", E.ToString()); }
return Result;
}
public void SaveMacroBar(int Index) {
this.MacroBars_[Index].WriteToMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", Index)));
}
private void LoadMacroBars() {
this.MacroBars_ = new MacroFolderCollection();
for (int i = 0; i < 10; ++i) {
MacroFolder MF = MacroFolder.LoadFromMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", i)));
MF.Name = String.Format(I18N.GetText("MacroBarLabel"), i + 1);
this.MacroBars_.Add(MF);
}
}
}
}
|
using System;
using System.IO;
using Microsoft.Win32;
using PlayOnline.Core;
namespace PlayOnline.FFXI {
public class Character {
#region Data Members
public string ID { get { return this.ID_; } }
public string Name {
get {
string value = String.Format("Unknown Character ({0})", this.ID_);
RegistryKey NameMappings = Registry.LocalMachine.OpenSubKey(@"Software\Pebbles\POLUtils\Character Names");
if (NameMappings != null) {
value = NameMappings.GetValue(this.ID_, value) as string;
NameMappings.Close();
}
return value;
}
set {
RegistryKey NameMappings = Registry.LocalMachine.CreateSubKey(@"Software\Pebbles\POLUtils\Character Names");
if (NameMappings != null) {
if (value == null)
NameMappings.DeleteValue(this.ID_, false);
else
NameMappings.SetValue(this.ID_, value);
NameMappings.Close();
}
}
}
public MacroFolderCollection MacroBars {
get { return this.MacroBars_; }
}
#region Private Fields
private string ID_;
private string DataDir_;
private MacroFolderCollection MacroBars_;
#endregion
#endregion
internal Character(string ContentID) {
this.ID_ = ContentID;
this.DataDir_ = Path.Combine(POL.GetApplicationPath(AppID.FFXI), Path.Combine("User", ContentID));
this.MacroBars_ = new MacroFolderCollection();
for (int i = 0; i < 10; ++i) {
MacroFolder MF = MacroFolder.LoadFromMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", i)));
MF.Name = String.Format("Macro Bar #{0}", i + 1);
this.MacroBars_.Add(MF);
}
}
public void SaveMacroBar(int Index) {
this.MacroBars_[Index].WriteToMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", Index)));
}
}
}
|
apache-2.0
|
C#
|
f395f657fc40abb8eb2a1895a476c60b6652e64b
|
Fix FxCop warning CA1018 (attributes should have AttributeUsage)
|
poizan42/coreclr,cshung/coreclr,krk/coreclr,poizan42/coreclr,cshung/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,krk/coreclr,cshung/coreclr,krk/coreclr,krk/coreclr,krk/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,poizan42/coreclr
|
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs
|
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.CompilerServices
{
// Custom attribute to indicating a TypeDef is a discardable attribute.
[AttributeUsage(AttributeTargets.All)]
public class DiscardableAttribute : Attribute
{
public DiscardableAttribute() { }
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.CompilerServices
{
// Custom attribute to indicating a TypeDef is a discardable attribute.
public class DiscardableAttribute : Attribute
{
public DiscardableAttribute() { }
}
}
|
mit
|
C#
|
2389434b4049fc3a754d4d16e776a42ccd3c84fd
|
fix validazione motivazione revoca
|
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
|
src/backend/SO115App.Models/Classi/Soccorso/Eventi/Partenze/RevocaPerSostituzioneMezzo.cs
|
src/backend/SO115App.Models/Classi/Soccorso/Eventi/Partenze/RevocaPerSostituzioneMezzo.cs
|
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi.Partenze;
using System;
namespace SO115App.Models.Classi.Soccorso.Eventi.Partenze
{
public class RevocaPerSostituzioneMezzo : Revoca
{
public RevocaPerSostituzioneMezzo(RichiestaAssistenza richiesta, string codiceMezzo, DateTime istante, string codiceFonte, string motivazione) : base(richiesta, codiceMezzo, istante, codiceFonte)
{
this.Motivazione = motivazione;
}
/// <summary>
/// La motivazione della revoca
/// </summary>
public string Motivazione { get; private set; }
}
}
|
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi.Partenze;
using System;
namespace SO115App.Models.Classi.Soccorso.Eventi.Partenze
{
public class RevocaPerSostituzioneMezzo : Revoca
{
public RevocaPerSostituzioneMezzo(RichiestaAssistenza richiesta, string codiceMezzo, DateTime istante, string codiceFonte, string motivazione) : base(richiesta, codiceMezzo, istante, codiceFonte)
{
if (string.IsNullOrWhiteSpace(motivazione))
{
throw new ArgumentException("La motivazione della revoca deve essere specificata", nameof(motivazione));
}
this.Motivazione = motivazione;
}
/// <summary>
/// La motivazione della revoca
/// </summary>
public string Motivazione { get; private set; }
}
}
|
agpl-3.0
|
C#
|
d20938c45fc394b195ec1305c3c1614bc39eb037
|
Convert Unshelve to NDesk.Options.
|
hazzik/git-tfs,steveandpeggyb/Public,allansson/git-tfs,andyrooger/git-tfs,bleissem/git-tfs,hazzik/git-tfs,hazzik/git-tfs,jeremy-sylvis-tmg/git-tfs,NathanLBCooper/git-tfs,WolfVR/git-tfs,bleissem/git-tfs,NathanLBCooper/git-tfs,spraints/git-tfs,TheoAndersen/git-tfs,guyboltonking/git-tfs,adbre/git-tfs,vzabavnov/git-tfs,adbre/git-tfs,modulexcite/git-tfs,timotei/git-tfs,pmiossec/git-tfs,guyboltonking/git-tfs,TheoAndersen/git-tfs,WolfVR/git-tfs,TheoAndersen/git-tfs,git-tfs/git-tfs,bleissem/git-tfs,codemerlin/git-tfs,jeremy-sylvis-tmg/git-tfs,irontoby/git-tfs,hazzik/git-tfs,timotei/git-tfs,adbre/git-tfs,jeremy-sylvis-tmg/git-tfs,spraints/git-tfs,irontoby/git-tfs,TheoAndersen/git-tfs,NathanLBCooper/git-tfs,kgybels/git-tfs,guyboltonking/git-tfs,kgybels/git-tfs,kgybels/git-tfs,steveandpeggyb/Public,steveandpeggyb/Public,allansson/git-tfs,spraints/git-tfs,timotei/git-tfs,codemerlin/git-tfs,WolfVR/git-tfs,PKRoma/git-tfs,allansson/git-tfs,codemerlin/git-tfs,irontoby/git-tfs,modulexcite/git-tfs,allansson/git-tfs,modulexcite/git-tfs
|
GitTfs/Commands/Unshelve.cs
|
GitTfs/Commands/Unshelve.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NDesk.Options;
using StructureMap;
using Sep.Git.Tfs.Core;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("unshelve")]
[Description("unshelve -u <shelve-owner-name> <shelve-name> <git-branch-name>")]
[RequiresValidGitRepository]
public class Unshelve : GitTfsCommand
{
private readonly Globals _globals;
public Unshelve(Globals globals)
{
_globals = globals;
}
private string Owner { get; set; }
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "u|user=", "Shelveset owner (default: current user)\nUse 'all' to search all shelvesets.",
v => Owner = v },
};
}
}
IEnumerable<CommandLine.OptParse.IOptionResults> GitTfsCommand.ExtraOptions
{
get { return this.MakeNestedOptionResults(); }
}
public int Run(IList<string> args)
{
var remote = _globals.Repository.ReadTfsRemote(_globals.RemoteId);
return remote.Tfs.Unshelve(this, remote, args);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NDesk.Options;
using CommandLine.OptParse;
using Sep.Git.Tfs.Core;
using StructureMap;
namespace Sep.Git.Tfs.Commands
{
[Pluggable("unshelve")]
[Description("unshelve -u <shelve-owner-name> <shelve-name> <git-branch-name>")]
[RequiresValidGitRepository]
public class Unshelve : GitTfsCommand
{
private readonly Globals _globals;
public Unshelve(Globals globals)
{
_globals = globals;
}
[OptDef(OptValType.ValueReq)]
[ShortOptionName('u')]
[LongOptionName("user")]
[UseNameAsLongOption(false)]
[Description("Shelveset owner ('all' means all users)")]
public string Owner { get; set; }
public OptionSet OptionSet
{
get { return new OptionSet(); }
}
public IEnumerable<IOptionResults> ExtraOptions
{
get { return this.MakeNestedOptionResults(); }
}
public int Run(IList<string> args)
{
var remote = _globals.Repository.ReadTfsRemote(_globals.RemoteId);
return remote.Tfs.Unshelve(this, remote, args);
}
}
}
|
apache-2.0
|
C#
|
666375f685f9fba1a4f201df6fdc6ec641cd639f
|
Add some changes to UI to make spacing equal for components
|
willb611/SlimeSimulation
|
SlimeSimulation/View/WindowComponent/SimulationControlComponent/AdaptionPhaseControlBox.cs
|
SlimeSimulation/View/WindowComponent/SimulationControlComponent/AdaptionPhaseControlBox.cs
|
using Gtk;
using NLog;
using SlimeSimulation.Controller.WindowController.Templates;
namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent
{
class AdaptionPhaseControlBox : AbstractSimulationControlBox
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
AddControls(simulationStepAbstractWindowController, parentWindow);
}
private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues;
var container = new Table(6, 1, true);
container.Attach(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow), 0, 1, 0, 1);
container.Attach(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues), 0, 1, 1, 3);
container.Attach(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues), 0, 1, 3, 4);
container.Attach(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues), 0, 1, 4, 5);
container.Attach(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow), 0, 1, 5, 6);
Add(container);
}
}
}
|
using Gtk;
using NLog;
using SlimeSimulation.Controller.WindowController.Templates;
namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent
{
class AdaptionPhaseControlBox : AbstractSimulationControlBox
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public AdaptionPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
AddControls(simulationStepAbstractWindowController, parentWindow);
}
private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
var controlInterfaceStartingValues = simulationStepAbstractWindowController.SimulationControlInterfaceValues;
Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow));
Add(new SimulationStepNumberOfTimesComponent(simulationStepAbstractWindowController, parentWindow, controlInterfaceStartingValues));
Add(new ShouldFlowResultsBeDisplayedControlComponent(controlInterfaceStartingValues));
Add(new ShouldStepFromAllSourcesAtOnceControlComponent(controlInterfaceStartingValues));
Add(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow));
}
}
}
|
apache-2.0
|
C#
|
134c35fe822263487e8e70aaee31c691eb0ae52e
|
Extend documentation for EnumToObjectConverter
|
thomasgalliker/ValueConverters.NET
|
ValueConverters.NetFx/EnumToObjectConverter.cs
|
ValueConverters.NetFx/EnumToObjectConverter.cs
|
using System;
using System.Globalization;
#if (NETFX || WINDOWS_PHONE)
using System.Windows;
using System.Windows.Markup;
#elif (NETFX_CORE)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Markup;
#elif (XAMARIN)
using Xamarin.Forms;
#endif
namespace ValueConverters
{
/// <summary>
/// EnumToObjectConverter can be used to select different resources based on given enum name.
/// This can be particularly useful if an enum needs to represent an image on the user interface.
///
/// Use the Items property to create a ResourceDictionary which contains object-to-enum-name mappings.
/// Each defined object must have an x:Key which maps to the particular enum name.
///
/// Check out following example:
/// <example>
/// <ResourceDictionary>
/// <BitmapImage x:Key="Off" UriSource="/Resources/Images/stop.png" />
/// <BitmapImage x:Key="On" UriSource="/Resources/Images/play.png" />
/// <BitmapImage x:Key="Maybe" UriSource="/Resources/Images/pause.png" />
/// </ResourceDictionary>
/// </example>
/// Source: http://stackoverflow.com/questions/2787725/how-to-display-different-enum-icons-using-xaml-only
/// </summary>
#if (NETFX || WINDOWS_PHONE)
[ContentProperty("Items")]
#elif (NETFX_CORE)
[ContentProperty(Name = "Items")]
#endif
public class EnumToObjectConverter : ConverterBase
{
public ResourceDictionary Items { get; set; }
protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return UnsetValue;
}
string key = Enum.GetName(value.GetType(), value);
if (this.Items != null && ContainsKey(this.Items, key))
{
return this.Items[key];
}
return UnsetValue;
}
#if (NETFX || WINDOWS_PHONE)
private static bool ContainsKey(ResourceDictionary dict, string key)
{
return dict.Contains(key);
}
#elif (NETFX_CORE || XAMARIN)
private static bool ContainsKey(ResourceDictionary dict, string key)
{
return dict.ContainsKey(key);
}
#endif
}
}
|
using System;
using System.Globalization;
#if (NETFX || WINDOWS_PHONE)
using System.Windows;
using System.Windows.Markup;
#elif (NETFX_CORE)
using Windows.UI.Xaml;
using Windows.UI.Xaml.Markup;
#elif (XAMARIN)
using Xamarin.Forms;
#endif
namespace ValueConverters
{
/// <summary>
/// Source: http://stackoverflow.com/questions/2787725/how-to-display-different-enum-icons-using-xaml-only
/// </summary>
#if (NETFX || WINDOWS_PHONE)
[ContentProperty("Items")]
#elif (NETFX_CORE)
[ContentProperty(Name = "Items")]
#endif
public class EnumToObjectConverter : ConverterBase
{
public ResourceDictionary Items { get; set; }
protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return UnsetValue;
}
string key = Enum.GetName(value.GetType(), value);
if (this.Items != null && ContainsKey(this.Items, key))
{
return this.Items[key];
}
return UnsetValue;
}
#if (NETFX || WINDOWS_PHONE)
private static bool ContainsKey(ResourceDictionary dict, string key)
{
return dict.Contains(key);
}
#elif (NETFX_CORE || XAMARIN)
private static bool ContainsKey(ResourceDictionary dict, string key)
{
return dict.ContainsKey(key);
}
#endif
}
}
|
mit
|
C#
|
e522428628b16fc4c44541f70e7221033720930b
|
Fix coding style issue
|
Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates
|
Migrations/Configuration.cs
|
Migrations/Configuration.cs
|
namespace CurrencyRates.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "CurrencyRates.Context";
}
}
}
|
namespace CurrencyRates.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<CurrencyRates.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "CurrencyRates.Context";
}
}
}
|
mit
|
C#
|
1a703cea26c7a4069a2bbde3179637eebed4d1e8
|
Update GridModel.cs
|
gaessaki/TicTacToe-WinForms-MVP
|
TicTacToe/Model/GridModel.cs
|
TicTacToe/Model/GridModel.cs
|
namespace TicTacToe.Model
{
class GridModel : IGridModel
{
private char[,] grid;
private bool playerOneTurn;
/// <summary>
/// Gets and sets the boolean indicating whether it's the first players turn.
/// </summary>
public bool PlayerOneTurn
{
get { return playerOneTurn; }
set { playerOneTurn = value; }
}
public GridModel()
{
grid = new char[3, 3];
playerOneTurn = true;
}
/// <summary>
/// Creates a new empty game grid and gives the turn to the first player.
/// </summary>
public void NewGrid()
{
grid = new char[3, 3];
playerOneTurn = true;
}
/// <summary>
/// Sets the player's marker on the specified grid square.
/// </summary>
/// <param name="piece">Character representing the players marker. Should be 'X' or 'O'.</param>
/// <param name="row">The row of the square that the marker should be placed on.</param>
/// <param name="col">The column of the square that the marker should be placed on.</param>
public void SetPiece(char piece, int row, int col)
{
grid[row, col] = piece;
}
/// <summary>
/// Gets the player's marker on the specified grid square.
/// </summary>
/// <param name="row">The row of the square in question.</param>
/// <param name="col">The column of the square in question.</param>
/// <returns>The character on the specified grid square.</returns>
public char GetPiece(int row, int col)
{
return grid[row, col];
}
}
}
|
namespace TicTacToe.Model
{
class GridModel : IGridModel
{
private char[,] grid;
private bool playerOneTurn;
/// <summary>
/// Gets and sets the boolean indicating whether it's the first players turn.
/// </summary>
public bool PlayerOneTurn {
get { return playerOneTurn; }
set { playerOneTurn = value; }
}
public GridModel()
{
grid = new char[3, 3];
playerOneTurn = true;
}
/// <summary>
/// Creates a new empty game grid and gives the turn to the first player.
/// </summary>
public void NewGrid()
{
grid = new char[3, 3];
playerOneTurn = true;
}
/// <summary>
/// Sets the player's marker on the specified grid square.
/// </summary>
/// <param name="piece">Character representing the players marker. Should be 'X' or 'O'.</param>
/// <param name="row">The row of the square that the marker should be placed on.</param>
/// <param name="col">The column of the square that the marker should be placed on.</param>
public void SetPiece(char piece, int row, int col)
{
grid[row, col] = piece;
}
/// <summary>
/// Gets the player's marker on the specified grid square.
/// </summary>
/// <param name="row">The row of the square in question.</param>
/// <param name="col">The column of the square in question.</param>
/// <returns>The character on the specified grid square.</returns>
public char GetPiece(int row, int col)
{
return grid[row, col];
}
}
}
|
mit
|
C#
|
a124b695d9b2c88a870bd36dc965f82918506b78
|
Update Index.cshtml
|
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
|
Anlab.Mvc/Views/Home/Index.cshtml
|
Anlab.Mvc/Views/Home/Index.cshtml
|
@{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Update posted: September 30, 2020<br /><br />
In response to the emergency need for the analysis of wine for smoke taint,
the UC Davis Department of Viticulture and Enology is partnering with the UC Davis Analytical Lab to offer testing<br /><br />
Please click <a href="/media/pdf/anlab_smoke-taint_instructions_v2.pdf" target="_blank"><strong>here</strong> for more information on
<strong> Wine Testing for Smoke Taint</strong></a>.<br /><br />
Please Note Receiving Hours: M - F, 8 - 5.<br /><br />
<strong>Please Note Important Dates<br /><br />
Wine samples will <i>not</i> be accepted during Thanksgiving week (November 23 through 27).<br /><br />
The emergency arrangement for wine testing will end in December with samples accepted through December 8th.</strong>
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
|
@{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
Update posted: September 30, 2020<br /><br />
In response to the emergency need for the analysis of wine for smoke taint,
the UC Davis Department of Viticulture and Enology is partnering with the UC Davis Analytical Lab to offer testing<br /><br />
Please click <a href="/media/pdf/anlab_smoke-taint_instructions_v2.pdf" target="_blank"><strong>here</strong> for more information on
<strong> Wine Testing for Smoke Taint</strong></a>.<br /><br />
Please Note Receiving Hours: M - F, 8 - 5, except University Holidays.<br />
Upcoming University Holidays include November 11, 26, and 27.
</div>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p>
<p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and
waste water, and feed in support of agricultural and environmental research.</p>
<p>For new clients, please note the drop-down menu under “Lab Information” which contains
an “Order Completion Help” section to help guide you in creating a work order. Also helpful
under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides
brief descriptions of our current methods.</p>
<p>Please feel free to contact the lab with any questions.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br>
Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br>
Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br>
Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
<p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br>
Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p>
</address>
</div>
|
mit
|
C#
|
6008e6c42040709fa2aefa3f886e563bca316e24
|
Move test component to bottom of class
|
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework
|
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
|
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new AudioCollectionManager<AdjustableAudioComponent>();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent());
// in a seperate thread start processing the queue
new Thread(() => manager.Update()).Start();
// wait a little for beginning of the update to start
Thread.Sleep(4);
Assert.DoesNotThrow(() => manager.Dispose());
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new AudioCollectionManager<AdjustableAudioComponent>();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent());
// in a seperate thread start processing the queue
new Thread(() => manager.Update()).Start();
// wait a little for beginning of the update to start
Thread.Sleep(4);
Assert.DoesNotThrow(() => manager.Dispose());
}
}
}
|
mit
|
C#
|
13e83eb051fb0de5edc3aeb7308c24f565d2b437
|
Use TryGetValue instead of catching and returning null
|
RonnChyran/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,faint32/snowflake-1,faint32/snowflake-1,SnowflakePowered/snowflake,SnowflakePowered/snowflake
|
Snowflake/Ajax/JSRequest.cs
|
Snowflake/Ajax/JSRequest.cs
|
using System.Collections.Generic;
namespace Snowflake.Ajax
{
public class JSRequest : IJSRequest
{
public string MethodName { get; }
public string NameSpace { get; }
public IDictionary<string, string> MethodParameters { get; }
public JSRequest(string nameSpace, string methodName, IDictionary<string, string> parameters)
{
this.NameSpace = nameSpace;
this.MethodName = methodName;
this.MethodParameters = parameters;
}
public string GetParameter(string paramKey)
{
string methodParameters;
this.MethodParameters.TryGetValue(paramKey, out methodParameters);
return methodParameters;
}
}
}
|
using System.Collections.Generic;
namespace Snowflake.Ajax
{
public class JSRequest : IJSRequest
{
public string MethodName { get; }
public string NameSpace { get; }
public IDictionary<string, string> MethodParameters { get; }
public JSRequest(string nameSpace, string methodName, IDictionary<string, string> parameters)
{
this.NameSpace = nameSpace;
this.MethodName = methodName;
this.MethodParameters = parameters;
}
public string GetParameter(string paramKey)
{
try
{
return this.MethodParameters[paramKey];
}
catch (KeyNotFoundException)
{
return null;
}
}
}
}
|
mpl-2.0
|
C#
|
7c6dd17145eb193fec02d16c4490d3e57244bc20
|
Fix import orderings
|
CedarLogic/Dash,MicrosoftDX/Dash,MicrosoftDX/Dash,MicrosoftDX/Dash,MicrosoftDX/Dash,MicrosoftDX/Dash
|
DashServer/Utils/HandlerResult.cs
|
DashServer/Utils/HandlerResult.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using Microsoft.WindowsAzure.Storage;
namespace Microsoft.Dash.Server.Utils
{
public class HandlerResult
{
public static HandlerResult Redirect(Uri location)
{
return Redirect(location.ToString());
}
public static HandlerResult Redirect(string location)
{
return new HandlerResult
{
StatusCode = HttpStatusCode.Redirect,
Location = location,
};
}
public static HandlerResult FromException(StorageException ex)
{
return new HandlerResult
{
StatusCode = (HttpStatusCode)ex.RequestInformation.HttpStatusCode,
ErrorInformation = new DashErrorInformation(ex.RequestInformation.ExtendedErrorInformation),
};
}
public HttpStatusCode StatusCode { get; set; }
public string Location { get; set; }
public ResponseHeaders Headers { get; set; }
public DashErrorInformation ErrorInformation { get; set; }
}
public class DashErrorInformation
{
public DashErrorInformation()
{
this.AdditionalDetails = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
public DashErrorInformation(StorageExtendedErrorInformation src)
{
this.ErrorCode = src.ErrorCode;
this.ErrorMessage = src.ErrorMessage;
this.AdditionalDetails = src.AdditionalDetails;
}
public IDictionary<string, string> AdditionalDetails { get; set; }
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
using Microsoft.WindowsAzure.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
namespace Microsoft.Dash.Server.Utils
{
public class HandlerResult
{
public static HandlerResult Redirect(Uri location)
{
return Redirect(location.ToString());
}
public static HandlerResult Redirect(string location)
{
return new HandlerResult
{
StatusCode = HttpStatusCode.Redirect,
Location = location,
};
}
public static HandlerResult FromException(StorageException ex)
{
return new HandlerResult
{
StatusCode = (HttpStatusCode)ex.RequestInformation.HttpStatusCode,
ErrorInformation = new DashErrorInformation(ex.RequestInformation.ExtendedErrorInformation),
};
}
public HttpStatusCode StatusCode { get; set; }
public string Location { get; set; }
public ResponseHeaders Headers { get; set; }
public DashErrorInformation ErrorInformation { get; set; }
}
public class DashErrorInformation
{
public DashErrorInformation()
{
this.AdditionalDetails = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
public DashErrorInformation(StorageExtendedErrorInformation src)
{
this.ErrorCode = src.ErrorCode;
this.ErrorMessage = src.ErrorMessage;
this.AdditionalDetails = src.AdditionalDetails;
}
public IDictionary<string, string> AdditionalDetails { get; set; }
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
}
}
|
mit
|
C#
|
92986caa7accd6980c698f7772fa70d81d2b39d4
|
Add quick check for attached domain
|
Seddryck/ERMine,Seddryck/ERMine
|
ERMine.Core/Modeling/Attribute.cs
|
ERMine.Core/Modeling/Attribute.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ERMine.Core.Modeling
{
public class Attribute : IEntityRelationship
{
public string Label { get; set; }
public string DataType { get; set; }
public Domain Domain { get; set; }
public bool IsConstrainedDomain
{
get { return Domain != null; }
}
public bool IsNullable { get; set; }
public bool IsSparse { get; set; }
public bool IsImmutable { get; set; }
public KeyType Key { get; set; }
public bool IsPartOfPrimaryKey
{
get { return Key == KeyType.Primary; }
set { Key = value ? KeyType.Primary : KeyType.None; }
}
public bool IsPartOfPartialKey
{
get { return Key == KeyType.Partial; }
set { Key = value ? KeyType.Partial : KeyType.None; }
}
public bool IsMultiValued { get; set; }
public bool IsDerived { get; set; }
public string DerivedFormula { get; set; }
public bool IsDefault { get; set; }
public string DefaultFormula { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ERMine.Core.Modeling
{
public class Attribute : IEntityRelationship
{
public string Label { get; set; }
public string DataType { get; set; }
public Domain Domain { get; set; }
public bool IsNullable { get; set; }
public bool IsSparse { get; set; }
public bool IsImmutable { get; set; }
public KeyType Key { get; set; }
public bool IsPartOfPrimaryKey
{
get { return Key == KeyType.Primary; }
set { Key = value ? KeyType.Primary : KeyType.None; }
}
public bool IsPartOfPartialKey
{
get { return Key == KeyType.Partial; }
set { Key = value ? KeyType.Partial : KeyType.None; }
}
public bool IsMultiValued { get; set; }
public bool IsDerived { get; set; }
public string DerivedFormula { get; set; }
public bool IsDefault { get; set; }
public string DefaultFormula { get; set; }
}
}
|
apache-2.0
|
C#
|
08d056093c71d8bc11517b44f2e5bbf880b01fa2
|
Change NetworkMessageSender to send NetworkMessages
|
HelloKitty/GladNet2.0,HelloKitty/GladNet2,HelloKitty/GladNet2,HelloKitty/GladNet2.0
|
src/GladNet.Common/Network/Message/Senders/INetworkMessageSender.cs
|
src/GladNet.Common/Network/Message/Senders/INetworkMessageSender.cs
|
using GladNet.Payload;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace GladNet.Common
{
/// <summary>
/// Contract that guarantees implementing types offer some <see cref="INetworkMessage"/> and <see cref="PacketPayload"/> sending functionality.
/// </summary>
public interface INetworkMessageSender : INetSender, INetworkMessagePayloadSender
{
/// <summary>
/// Tries to send the <see cref="IResponseMessage"/> message without routing semantics.
/// </summary>
/// <param name="message"><see cref="IResponseMessage"/> to be sent.</param>
/// <param name="deliveryMethod">The deseried <see cref="DeliveryMethod"/> of the message.</param>
/// <param name="encrypt">Indicates if the message should be encrypted.</param>
/// <param name="channel">Indicates the channel for this message to be sent over.</param>
/// <returns>Indication of the message send state.</returns>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
SendResult TrySendMessage(IResponseMessage message, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0);
/// <summary>
/// Tries to send the <see cref="IEventMessage"/> message without routing semantics.
/// </summary>
/// <param name="message"><see cref="IEventMessage"/> to be sent.</param>
/// <param name="deliveryMethod">The deseried <see cref="DeliveryMethod"/> of the message.</param>
/// <param name="encrypt">Indicates if the message should be encrypted.</param>
/// <param name="channel">Indicates the channel for this message to be sent over.</param>
/// <returns>Indication of the message send state.</returns>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
SendResult TrySendMessage(IEventMessage message, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0);
/// <summary>
/// Tries to send the <see cref="IResponseMessage"/> message without routing semantics.
/// </summary>
/// <param name="message"><see cref="IResponseMessage"/> to be sent.</param>
/// <param name="deliveryMethod">The deseried <see cref="DeliveryMethod"/> of the message.</param>
/// <param name="encrypt">Indicates if the message should be encrypted.</param>
/// <param name="channel">Indicates the channel for this message to be sent over.</param>
/// <returns>Indication of the message send state.</returns>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
SendResult TrySendMessage(IRequestMessage message, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0);
}
}
|
using GladNet.Payload;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace GladNet.Common
{
/// <summary>
/// Contract that guarantees implementing types offer some network message sending functionality.
/// </summary>
public interface INetworkMessageSender : INetSender
{
/// <summary>
/// Attempts to send a message; may fail and failure will be reported.
/// </summary>
/// <param name="opType"><see cref="OperationType"/> of the message to send.</param>
/// <param name="payload">Payload instance to be sent in the message.</param>
/// <param name="deliveryMethod">The deseried <see cref="DeliveryMethod"/> of the message.</param>
/// <param name="encrypt">Indicates if the message should be encrypted.</param>
/// <param name="channel">Indicates the channel for this message to be sent over.</param>
/// <returns>Indication of the message send state.</returns>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
SendResult TrySendMessage(OperationType opType, PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0);
/// <summary>
/// Attempts to send a message; may fail and failure will be reported.
/// Additionally this message/payloadtype is known to have static send parameters and those will be used in transit.
/// </summary>
/// <typeparam name="TPacketType">Type of the packet payload.</typeparam>
/// <param name="opType"><see cref="OperationType"/> of the message to send.</param>
/// <param name="payload">Payload instance to be sent in the message that contains static message parameters.</param>
/// <returns>Indication of the message send state.</returns>
SendResult TrySendMessage<TPacketType>(OperationType opType, TPacketType payload)
where TPacketType : PacketPayload, IStaticPayloadParameters;
}
}
|
bsd-3-clause
|
C#
|
42b117b9d3804249a39ae1e191e7db2615122d72
|
add property for authenticated request
|
MienDev/IdentityServer4,chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,siyo-wang/IdentityServer4,siyo-wang/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,chrisowhite/IdentityServer4,jbijlsma/IdentityServer4
|
src/IdentityServer4/Validation/Models/ValidatedEndSessionRequest.cs
|
src/IdentityServer4/Validation/Models/ValidatedEndSessionRequest.cs
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
namespace IdentityServer4.Validation
{
/// <summary>
/// Represents a validated end session (logout) request
/// </summary>
public class ValidatedEndSessionRequest : ValidatedRequest
{
/// <summary>
/// Gets a value indicating whether this instance is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if this instance is authenticated; otherwise, <c>false</c>.
/// </value>
public bool IsAuthenticated => Client != null;
/// <summary>
/// Gets or sets the client.
/// </summary>
/// <value>
/// The client.
/// </value>
public Client Client { get; set; }
/// <summary>
/// Gets or sets the post-logout URI.
/// </summary>
/// <value>
/// The post-logout URI.
/// </value>
public string PostLogOutUri { get; set; }
/// <summary>
/// Gets or sets the state.
/// </summary>
/// <value>
/// The state.
/// </value>
public string State { get; set; }
}
}
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
namespace IdentityServer4.Validation
{
/// <summary>
/// Represents a validated end session (logout) request
/// </summary>
public class ValidatedEndSessionRequest : ValidatedRequest
{
/// <summary>
/// Gets or sets the client.
/// </summary>
/// <value>
/// The client.
/// </value>
public Client Client { get; set; }
/// <summary>
/// Gets or sets the post-logout URI.
/// </summary>
/// <value>
/// The post-logout URI.
/// </value>
public string PostLogOutUri { get; set; }
/// <summary>
/// Gets or sets the state.
/// </summary>
/// <value>
/// The state.
/// </value>
public string State { get; set; }
}
}
|
apache-2.0
|
C#
|
7f3392e8c87dbc046b8a0b725e305f599c022e55
|
use correct availability status, as described in https://xmpp.org/rfcs/rfc6121.html#presence-syntax-children-show
|
pgstath/Sharp.Xmpp,Hitcents/S22.Xmpp
|
Im/Availability.cs
|
Im/Availability.cs
|
namespace Sharp.Xmpp.Im
{
/// <summary>
/// Defines the possible values for a user's availability status.
/// </summary>
public enum Availability
{
/// <summary>
/// The user or resource is offline and unavailable.
/// </summary>
Offline,
/// <summary>
/// The user or resource is online and available.
/// </summary>
Online,
/// <summary>
/// The user or resource is temporarily away.
/// </summary>
Away,
/// <summary>
/// The user or resource is actively interested in chatting.
/// </summary>
Chat,
/// <summary>
/// The user or resource is busy.
/// </summary>
Dnd,
/// <summary>
/// The user or resource is away for an extended period.
/// </summary>
Xa
}
}
|
namespace Sharp.Xmpp.Im
{
/// <summary>
/// Defines the possible values for a user's availability status.
/// </summary>
public enum Availability
{
/// <summary>
/// The user or resource is offline and unavailable.
/// </summary>
Offline,
/// <summary>
/// The user or resource is online and available.
/// </summary>
Online,
/// <summary>
/// The user or resource is temporarily away.
/// </summary>
Away,
/// <summary>
/// The user or resource is actively interested in chatting.
/// </summary>
Chat,
/// <summary>
/// The user or resource is busy.
/// </summary>
DoNotDisturb,
/// <summary>
/// The user or resource is away for an extended period.
/// </summary>
ExtendedAway
}
}
|
mit
|
C#
|
28ce38bd4a0462f43ba4132903537b16212bf2dd
|
Enable OMS in the frontent service startup code.
|
karolz-ms/diagnostics-eventflow
|
AirTrafficControl.Web/Program.cs
|
AirTrafficControl.Web/Program.cs
|
using AirTrafficControl.Web.Fabric;
using Microsoft.Diagnostics.EventListeners;
using Microsoft.ServiceFabric.Services.Runtime;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Fabric;
using System.Threading;
using FabricEventListeners = Microsoft.Diagnostics.EventListeners.Fabric;
namespace AirTrafficControl.Web
{
public class Program
{
public static void Main(string[] args)
{
try
{
const string ElasticSearchEventListenerId = "ElasticSearchEventListener";
ElasticSearchListener esListener = null;
FabricEventListeners.FabricConfigurationProvider configProvider = new FabricEventListeners.FabricConfigurationProvider(ElasticSearchEventListenerId);
if (configProvider.HasConfiguration)
{
esListener = new ElasticSearchListener(configProvider, new FabricEventListeners.FabricHealthReporter(ElasticSearchEventListenerId));
}
const string OmsEventListenerId = "OmsEventListener";
OmsEventListener omsListener = null;
configProvider = new FabricEventListeners.FabricConfigurationProvider(OmsEventListenerId);
if (configProvider.HasConfiguration)
{
omsListener = new OmsEventListener(configProvider, new FabricEventListeners.FabricHealthReporter(OmsEventListenerId));
}
// This is the name of the ServiceType that is registered with FabricRuntime.
// This name must match the name defined in the ServiceManifest. If you change
// this name, please change the name of the ServiceType in the ServiceManifest.
ServiceRuntime.RegisterServiceAsync("AirTrafficControlWebType", ctx => new AirTrafficControlWeb(ctx)).Wait();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(AirTrafficControlWeb).Name);
Thread.Sleep(Timeout.Infinite);
GC.KeepAlive(esListener);
GC.KeepAlive(omsListener);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
}
}
|
using AirTrafficControl.Web.Fabric;
using Microsoft.Diagnostics.EventListeners;
using Microsoft.ServiceFabric.Services.Runtime;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Fabric;
using System.Threading;
using FabricEventListeners = Microsoft.Diagnostics.EventListeners.Fabric;
namespace AirTrafficControl.Web
{
public class Program
{
public static void Main(string[] args)
{
try
{
const string ElasticSearchEventListenerId = "ElasticSearchEventListener";
FabricEventListeners.FabricConfigurationProvider configProvider = new FabricEventListeners.FabricConfigurationProvider(ElasticSearchEventListenerId);
ElasticSearchListener listener = null;
if (configProvider.HasConfiguration)
{
listener = new ElasticSearchListener(configProvider, new FabricEventListeners.FabricHealthReporter(ElasticSearchEventListenerId));
}
// This is the name of the ServiceType that is registered with FabricRuntime.
// This name must match the name defined in the ServiceManifest. If you change
// this name, please change the name of the ServiceType in the ServiceManifest.
ServiceRuntime.RegisterServiceAsync("AirTrafficControlWebType", ctx => new AirTrafficControlWeb(ctx)).Wait();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(AirTrafficControlWeb).Name);
Thread.Sleep(Timeout.Infinite);
GC.KeepAlive(listener);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
}
}
|
mit
|
C#
|
5e4a8e3b09fe3a9eee94f0acb195687d5619393c
|
edit for style
|
kaosborn/KaosCollections
|
Bench/RdExample04/RdExample04.cs
|
Bench/RdExample04/RdExample04.cs
|
using System;
using Kaos.Collections;
namespace ExampleApp
{
class RdExample04
{
static void Main()
{
var dary1 = new RankedDictionary<string,int> (StringComparer.InvariantCultureIgnoreCase);
dary1.Add ("AAA", 0);
dary1.Add ("bbb", 1);
dary1.Add ("CCC", 2);
dary1.Add ("ddd", 3);
Console.WriteLine ("Comparer is case insensitive:");
foreach (System.Collections.Generic.KeyValuePair<string,int> pair in dary1)
Console.WriteLine (pair.Key);
Console.WriteLine();
var dary2 = new RankedDictionary<string,int> (StringComparer.Ordinal);
dary2.Add ("AAA", 0);
dary2.Add ("bbb", 2);
dary2.Add ("CCC", 1);
dary2.Add ("ddd", 3);
Console.WriteLine ("Comparer is case sensitive:");
foreach (System.Collections.Generic.KeyValuePair<string,int> pair in dary2)
Console.WriteLine (pair.Key);
}
/* Output:
Comparer is case insensitive:
AAA
bbb
CCC
ddd
Comparer is case sensitive:
AAA
CCC
bbb
ddd
*/
}
}
|
//
// Program: RdExample04.cs
// Purpose: Exercise BtreeDictionary with a supplied comparer.
//
using System;
using System.Collections.Generic;
using Kaos.Collections;
namespace ExampleApp
{
class RdExample04
{
static void Main()
{
var tree1 = new RankedDictionary<string,int> (StringComparer.InvariantCultureIgnoreCase);
tree1.Add ("AAA", 0);
tree1.Add ("bbb", 1);
tree1.Add ("CCC", 2);
tree1.Add ("ddd", 3);
Console.WriteLine ("Case insensitive:");
foreach (KeyValuePair<string,int> pair in tree1)
Console.WriteLine (pair.Key);
Console.WriteLine();
var tree2 = new RankedDictionary<string,int> (StringComparer.Ordinal);
tree2.Add ("AAA", 0);
tree2.Add ("bbb", 2);
tree2.Add ("CCC", 1);
tree2.Add ("ddd", 3);
Console.WriteLine ("Case sensitive:");
foreach (KeyValuePair<string,int> pair in tree2)
Console.WriteLine (pair.Key);
}
}
}
|
mit
|
C#
|
c4eeb17d510df0d8a4154f88dd8dc8927234d5c0
|
Fix duplicate target
|
RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake
|
src/Snowflake.Framework.Tests/Configuration/OrderSensitiveConfigurationCollection.cs
|
src/Snowflake.Framework.Tests/Configuration/OrderSensitiveConfigurationCollection.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Configuration;
using Snowflake.Configuration.Attributes;
using Snowflake.Configuration.Serialization.Serializers.Implementations;
using Snowflake.Configuration.Tests;
namespace Snowflake.Configuration.Tests
{
[ConfigurationTarget("#dolphin", typeof(SimpleIniConfigurationSerializer))]
[ConfigurationTarget("#retroarch", typeof(SimpleCfgConfigurationSerializer))]
public interface
OrderSensitiveConfigurationCollection : IConfigurationCollection<OrderSensitiveConfigurationCollection>
{
[ConfigurationTargetMember("#dolphin")] ExampleConfigurationSection ExampleConfiguration { get; set; }
[ConfigurationTargetMember("#retroarch")] IVideoConfiguration VideoConfiguration { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Configuration;
using Snowflake.Configuration.Attributes;
using Snowflake.Configuration.Serialization.Serializers.Implementations;
using Snowflake.Configuration.Tests;
namespace Snowflake.Configuration.Tests
{
[ConfigurationTarget("#dolphin", typeof(SimpleIniConfigurationSerializer))]
[ConfigurationTarget("#dolphin", typeof(SimpleCfgConfigurationSerializer))]
public interface
OrderSensitiveConfigurationCollection : IConfigurationCollection<OrderSensitiveConfigurationCollection>
{
[ConfigurationTargetMember("#dolphin")] ExampleConfigurationSection ExampleConfiguration { get; set; }
[ConfigurationTargetMember("#retroarch")] IVideoConfiguration VideoConfiguration { get; set; }
}
}
|
mpl-2.0
|
C#
|
e7467da742ecc93b2debe0142412c386ddee6316
|
Fix runtime error
|
anuracode/forms_controls
|
Anuracode.Forms.Controls.Sample/Anuracode.Forms.Controls.Sample.Droid/MainActivity.cs
|
Anuracode.Forms.Controls.Sample/Anuracode.Forms.Controls.Sample.Droid/MainActivity.cs
|
using Android.App;
using Android.Content.PM;
using Android.OS;
using Anuracode.Forms.Controls.Sample;
namespace SampleAndroid
{
[Activity(Label = "Anuracode.Forms.Controls.Sample", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity // global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
Xamarin.Essentials.Platform.Init(this, bundle); // add this line to your code, it may also be called: bundle
Anuracode.Forms.Controls.Renderers.ExtendedImageRenderer.AllowDownSample = true;
FFImageLoading.ImageService.Instance.Initialize(
new FFImageLoading.Config.Configuration()
{
VerboseLoadingCancelledLogging = false,
VerboseLogging = false,
VerboseMemoryCacheLogging = false,
VerbosePerformanceLogging = false,
MaxMemoryCacheSize = 100000 * 5,
HttpClient = new System.Net.Http.HttpClient(new Xamarin.Android.Net.AndroidClientHandler())
});
// set the layout resources first
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity.ToolbarResource = Resource.Layout.toolbar;
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity.TabLayoutResource = Resource.Layout.tabs;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
global::Xamarin.Forms.Forms.SetTitleBarVisibility(global::Xamarin.Forms.AndroidTitleBarVisibility.Never);
LoadApplication(new App());
}
}
}
|
using Android.App;
using Android.Content.PM;
using Android.OS;
using Anuracode.Forms.Controls.Sample;
namespace SampleAndroid
{
[Activity(Label = "Anuracode.Forms.Controls.Sample", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity // global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
Xamarin.Essentials.Platform.Init(this, bundle); // add this line to your code, it may also be called: bundle
Anuracode.Forms.Controls.Renderers.ExtendedImageRenderer.AllowDownSample = true;
FFImageLoading.ImageService.Instance.Initialize(
new FFImageLoading.Config.Configuration()
{
VerboseLoadingCancelledLogging = false,
VerboseLogging = false,
VerboseMemoryCacheLogging = false,
VerbosePerformanceLogging = false,
MaxMemoryCacheSize = 100000 * 5,
HttpClient = new System.Net.Http.HttpClient(new Xamarin.Android.Net.AndroidClientHandler())
});
// set the layout resources first
// global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity.ToolbarResource = Resource.Layout.toolbar;
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity.TabLayoutResource = Resource.Layout.tabs;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
global::Xamarin.Forms.Forms.SetTitleBarVisibility(global::Xamarin.Forms.AndroidTitleBarVisibility.Never);
LoadApplication(new App());
}
}
}
|
apache-2.0
|
C#
|
fd1c7c5b47464acd7c26b4a69c7c90096000b6ab
|
Make NoRequiredScopeAttribute public
|
Brightspace/D2L.Security.OAuth2
|
D2L.Security.OAuth2.WebApi/Authorization/NoRequiredScopeAttribute.cs
|
D2L.Security.OAuth2.WebApi/Authorization/NoRequiredScopeAttribute.cs
|
using System;
using System.Web.Http;
using System.Web.Http.Controllers;
using D2L.Security.OAuth2.Principal;
namespace D2L.Security.OAuth2.Authorization {
[AttributeUsage( AttributeTargets.Method, AllowMultiple = false )]
public sealed class NoRequiredScopeAttribute : AuthorizeAttribute {
// This attribute is only used as a signal in DefaultAuthorizationAttribute
protected override bool IsAuthorized( HttpActionContext context ) {
return true;
}
}
}
|
using System;
using System.Web.Http;
using System.Web.Http.Controllers;
using D2L.Security.OAuth2.Principal;
namespace D2L.Security.OAuth2.Authorization {
internal sealed class NoRequiredScopeAttribute : AuthorizeAttribute {
[AttributeUsage( AttributeTargets.Method, AllowMultiple = false )]
// This attribute is only used as a signal in DefaultAuthorizationAttribute
protected override bool IsAuthorized( HttpActionContext context ) {
return true;
}
}
}
|
apache-2.0
|
C#
|
7dad561c96fb3bc32bb330c549a0ef4fca2bad93
|
Revert to use ProductType since this is all that is needed in the summary, as it is the only thing shown in the opportunity summary, in the offer page
|
Paymentsense/Dapper.SimpleSave
|
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/OpportunitySummaryDto.cs
|
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Application/OpportunitySummaryDto.cs
|
using PS.Mothership.Core.Common.Template.Gen;
using PS.Mothership.Core.Common.Template.Opp;
using System;
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class OpportunitySummaryDto
{
[DataMember]
public Guid OpportunityGuid { get; set; }
[DataMember]
public double Credit { get; set; }
[DataMember]
public double Debit { get; set; }
[DataMember]
public OppTypeOfTransactionEnum TypeOfTransactionKey { get; set; }
[DataMember]
public string ProductType { get; set; }
[DataMember]
public GenOpportunityStatusEnum OpportunityStatusKey { get; set; }
[DataMember]
public string ContractLengthDescription { get; set; }
}
}
|
using PS.Mothership.Core.Common.Template.Gen;
using PS.Mothership.Core.Common.Template.Opp;
using System;
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class OpportunitySummaryDto
{
[DataMember]
public Guid OpportunityGuid { get; set; }
[DataMember]
public double Credit { get; set; }
[DataMember]
public double Debit { get; set; }
[DataMember]
public OppTypeOfTransactionEnum TypeOfTransactionKey { get; set; }
[DataMember]
public string Vendor { get; set; }
[DataMember]
public string Model { get; set; }
[DataMember]
public GenOpportunityStatusEnum OpportunityStatusKey { get; set; }
[DataMember]
public string ContractLengthDescription { get; set; }
}
}
|
mit
|
C#
|
ce2d6b6b2f91a5e494b8038216be8a3eb881c223
|
Use the Query property of the Uri
|
ScottIsAFool/Bex,jamesmcroft/Bex
|
Bex/Extensions/UriExtensions.cs
|
Bex/Extensions/UriExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Bex.Extensions
{
internal static class UriExtensions
{
internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri)
{
if (string.IsNullOrEmpty(uri.Query))
{
return Enumerable.Empty<KeyValuePair<string, string>>();
}
var query = uri.Query.TrimStart('?');
return query.Split('&')
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => x.Split('='))
.Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Bex.Extensions
{
internal static class UriExtensions
{
internal static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri)
{
var uriString = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString;
var queryIndex = uriString.IndexOf("?", StringComparison.OrdinalIgnoreCase);
if (queryIndex == -1)
{
return Enumerable.Empty<KeyValuePair<string, string>>();
}
var query = uriString.Substring(queryIndex + 1);
return query.Split('&')
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => x.Split('='))
.Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null));
}
}
}
|
mit
|
C#
|
d60528c40fc88d36a6947c75ba95e8327cb8011e
|
Fix AssemblyInfo details
|
SuperDrew/ggUnit
|
GgUnit/Properties/AssemblyInfo.cs
|
GgUnit/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("GgUnit")]
[assembly: AssemblyDescription("Generate Group stochastic testing framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GgUnit")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e97f7538-677d-44a2-9a70-f5d652591e70")]
// 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.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GgUnit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Abcam")]
[assembly: AssemblyProduct("GgUnit")]
[assembly: AssemblyCopyright("Copyright © Abcam 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e97f7538-677d-44a2-9a70-f5d652591e70")]
// 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#
|
c0b2c2b194bde4ffa6a38d200bcf76223743c714
|
Fix commit 82eff307d5fc9c962dbbb6e109781d92bbb0f069
|
StockSharp/StockSharp
|
Community/CommunityMessageTypes.cs
|
Community/CommunityMessageTypes.cs
|
namespace StockSharp.Community
{
using StockSharp.Messages;
/// <summary>
/// Extended <see cref="MessageTypes"/>.
/// </summary>
public static class CommunityMessageTypes
{
/// <summary>
/// <see cref="FileInfoMessage"/>.
/// </summary>
public const MessageTypes FileInfo = (MessageTypes)(-11000);
/// <summary>
/// <see cref="ProductInfoMessage"/>.
/// </summary>
public const MessageTypes ProductInfo = (MessageTypes)(-11001);
/// <summary>
/// <see cref="ProductLookupMessage"/>.
/// </summary>
public const MessageTypes ProductLookup = (MessageTypes)(-11002);
/// <summary>
/// <see cref="ProductFeedbackMessage"/>.
/// </summary>
public const MessageTypes ProductFeedback = (MessageTypes)(-11003);
internal static DataType ProductInfoType = DataType.Create(typeof(ProductInfoMessage), null).Immutable();
internal static DataType ProductFeedbackType = DataType.Create(typeof(ProductFeedbackMessage), null).Immutable();
}
}
|
namespace StockSharp.Community
{
using StockSharp.Messages;
/// <summary>
/// Extended <see cref="MessageTypes"/>.
/// </summary>
public class CommunityMessageTypes
{
/// <summary>
/// <see cref="FileInfoMessage"/>.
/// </summary>
public const MessageTypes FileInfo = (MessageTypes)(-11000);
/// <summary>
/// <see cref="ProductInfoMessage"/>.
/// </summary>
public const MessageTypes ProductInfo = (MessageTypes)(-11001);
/// <summary>
/// <see cref="ProductLookupMessage"/>.
/// </summary>
public const MessageTypes ProductLookup = (MessageTypes)(-11002);
/// <summary>
/// <see cref="ProductFeedbackMessage"/>.
/// </summary>
public const MessageTypes ProductFeedback = (MessageTypes)(-11003);
internal static DataType ProductInfoType = DataType.Create(typeof(ProductInfoMessage), null).Immutable();
internal static DataType ProductFeedbackType = DataType.Create(typeof(ProductFeedbackMessage), null).Immutable();
}
}
|
apache-2.0
|
C#
|
69bb7140502abddab974171fe08222b900a358c1
|
Update default configuration to use legacy URLs
|
k-t/SharpHaven
|
SharpHaven/Config.cs
|
SharpHaven/Config.cs
|
using System;
using System.IO;
using Nini.Config;
namespace SharpHaven
{
public class Config
{
private const string DefaultHost = "legacy.havenandhearth.com";
private const int DefaultGamePort = 1870;
private const int DefaultAuthPort = 1871;
private const string DefaultMapUrl = "http://legacy.havenandhearth.com/mm/";
private const string DefaultResUrl = "http://legacy.havenandhearth.com/res/";
private readonly IConfig havenConfig;
public Config()
{
var configSource = new IniConfigSource();
configSource.AutoSave = true;
CreateOrLoadIniConfig(configSource);
havenConfig = configSource.Configs["haven"] ?? configSource.AddConfig("haven");
var commandLineConfigSource = LoadCommandLineConfig();
configSource.Merge(commandLineConfigSource);
}
public string AuthHost
{
get { return havenConfig.Get("authsrv", DefaultHost); }
}
public int AuthPort
{
get { return DefaultAuthPort; }
}
public byte[] AuthToken
{
get
{
var encoded = havenConfig.Get("authtoken", "");
return string.IsNullOrEmpty(encoded)
? null
: Convert.FromBase64String(encoded);
}
set
{
var decoded = value != null ? Convert.ToBase64String(value) : "";
havenConfig.Set("authtoken", decoded);
}
}
public string UserName
{
get { return havenConfig.Get("username", ""); }
set { havenConfig.Set("username", value); }
}
public string GameHost
{
get { return havenConfig.Get("gamesrv", DefaultHost); }
}
public int GamePort
{
get { return DefaultGamePort; }
}
public string MapUrl
{
get { return havenConfig.Get("mapurl", DefaultMapUrl); }
}
public string ResUrl
{
get { return havenConfig.Get("resurl", DefaultResUrl); }
}
private static void CreateOrLoadIniConfig(IniConfigSource config)
{
var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var configPath = Path.Combine(appDataPath, "sharphaven", "settings.ini");
try
{
config.Load(configPath);
}
catch (Exception)
{
Directory.CreateDirectory(Path.GetDirectoryName(configPath));
config.Save(configPath);
}
}
private static IConfigSource LoadCommandLineConfig()
{
var argvSource = new ArgvConfigSource(Environment.GetCommandLineArgs());
argvSource.AddSwitch("haven", "gamesrv", "g");
argvSource.AddSwitch("haven", "authsrv", "a");
return argvSource;
}
}
}
|
using System;
using System.IO;
using Nini.Config;
namespace SharpHaven
{
public class Config
{
private const string DefaultHost = "moltke.seatribe.se";
private const int DefaultGamePort = 1870;
private const int DefaultAuthPort = 1871;
private const string DefaultMapUrl = "http://www.havenandhearth.com/mm/";
private const string DefaultResUrl = "http://www.havenandhearth.com/res/";
private readonly IConfig havenConfig;
public Config()
{
var configSource = new IniConfigSource();
configSource.AutoSave = true;
CreateOrLoadIniConfig(configSource);
havenConfig = configSource.Configs["haven"] ?? configSource.AddConfig("haven");
var commandLineConfigSource = LoadCommandLineConfig();
configSource.Merge(commandLineConfigSource);
}
public string AuthHost
{
get { return havenConfig.Get("authsrv", DefaultHost); }
}
public int AuthPort
{
get { return DefaultAuthPort; }
}
public byte[] AuthToken
{
get
{
var encoded = havenConfig.Get("authtoken", "");
return string.IsNullOrEmpty(encoded)
? null
: Convert.FromBase64String(encoded);
}
set
{
var decoded = value != null ? Convert.ToBase64String(value) : "";
havenConfig.Set("authtoken", decoded);
}
}
public string UserName
{
get { return havenConfig.Get("username", ""); }
set { havenConfig.Set("username", value); }
}
public string GameHost
{
get { return havenConfig.Get("gamesrv", DefaultHost); }
}
public int GamePort
{
get { return DefaultGamePort; }
}
public string MapUrl
{
get { return havenConfig.Get("mapurl", DefaultMapUrl); }
}
public string ResUrl
{
get { return havenConfig.Get("resurl", DefaultResUrl); }
}
private static void CreateOrLoadIniConfig(IniConfigSource config)
{
var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var configPath = Path.Combine(appDataPath, "sharphaven", "settings.ini");
try
{
config.Load(configPath);
}
catch (Exception)
{
Directory.CreateDirectory(Path.GetDirectoryName(configPath));
config.Save(configPath);
}
}
private static IConfigSource LoadCommandLineConfig()
{
var argvSource = new ArgvConfigSource(Environment.GetCommandLineArgs());
argvSource.AddSwitch("haven", "gamesrv", "g");
argvSource.AddSwitch("haven", "authsrv", "a");
return argvSource;
}
}
}
|
mit
|
C#
|
cd8751f84884bc11c7d9b9452f06eacb6d2c9774
|
Remove distinct tags
|
joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net
|
JoinRpg.Domain/TagExtensions.cs
|
JoinRpg.Domain/TagExtensions.cs
|
using System.Collections.Generic;
using System.Linq;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class TagExtensions
{
public static IEnumerable<string> ExtractTagNames(this string title)
{
return ExtractTagNamesImpl(title).Distinct();
}
private static IEnumerable<string> ExtractTagNamesImpl(string title)
{
for (var i = 0; i < title.Length; i++)
{
if (title[i] != '#') continue;
var tagName = title.Skip(i + 1).TakeWhile(c => char.IsLetterOrDigit(c) || c == '_').AsString().Trim();
if (tagName != "")
{
yield return tagName;
}
}
}
public static string RemoveTagNames(this string title)
{
return title.RemoveFromString(title.ExtractTagNames().Select(tag => "#" + tag)).Trim();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class TagExtensions
{
public static IEnumerable<string> ExtractTagNames(this string title)
{
for (var i = 0; i < title.Length; i++)
{
if (title[i] != '#') continue;
var tagName = title.Skip(i + 1).TakeWhile(c => char.IsLetterOrDigit(c) || c == '_').AsString().Trim();
if (tagName != "")
{
yield return tagName;
}
}
}
public static string RemoveTagNames(this string title)
{
return title.RemoveFromString(title.ExtractTagNames().Select(tag => "#" + tag)).Trim();
}
}
}
|
mit
|
C#
|
e497e87be767abbd2da6a9faf91db699819065fe
|
Delete dead code
|
jasonmalinowski/roslyn,bartdesmet/roslyn,mavasani/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,weltkante/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Indentation/AbstractIndentation.cs
|
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Indentation/AbstractIndentation.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Indentation
{
internal abstract partial class AbstractIndentation<TSyntaxRoot>
where TSyntaxRoot : SyntaxNode, ICompilationUnitSyntax
{
protected abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract IHeaderFacts HeaderFacts { get; }
protected abstract ISyntaxFormatting SyntaxFormatting { get; }
protected abstract AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions2.IndentStyle indentStyle);
/// <summary>
/// Returns <see langword="true"/> if the language specific <see
/// cref="ISmartTokenFormatter"/> should be deferred to figure out indentation. If so, it
/// will be asked to <see cref="ISmartTokenFormatter.FormatTokenAsync"/> the resultant
/// <paramref name="token"/> provided by this method.
/// </summary>
protected abstract bool ShouldUseTokenIndenter(Indenter indenter, out SyntaxToken token);
protected abstract ISmartTokenFormatter CreateSmartTokenFormatter(
TSyntaxRoot root, TextLine lineToBeIndented, IndentationOptions options, AbstractFormattingRule baseFormattingRule);
protected abstract IndentationResult? GetDesiredIndentationWorker(
Indenter indenter, SyntaxToken? token, SyntaxTrivia? trivia);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Indentation
{
internal abstract partial class AbstractIndentation<TSyntaxRoot>
where TSyntaxRoot : SyntaxNode, ICompilationUnitSyntax
{
protected abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract IHeaderFacts HeaderFacts { get; }
protected abstract ISyntaxFormatting SyntaxFormatting { get; }
protected abstract AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions2.IndentStyle indentStyle);
/// <summary>
/// Returns <see langword="true"/> if the language specific <see
/// cref="ISmartTokenFormatter"/> should be deferred to figure out indentation. If so, it
/// will be asked to <see cref="ISmartTokenFormatter.FormatTokenAsync"/> the resultant
/// <paramref name="token"/> provided by this method.
/// </summary>
protected abstract bool ShouldUseTokenIndenter(Indenter indenter, out SyntaxToken token);
protected abstract ISmartTokenFormatter CreateSmartTokenFormatter(
TSyntaxRoot root, TextLine lineToBeIndented, IndentationOptions options, AbstractFormattingRule baseFormattingRule);
protected abstract IndentationResult? GetDesiredIndentationWorker(
Indenter indenter, SyntaxToken? token, SyntaxTrivia? trivia);
#if false
public IndentationResult GetIndentation(
Document document, int lineNumber,
FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var indenter = GetIndenter(document, lineNumber, (FormattingOptions2.IndentStyle)indentStyle, cancellationToken);
if (indentStyle == FormattingOptions.IndentStyle.None)
{
// If there is no indent style, then do nothing.
return new IndentationResult(basePosition: 0, offset: 0);
}
if (indentStyle == FormattingOptions.IndentStyle.Smart &&
indenter.TryGetSmartTokenIndentation(out var indentationResult))
{
return indentationResult;
}
// If the indenter can't produce a valid result, just default to 0 as our indentation.
return indenter.GetDesiredIndentation(indentStyle) ?? default;
}
private Indenter GetIndenter(Document document, int lineNumber, FormattingOptions2.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var options = IndentationOptions.FromDocumentAsync(document, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
var tree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var sourceText = tree.GetText(cancellationToken);
var lineToBeIndented = sourceText.Lines[lineNumber];
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
var baseIndentationRule = formattingRuleFactory.CreateRule(document, lineToBeIndented.Start);
var formattingRules = ImmutableArray.Create(
baseIndentationRule,
this.GetSpecializedIndentationFormattingRule(indentStyle)).AddRange(
Formatter.GetDefaultFormattingRules(document));
var smartTokenFormatter = CreateSmartTokenFormatter(
(TSyntaxRoot)tree.GetRoot(cancellationToken), lineToBeIndented, options, baseIndentationRule);
return new Indenter(this, tree, formattingRules, options, lineToBeIndented, smartTokenFormatter, cancellationToken);
}
#endif
}
}
|
mit
|
C#
|
49ef209c0ef961c98ac4c7a7dd86a4f50a1a776e
|
test generatore fake coordinate intervento
|
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
|
src/backend/SO115App.GeneratoreFakeRichieste.Test/TestGeneratoreCoordinateInterventoPerUO.cs
|
src/backend/SO115App.GeneratoreFakeRichieste.Test/TestGeneratoreCoordinateInterventoPerUO.cs
|
using NUnit.Framework;
using SO115App.GeneratoreRichiesteFake;
namespace Tests
{
public class TestGeneratoreCoordinateInterventoPerUO
{
[Test]
[Repeat(100)]
public void GliInterventiDiTorinoSonoViciniATorino()
{
var generatore = new GeneratoreCoordinateInterventoPerUO();
var coordinate = generatore.Genera("TO.1000");
Assert.That(coordinate.Latitudine, Is.GreaterThan(44.08).And.LessThan(46.08));
Assert.That(coordinate.Longitudine, Is.GreaterThan(6.62).And.LessThan(8.62));
}
[Test]
[Repeat(100)]
public void GliInterventiDiSiracusaSonoViciniASiracusa()
{
var generatore = new GeneratoreCoordinateInterventoPerUO();
var coordinate = generatore.Genera("SR.1000");
Assert.That(coordinate.Latitudine, Is.GreaterThan(36.08).And.LessThan(38.08));
Assert.That(coordinate.Longitudine, Is.GreaterThan(14.18).And.LessThan(16.18));
}
}
}
|
using NUnit.Framework;
using SO115App.GeneratoreRichiesteFake;
namespace Tests
{
public class TestGeneratoreCoordinateInterventoPerUO
{
[Test]
[Repeat(100)]
public void GliInterventiDiTorinoSonoViciniATorino()
{
var generatore = new GeneratoreCoordinateInterventoPerUO();
var coordinate = generatore.Genera("TO");
Assert.That(coordinate.Latitudine, Is.GreaterThan(44.08).And.LessThan(46.08));
Assert.That(coordinate.Longitudine, Is.GreaterThan(6.62).And.LessThan(8.62));
}
[Test]
[Repeat(100)]
public void GliInterventiDiSiracusaSonoViciniASiracusa()
{
var generatore = new GeneratoreCoordinateInterventoPerUO();
var coordinate = generatore.Genera("SR");
Assert.That(coordinate.Latitudine, Is.GreaterThan(36.08).And.LessThan(38.08));
Assert.That(coordinate.Longitudine, Is.GreaterThan(14.18).And.LessThan(16.18));
}
}
}
|
agpl-3.0
|
C#
|
fc2f0faf1421e6c7414b63ebe88df1bfdd201191
|
Fix for #39
|
4nonym0us/aspnetboilerplate,takintsft/aspnetboilerplate,andmattia/aspnetboilerplate,virtualcca/aspnetboilerplate,verdentk/aspnetboilerplate,MetSystem/aspnetboilerplate,nicklv/aspnetboilerplate,zquans/aspnetboilerplate,takintsft/aspnetboilerplate,oceanho/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,Tinkerc/aspnetboilerplate,fengyeju/aspnetboilerplate,gregoriusxu/aspnetboilerplate,ZhaoRd/aspnetboilerplate,liujunhua/aspnetboilerplate,zclmoon/aspnetboilerplate,4nonym0us/aspnetboilerplate,chendong152/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ShiningRush/aspnetboilerplate,gentledepp/aspnetboilerplate,andmattia/aspnetboilerplate,AndHuang/aspnetboilerplate,MDSNet2016/aspnetboilerplate,backendeveloper/aspnetboilerplate,MetSystem/aspnetboilerplate,SecComm/aspnetboilerplate,virtualcca/aspnetboilerplate,SecComm/aspnetboilerplate,LenFon/aspnetboilerplate,hanu412/aspnetboilerplate,SXTSOFT/aspnetboilerplate,Tinkerc/aspnetboilerplate,s-takatsu/aspnetboilerplate,Nongzhsh/aspnetboilerplate,MaikelE/aspnetboilerplate-fork,lemestrez/aspnetboilerplate,ddNils/aspnetboilerplate,dVakulen/aspnetboilerplate,rucila/aspnetboilerplate,AlexGeller/aspnetboilerplate,spraiin/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,fengyeju/aspnetboilerplate,dVakulen/aspnetboilerplate,sagacite2/aspnetboilerplate,SXTSOFT/aspnetboilerplate,lvjunlei/aspnetboilerplate,asauriol/aspnetboilerplate,Tobyee/aspnetboilerplate,fengyeju/aspnetboilerplate,4nonym0us/aspnetboilerplate,ryancyq/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,azhe127/aspnetboilerplate,hanu412/aspnetboilerplate,ryancyq/aspnetboilerplate,beratcarsi/aspnetboilerplate,jaq316/aspnetboilerplate,burakaydemir/aspnetboilerplate,Sivalingaamorthy/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,nicklv/aspnetboilerplate,saeedallahyari/aspnetboilerplate,SXTSOFT/aspnetboilerplate,chenkaibin/aspnetboilerplate,ZhaoRd/aspnetboilerplate,zclmoon/aspnetboilerplate,spraiin/aspnetboilerplate,SecComm/aspnetboilerplate,jaq316/aspnetboilerplate,burakaydemir/aspnetboilerplate,ddNils/aspnetboilerplate,690486439/aspnetboilerplate,Tobyee/aspnetboilerplate,lemestrez/aspnetboilerplate,carldai0106/aspnetboilerplate,jaq316/aspnetboilerplate,beratcarsi/aspnetboilerplate,daywrite/aspnetboilerplate,Nongzhsh/aspnetboilerplate,asauriol/aspnetboilerplate,AlexGeller/aspnetboilerplate,cato541265/aspnetboilerplate,AlexGeller/aspnetboilerplate,FJQBT/ABP,yuzukwok/aspnetboilerplate,zclmoon/aspnetboilerplate,expertmaksud/aspnetboilerplate,690486439/aspnetboilerplate,zquans/aspnetboilerplate,luchaoshuai/aspnetboilerplate,azhe127/aspnetboilerplate,liujunhua/aspnetboilerplate,Tobyee/aspnetboilerplate,690486439/aspnetboilerplate,nineconsult/Kickoff2016Net,daywrite/aspnetboilerplate,ShiningRush/aspnetboilerplate,AntTech/aspnetboilerplate,beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,nineconsult/Kickoff2016Net,berdankoca/aspnetboilerplate,lemestrez/aspnetboilerplate,Saviio/aspnetboilerplate,berdankoca/aspnetboilerplate,luchaoshuai/aspnetboilerplate,s-takatsu/aspnetboilerplate,daywrite/aspnetboilerplate,lidonghao1116/aspnetboilerplate,virtualcca/aspnetboilerplate,jefferyzhang/aspnetboilerplate,yuzukwok/aspnetboilerplate,LenFon/aspnetboilerplate,ryancyq/aspnetboilerplate,MaikelE/aspnetboilerplate-fork,Nongzhsh/aspnetboilerplate,chendong152/aspnetboilerplate,chenkaibin/aspnetboilerplate,saeedallahyari/aspnetboilerplate,gregoriusxu/aspnetboilerplate,ilyhacker/aspnetboilerplate,lidonghao1116/aspnetboilerplate,berdankoca/aspnetboilerplate,sagacite2/aspnetboilerplate,lvjunlei/aspnetboilerplate,MDSNet2016/aspnetboilerplate,FJQBT/ABP,chenkaibin/aspnetboilerplate,yhhno/aspnetboilerplate,Saviio/aspnetboilerplate,carldai0106/aspnetboilerplate,ShiningRush/aspnetboilerplate,cato541265/aspnetboilerplate,oceanho/aspnetboilerplate,anhuisunfei/aspnetboilerplate,ddNils/aspnetboilerplate,AndHuang/aspnetboilerplate,ilyhacker/aspnetboilerplate,jefferyzhang/aspnetboilerplate,rucila/aspnetboilerplate,yuzukwok/aspnetboilerplate,backendeveloper/aspnetboilerplate,carldai0106/aspnetboilerplate,Sivalingaamorthy/aspnetboilerplate,AndHuang/aspnetboilerplate,AntTech/aspnetboilerplate,ZhaoRd/aspnetboilerplate,andmattia/aspnetboilerplate,MaikelE/aspnetboilerplate-fork,anhuisunfei/aspnetboilerplate,zquans/aspnetboilerplate,luenick/aspnetboilerplate,gentledepp/aspnetboilerplate,lvjunlei/aspnetboilerplate,ryancyq/aspnetboilerplate,luenick/aspnetboilerplate,yhhno/aspnetboilerplate,oceanho/aspnetboilerplate,s-takatsu/aspnetboilerplate,expertmaksud/aspnetboilerplate,verdentk/aspnetboilerplate
|
src/Abp/Framework/Abp/Domain/Uow/UnitOfWorkRegistrer.cs
|
src/Abp/Framework/Abp/Domain/Uow/UnitOfWorkRegistrer.cs
|
using System.Linq;
using System.Reflection;
using Abp.Startup;
using Castle.Core;
using Castle.MicroKernel;
namespace Abp.Domain.Uow
{
/// <summary>
/// This class is used to register interceptor for needed classes for Unit Of Work mechanism.
/// </summary>
public static class UnitOfWorkRegistrer
{
/// <summary>
/// Initializes the registerer.
/// </summary>
/// <param name="initializationContext">Initialization context</param>
public static void Initialize(IAbpInitializationContext initializationContext)
{
initializationContext.IocContainer.Kernel.ComponentRegistered += ComponentRegistered;
}
private static void ComponentRegistered(string key, IHandler handler)
{
if (UnitOfWorkHelper.IsConventionalUowClass(handler.ComponentModel.Implementation))
{
//Intercept all methods of all repositories.
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
}
else if (handler.ComponentModel.Implementation.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(UnitOfWorkHelper.HasUnitOfWorkAttribute))
{
//Intercept all methods of classes those have at least one method that has UnitOfWork attribute.
//TODO: Intecept only UnitOfWork methods, not other methods!
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
}
}
}
}
|
using System.Linq;
using Abp.Startup;
using Castle.Core;
using Castle.MicroKernel;
namespace Abp.Domain.Uow
{
/// <summary>
/// This class is used to register interceptor for needed classes for Unit Of Work mechanism.
/// </summary>
public static class UnitOfWorkRegistrer
{
/// <summary>
/// Initializes the registerer.
/// </summary>
/// <param name="initializationContext">Initialization context</param>
public static void Initialize(IAbpInitializationContext initializationContext)
{
initializationContext.IocContainer.Kernel.ComponentRegistered += ComponentRegistered;
}
private static void ComponentRegistered(string key, IHandler handler)
{
if (UnitOfWorkHelper.IsConventionalUowClass(handler.ComponentModel.Implementation))
{
//Intercept all methods of all repositories.
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
}
else if (handler.ComponentModel.Implementation.GetMethods().Any(UnitOfWorkHelper.HasUnitOfWorkAttribute))
{
//Intercept all methods of classes those have at least one method that has UnitOfWork attribute.
//TODO: Intecept only UnitOfWork methods, not other methods!
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
}
}
}
}
|
mit
|
C#
|
7716a96b2848d32d1e49c932d8a25d19a877aa02
|
Allow scrolling through DimmedLoadingLayer
|
2yangk23/osu,peppy/osu-new,smoogipoo/osu,2yangk23/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu
|
osu.Game/Graphics/UserInterface/DimmedLoadingLayer.cs
|
osu.Game/Graphics/UserInterface/DimmedLoadingLayer.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Extensions.Color4Extensions;
using osuTK;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class DimmedLoadingLayer : OverlayContainer
{
private const float transition_duration = 250;
private readonly LoadingAnimation loading;
public DimmedLoadingLayer(float dimAmount = 0.5f, float iconScale = 1f)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(dimAmount),
},
loading = new LoadingAnimation { Scale = new Vector2(iconScale) },
};
}
protected override void PopIn()
{
this.FadeIn(transition_duration, Easing.OutQuint);
loading.Show();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.OutQuint);
loading.Hide();
}
protected override bool Handle(UIEvent e)
{
switch (e)
{
case ScrollEvent _:
return false;
}
return base.Handle(e);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Extensions.Color4Extensions;
using osuTK;
namespace osu.Game.Graphics.UserInterface
{
public class DimmedLoadingLayer : OverlayContainer
{
private const float transition_duration = 250;
private readonly LoadingAnimation loading;
public DimmedLoadingLayer(float dimAmount = 0.5f, float iconScale = 1f)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(dimAmount),
},
loading = new LoadingAnimation { Scale = new Vector2(iconScale) },
};
}
protected override void PopIn()
{
this.FadeIn(transition_duration, Easing.OutQuint);
loading.Show();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.OutQuint);
loading.Hide();
}
}
}
|
mit
|
C#
|
5f1d902ffcfe5fa5540edc741bc4caa77313b0e6
|
Align assembly verions with package release 2.0.3
|
bfreese/ExCSS
|
ExCSS/Properties/AssemblyInfo.cs
|
ExCSS/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("ExCSS Parser")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExCSS CSS Parser")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("eb4daa16-725f-4c8f-9d74-b9b569d57f42")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.3")]
[assembly: AssemblyFileVersion("2.0.3")]
|
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("ExCSS Parser")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExCSS CSS Parser")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("eb4daa16-725f-4c8f-9d74-b9b569d57f42")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.2")]
[assembly: AssemblyFileVersion("2.0.2")]
|
mit
|
C#
|
1e821b0f60de97419234b7343366a1d1ced602fc
|
Update TrieNode.cs
|
ibendrup/LevenshteinAutomaton
|
LevenshteinAutomaton/TrieNode.cs
|
LevenshteinAutomaton/TrieNode.cs
|
using System;
using System.Collections.Generic;
namespace LevenshteinAutomaton
{
/// <summary>
/// Prefix tree node
/// </summary>
public class TrieNode
{
/// <summary>
/// Node's key
/// </summary>
public readonly String Key;
/// <summary>
/// Children node list
/// </summary>
public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>();
/// <summary>
/// Init node with the given key
/// </summary>
/// <param name="key">Key</param>
public TrieNode(String key) {
Key = key;
}
/// <summary>
/// Add child node
/// </summary>
/// <param name="c">Letter</param>
/// <param name="child">Node to add</param>
/// <returns></returns>
public bool AddChild(char c, TrieNode child)
{
Children.Add(c, child);
return true;
}
/// <summary>
/// Check if node contains child for given letter
/// </summary>
public bool ContainsChildValue(char letter) {
return Children.ContainsKey(letter);
}
/// <summary>
/// Get child node by letter
/// </summary>
public TrieNode GetChild(char letter)
{
if (Children.ContainsKey(letter))
return Children[letter];
else
return null;
}
/// <summary>
/// The node represents word
/// </summary>
public bool IsWord { get; set; }
/// <summary>
/// Get node for given word or prefix if exists
/// </summary>
public TrieNode GetChild(String wordOrPrefix)
{
return string.IsNullOrEmpty(wordOrPrefix) ? null : GetChild(wordOrPrefix.ToCharArray());
}
/// <summary>
/// Get node for given char array
/// </summary>
public TrieNode GetChild(char[] letters)
{
TrieNode currentNode = this;
for (int i = 0; i < letters.Length && currentNode != null; i++)
{
currentNode = currentNode.GetChild(letters[i]);
if (currentNode == null)
{
return null;
}
}
return currentNode;
}
/// <summary>
/// Get node for given word if exists
/// </summary>
public TrieNode GetWord(string word)
{
TrieNode node = GetChild(word);
return node != null && node.IsWord ? node : null;
}
public override String ToString() {
return Key;
}
}
}
|
using System;
using System.Collections.Generic;
namespace LevenshteinAutomaton
{
/// <summary>
/// Prefix tree node
/// </summary>
public class TrieNode
{
/// <summary>
/// Node's key
/// </summary>
public readonly String Key;
/// <summary>
/// Перечень дочерних узлов
/// </summary>
public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>();
/// <summary>
/// Init node with the given key
/// </summary>
/// <param name="key">Key</param>
public TrieNode(String key) {
Key = key;
}
/// <summary>
/// Add child node
/// </summary>
/// <param name="c">Letter</param>
/// <param name="child">Node to add</param>
/// <returns></returns>
public bool AddChild(char c, TrieNode child)
{
Children.Add(c, child);
return true;
}
/// <summary>
/// Check if node contains child for given letter
/// </summary>
public bool ContainsChildValue(char letter) {
return Children.ContainsKey(letter);
}
/// <summary>
/// Get child node by letter
/// </summary>
public TrieNode GetChild(char letter)
{
if (Children.ContainsKey(letter))
return Children[letter];
else
return null;
}
/// <summary>
/// The node represents word
/// </summary>
public bool IsWord { get; set; }
/// <summary>
/// Get node for given word or prefix if exists
/// </summary>
public TrieNode GetChild(String wordOrPrefix)
{
return string.IsNullOrEmpty(wordOrPrefix) ? null : GetChild(wordOrPrefix.ToCharArray());
}
/// <summary>
/// Get node for given char array
/// </summary>
public TrieNode GetChild(char[] letters)
{
TrieNode currentNode = this;
for (int i = 0; i < letters.Length && currentNode != null; i++)
{
currentNode = currentNode.GetChild(letters[i]);
if (currentNode == null)
{
return null;
}
}
return currentNode;
}
/// <summary>
/// Get node for given word if exists
/// </summary>
public TrieNode GetWord(string word)
{
TrieNode node = GetChild(word);
return node != null && node.IsWord ? node : null;
}
public override String ToString() {
return Key;
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.