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 |
|---|---|---|---|---|---|---|---|---|
5206ef95ab19361dc729fbf69050abd9ebfd6dbd
|
Update Program.cs
|
natintosh/Numerical-Methods
|
NumericalMethods/GaussJordan/GaussJordan/Program.cs
|
NumericalMethods/GaussJordan/GaussJordan/Program.cs
|
using System;
namespace GaussJordan
{
class MainClass : NumericalMethods
{
public static void Main()
{
Double[,] matrix = { { 25, 5, 1, 106.8 }, { 64, 8, 1, 177.2 }, { 144, 12, 1, 292.2 } };
ForwardElimination forwardElimination = new ForwardElimination(ref matrix);
forwardElimination.Eliminate();
BackwardSubstitution backwardSubstitution = new BackwardSubstitution(matrix);
backwardSubstitution.Substitute();
}
}
}
|
using System;
namespace GaussJordan
{
class MainClass : NumericalMethods
{
public static void Main()
{
Double[,] matrix = { { 1, 2, 1, 4 }, { 3, -4, -2, 2 }, { 5, 3, 5, -1 } };
ForwardElimination forwardElimination = new ForwardElimination(ref matrix);
forwardElimination.Eliminate();
BackwardSubstitution backwardSubstitution = new BackwardSubstitution(matrix);
backwardSubstitution.Substitute();
}
}
}
|
mit
|
C#
|
d64c15bea4cb31f903663660dcfd15059e11c81b
|
Debug mode only enabled for Debug Build configuration
|
Jeern/SimpleEventMonitor,Jeern/SimpleEventMonitor,Jeern/SimpleEventMonitor
|
SimpleEventMonitor.Web/AppHostSimpleEventMonitor.cs
|
SimpleEventMonitor.Web/AppHostSimpleEventMonitor.cs
|
using System.Reflection;
using Funq;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
using SimpleEventMonitor.Core;
namespace SimpleEventMonitor.Web
{
public class AppHostSimpleEventMonitor : AppHostBase
{
public AppHostSimpleEventMonitor(IEventDataStore dataStore)
: base("SimpleEventMonitorServices", Assembly.GetExecutingAssembly())
{
Container.Register(dataStore);
}
public override void Configure(Container container)
{
#if DEBUG
bool debug = true;
var enableFeatures = Feature.All;
#else
bool debug = false;
var enableFeatures = Feature.All.Remove(Feature.Metadata);
#endif
JsConfig.IncludeNullValues = true;
SetConfig(
new EndpointHostConfig
{
DebugMode = debug,
DefaultContentType = ContentType.Json,
EnableFeatures = enableFeatures
});
}
}
}
|
using System.Reflection;
using Funq;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
using SimpleEventMonitor.Core;
namespace SimpleEventMonitor.Web
{
public class AppHostSimpleEventMonitor : AppHostBase
{
public AppHostSimpleEventMonitor(IEventDataStore dataStore)
: base("SimpleEventMonitorServices", Assembly.GetExecutingAssembly())
{
Container.Register(dataStore);
}
public override void Configure(Container container)
{
JsConfig.IncludeNullValues = true;
SetConfig(
new EndpointHostConfig
{
DebugMode = true,
DefaultContentType = ContentType.Json,
EnableFeatures = Feature.All
});
}
}
}
|
mit
|
C#
|
fb893aa152a049a319b0abc354e0623d2efc628f
|
Add the missing newline
|
vers-one/EpubReader
|
Source/VersOne.Epub.ConsoleDemo/ExtractPlainText.cs
|
Source/VersOne.Epub.ConsoleDemo/ExtractPlainText.cs
|
using System;
using System.Text;
using HtmlAgilityPack;
namespace VersOne.Epub.ConsoleDemo
{
internal static class ExtractPlainText
{
public static void Run(string filePath)
{
EpubBook book = EpubReader.ReadBook(filePath);
foreach (EpubTextContentFile textContentFile in book.ReadingOrder)
{
PrintTextContentFile(textContentFile);
}
}
private static void PrintTextContentFile(EpubTextContentFile textContentFile)
{
HtmlDocument htmlDocument = new();
htmlDocument.LoadHtml(textContentFile.Content);
StringBuilder sb = new();
foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//text()"))
{
sb.AppendLine(node.InnerText.Trim());
}
string contentText = sb.ToString();
Console.WriteLine(contentText);
Console.WriteLine();
}
}
}
|
using System;
using System.Text;
using HtmlAgilityPack;
namespace VersOne.Epub.ConsoleDemo
{
internal static class ExtractPlainText
{
public static void Run(string filePath)
{
EpubBook book = EpubReader.ReadBook(filePath);
foreach (EpubTextContentFile textContentFile in book.ReadingOrder)
{
PrintTextContentFile(textContentFile);
}
}
private static void PrintTextContentFile(EpubTextContentFile textContentFile)
{
HtmlDocument htmlDocument = new();
htmlDocument.LoadHtml(textContentFile.Content);
StringBuilder sb = new();
foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//text()"))
{
sb.AppendLine(node.InnerText.Trim());
}
string contentText = sb.ToString();
Console.WriteLine(contentText);
Console.WriteLine();
}
}
}
|
unlicense
|
C#
|
b00921c8768b3914419bb7407ba3d7c8f3da82f5
|
test no import
|
jezzay/Test-Travis-CI,jezzay/Test-Travis-CI
|
TestWebApp/TestWebApp/Controllers/HomeController.cs
|
TestWebApp/TestWebApp/Controllers/HomeController.cs
|
using System.Web.Mvc;
namespace TestWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page test";
var data = new {firstname = "test", lastname = "lastname"};
string json = JsonConvert.SerializeObject(data);
return View();
}
}
}
|
using System.Web.Mvc;
using Newtonsoft.Json;
namespace TestWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page test";
var data = new {firstname = "test", lastname = "lastname"};
string json = JsonConvert.SerializeObject(data);
return View();
}
}
}
|
mit
|
C#
|
194bd95c8780f275a7e50da865c16dca76bc5577
|
Remove comments on internals.
|
jgoz/netzmq,jgoz/netzmq,jgoz/netzmq,jgoz/netzmq,jgoz/netzmq
|
src/proj/ZeroMQ/Interop/PollItem.cs
|
src/proj/ZeroMQ/Interop/PollItem.cs
|
namespace ZeroMQ.Interop
{
using System;
using System.Runtime.InteropServices;
[Flags]
internal enum PollEvent
{
PollIn = 0x1,
PollOut = 0x2,
PollErr = 0x4
}
[StructLayout(LayoutKind.Sequential)]
internal struct PollItem
{
// ReSharper disable FieldCanBeMadeReadOnly.Local
private IntPtr socket;
#if POSIX
private int fd;
#else
private IntPtr fd;
#endif
// ReSharper restore FieldCanBeMadeReadOnly.Local
private short events;
private short revents;
internal PollItem(IntPtr socket, IntPtr fd, short events)
{
this.socket = socket;
this.events = events;
this.revents = 0;
#if POSIX
this.fd = fd.ToInt32();
#else
this.fd = fd;
#endif
}
public PollEvent Revents
{
get { return (PollEvent)this.revents; }
}
public void ResetRevents()
{
this.revents = 0;
}
internal void ActivateEvent(params PollEvent[] evts)
{
foreach (PollEvent evt in evts)
{
this.events = (short)(this.events | (short)evt);
}
}
internal void DeactivateEvent(params PollEvent[] evts)
{
foreach (PollEvent evt in evts)
{
this.events &= (short)evt;
}
}
}
}
|
namespace ZeroMQ.Interop
{
using System;
using System.Runtime.InteropServices;
[Flags]
internal enum PollEvent
{
PollIn = 0x1,
PollOut = 0x2,
PollErr = 0x4
}
[StructLayout(LayoutKind.Sequential)]
internal struct PollItem
{
#pragma warning disable 414
private readonly IntPtr socket;
#if POSIX
private int fd;
#else
private readonly IntPtr fd;
#endif
private short events;
private short revents;
#pragma warning restore
/// <summary>
/// Initializes a new instance of the PollItem struct.
/// </summary>
/// <param name="socket">Target ZMQ socket ptr</param>
/// <param name="fd">Non ZMQ socket (Not Supported)</param>
/// <param name="events">Desired events</param>
internal PollItem(IntPtr socket, IntPtr fd, short events)
{
this.socket = socket;
this.events = events;
this.revents = 0;
#if POSIX
this.fd = fd.ToInt32();
#else
this.fd = fd;
#endif
}
/// <summary>
/// Gets returned event flags
/// </summary>
public PollEvent Revents
{
get { return (PollEvent)this.revents; }
}
/// <summary>
/// Reset revents so that poll item can be safely reused
/// </summary>
public void ResetRevents()
{
this.revents = 0;
}
internal void ActivateEvent(params PollEvent[] evts)
{
foreach (PollEvent evt in evts)
{
this.events = (short)(this.events | (short)evt);
}
}
internal void DeactivateEvent(params PollEvent[] evts)
{
foreach (PollEvent evt in evts)
{
this.events &= (short)evt;
}
}
}
}
|
apache-2.0
|
C#
|
b09c4b0b51f11695c349d6537318af5a3fe7b584
|
Update RecordsControl.xaml.cs
|
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
|
src/Core2D.UI/Views/Data/RecordsControl.xaml.cs
|
src/Core2D.UI/Views/Data/RecordsControl.xaml.cs
|
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Markup.Xaml;
using Core2D.Data;
using DocumentFormat.OpenXml.InkML;
using System.ComponentModel;
using System.Reactive;
namespace Core2D.UI.Views.Data
{
/// <summary>
/// Interaction logic for <see cref="RecordsControl"/> xaml.
/// </summary>
public class RecordsControl : UserControl
{
private DataGrid _rowsDataGrid;
private IDatabase _database;
/// <summary>
/// Initializes a new instance of the <see cref="RecordsControl"/> class.
/// </summary>
public RecordsControl()
{
InitializeComponent();
_rowsDataGrid = this.FindControl<DataGrid>("rowsDataGrid");
DataContextChanged += RecordsControl_DataContextChanged;
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void RecordsControl_DataContextChanged(object sender, System.EventArgs e)
{
if (_database != null)
{
_database.PropertyChanged -= Database_PropertyChanged;
_database = null;
}
ResetColumns();
if (DataContext is IDatabase database)
{
_database = database;
_database.PropertyChanged += Database_PropertyChanged;
CreateColumns();
}
}
private void Database_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Columns")
{
if (_database != null)
{
ResetColumns();
CreateColumns();
}
}
}
private void Column_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Name")
{
if (_database != null)
{
UpdateHeaders();
}
}
}
private void CreateColumns()
{
for (int i = 0; i < _database.Columns.Length; i++)
{
var column = _database.Columns[i];
var dataGridTextColumn = new DataGridTextColumn()
{
Header = $"{column.Name}",
Binding = new Binding($"Values[{i}].Content"),
IsReadOnly = true
};
column.PropertyChanged += Column_PropertyChanged;
_rowsDataGrid.Columns.Add(dataGridTextColumn);
}
}
private void ResetColumns()
{
_rowsDataGrid.Columns.Clear();
}
private void UpdateHeaders()
{
for (int i = 0; i < _database.Columns.Length; i++)
{
var column = _database.Columns[i];
_rowsDataGrid.Columns[i].Header = column.Name;
}
}
}
}
|
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Core2D.UI.Views.Data
{
/// <summary>
/// Interaction logic for <see cref="RecordsControl"/> xaml.
/// </summary>
public class RecordsControl : UserControl
{
/// <summary>
/// Initializes a new instance of the <see cref="RecordsControl"/> class.
/// </summary>
public RecordsControl()
{
InitializeComponent();
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
|
mit
|
C#
|
03d4931137d73f7f55f5e4a62b3b26dab0ca7827
|
add comment
|
bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL
|
CSharpGL/NewFontResource/FontTexture.cs
|
CSharpGL/NewFontResource/FontTexture.cs
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace CSharpGL.NewFontResource
{
/// <summary>
/// font, texture and texture coordiante.
/// </summary>
public partial class FontTexture : IDisposable
{
/// <summary>
/// Texture's id.
/// </summary>
public uint FontTextureId { get; private set; }
/// <summary>
/// font of glyphs.
/// </summary>
internal Font font;
/// <summary>
/// glyph information dictionary.
/// </summary>
internal FullDictionary<char, GlyphInfo> glyphInfoDictionary;
internal FontTexture(Font font, FullDictionary<char, GlyphInfo> dict)
{
this.font = font;
this.glyphInfoDictionary = dict;
}
/// <summary>
///
/// </summary>
public samplerValue GetSamplerValue()
{
return new samplerValue(
BindTextureTarget.Texture2D,
this.FontTextureId,
OpenGL.GL_TEXTURE0);
}
internal void Initialize(TextureBuilder textureBuilder, Bitmap bitmap)
{
this.FontTextureId = textureBuilder.BuildTexture(bitmap);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace CSharpGL.NewFontResource
{
/// <summary>
/// font, texture and texture coordiante.
/// </summary>
public partial class FontTexture : IDisposable
{
/// <summary>
/// 含有各个字形的贴图的Id。
/// </summary>
public uint FontTextureId { get; private set; }
/// <summary>
/// font of glyphs.
/// </summary>
internal Font font;
///// <summary>
///// bitmap in which glyphs is printed.
///// </summary>
//internal Bitmap glyphBitmap;
/// <summary>
/// glyph information dictionary.
/// </summary>
internal FullDictionary<char, GlyphInfo> glyphInfoDictionary;
internal FontTexture(Font font, FullDictionary<char, GlyphInfo> dict)
{
this.font = font;
this.glyphInfoDictionary = dict;
}
/// <summary>
///
/// </summary>
public samplerValue GetSamplerValue()
{
return new samplerValue(
BindTextureTarget.Texture2D,
this.FontTextureId,
OpenGL.GL_TEXTURE0);
}
internal void Initialize(TextureBuilder textureBuilder, Bitmap bitmap)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
12e1d1d17912c4464cd56307fd815685decae00b
|
Update to assembly version.
|
emerbrito/ILMerge-MSBuild-Task
|
ILMerge.MSBuild.Task/ILMerge.MSBuild.Task/Properties/AssemblyInfo.cs
|
ILMerge.MSBuild.Task/ILMerge.MSBuild.Task/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("ILMerge.MSBuild.Task")]
[assembly: AssemblyDescription("ILMerge Configurable MSBuild Task")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Emerson Brito")]
[assembly: AssemblyProduct("ILMerge.MSBuild.Task")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("43fd3a69-730f-4fa0-9036-0897f3b758ee")]
// 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.3.0")]
[assembly: AssemblyFileVersion("1.0.3.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("ILMerge.MSBuild.Task")]
[assembly: AssemblyDescription("ILMerge Configurable MSBuild Task")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Emerson Brito")]
[assembly: AssemblyProduct("ILMerge.MSBuild.Task")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("43fd3a69-730f-4fa0-9036-0897f3b758ee")]
// 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.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
|
mit
|
C#
|
d7650f2c5f284c8cd55c72975a9a44f2b6352a67
|
Add preflop ranges
|
DataBaseExam/TexasHold-em-AI
|
Source/TexasHoldem.AI.RaiseTwoSevenTestPlayer/RaiseTwoSevenPlayer.cs
|
Source/TexasHoldem.AI.RaiseTwoSevenTestPlayer/RaiseTwoSevenPlayer.cs
|
namespace TexasHoldem.AI.RaiseTwoSevenTestPlayer
{
using System;
using TexasHoldem.Logic.Players;
using TexasHoldem.Logic.Cards;
using Logic;
public class RaiseTwoSevenPlayer : BasePlayer
{
public override string Name { get; } = "RaiseTwoSeven";
public override PlayerAction GetTurn(GetTurnContext context)
{
if (context.RoundType == GameRoundType.PreFlop)
{
if (context.MoneyLeft / context.SmallBlind > 100)
{
}
}
if (FirstCard.Type == CardType.Two && SecondCard.Type == CardType.Seven
|| SecondCard.Type == CardType.Two && FirstCard.Type == CardType.Seven)
{
return PlayerAction.Raise(context.MoneyLeft);
}
else
{
return PlayerAction.Fold();
}
}
}
}
|
namespace TexasHoldem.AI.RaiseTwoSevenTestPlayer
{
using System;
using TexasHoldem.Logic.Players;
using TexasHoldem.Logic.Cards;
using Logic;
public class RaiseTwoSevenPlayer : BasePlayer
{
public override string Name { get; } = "RaiseTwoSeven";
public override PlayerAction GetTurn(GetTurnContext context)
{
if (context.RoundType == GameRoundType.PreFlop)
{
if (context.MoneyLeft / context.SmallBlind > 100)
{
//
}
}
if (FirstCard.Type == CardType.Two && SecondCard.Type == CardType.Seven
|| SecondCard.Type == CardType.Two && FirstCard.Type == CardType.Seven)
{
return PlayerAction.Raise(context.MoneyLeft);
}
else
{
return PlayerAction.Fold();
}
}
}
}
|
mit
|
C#
|
142f94f5d551192754b1ef70b6d4bb3c74bd538e
|
Create directory if not exists.
|
riganti/infrastructure
|
src/Infrastructure/Riganti.Utils.Infrastructure.Services.Mailing/PickupFolderMailSender.cs
|
src/Infrastructure/Riganti.Utils.Infrastructure.Services.Mailing/PickupFolderMailSender.cs
|
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Riganti.Utils.Infrastructure.Services.Mailing
{
public class PickupFolderMailSender : IMailSender
{
public string FolderName { get; }
public PickupFolderMailSender(string folderName)
{
if (folderName == null) throw new ArgumentNullException(nameof(folderName));
if (string.IsNullOrWhiteSpace(folderName)) throw new ArgumentException("Value cannot be empty or whitespace only string.", nameof(folderName));
FolderName = folderName;
}
public async Task SendAsync(MailMessageDTO message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
// Convert to message
var msg = message.ToMimeMessage();
// Write to temp file to avoid pickup of incomplete message
var tempFileName = Path.GetTempFileName();
using (var sw = File.CreateText(tempFileName))
{
// Write envelope sender
await sw.WriteLineAsync($"X-Sender: <{message.From.Address}>");
// Write envelope receivers
var receivers = message.To
.Union(message.Cc)
.Union(message.Bcc);
foreach (var item in receivers.Select(x => x.Address))
{
await sw.WriteLineAsync($"X-Receiver: <{item}>");
}
// Flush data and write rest of message
await sw.FlushAsync();
msg.WriteTo(sw.BaseStream);
}
var msgFileName = Path.Combine(FolderName, string.Join(".", DateTime.Now.ToString("yyyyMMdd-HHmmss"), Guid.NewGuid().ToString("N"), "eml"));
// Create final directory if not exists
if (!Directory.Exists(FolderName))
{
Directory.CreateDirectory(FolderName);
}
// Move the file to final destination
File.Move(tempFileName, msgFileName);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Riganti.Utils.Infrastructure.Services.Mailing
{
public class PickupFolderMailSender : IMailSender
{
public string FolderName { get; }
public PickupFolderMailSender(string folderName)
{
if (folderName == null) throw new ArgumentNullException(nameof(folderName));
if (string.IsNullOrWhiteSpace(folderName)) throw new ArgumentException("Value cannot be empty or whitespace only string.", nameof(folderName));
this.FolderName = folderName;
}
public async Task SendAsync(MailMessageDTO message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
// Convert to message
var msg = message.ToMimeMessage();
// Write to temp file to avoid pickup of incomplete message
var tempFileName = Path.GetTempFileName();
using (var sw = File.CreateText(tempFileName))
{
// Write envelope sender
await sw.WriteLineAsync($"X-Sender: <{message.From.Address}>");
// Write envelope receivers
var receivers = message.To
.Union(message.Cc)
.Union(message.Bcc);
foreach (var item in receivers.Select(x => x.Address))
{
await sw.WriteLineAsync($"X-Receiver: <{item}>");
}
// Flush data and write rest of message
await sw.FlushAsync();
msg.WriteTo(sw.BaseStream);
}
// Move the file to final destination
var msgFileName = Path.Combine(this.FolderName, string.Join(".", DateTime.Now.ToString("yyyyMMdd-HHmmss"), Guid.NewGuid().ToString("N"), "eml"));
File.Move(tempFileName, msgFileName);
}
}
}
|
apache-2.0
|
C#
|
c063f5fd28d31c5c791ded98eb73c3b4a9f67feb
|
Fix screen capture durring test failure
|
rcasady616/Selenium.WeDriver.Equip,rcasady616/Selenium.WeDriver.Equip
|
Selenium.WebDriver.Equip/TestCapture.cs
|
Selenium.WebDriver.Equip/TestCapture.cs
|
using OpenQA.Selenium;
using System;
using System.IO;
using System.Reflection;
namespace Selenium.WebDriver.Equip
{
public class TestCapture
{
private IWebDriver _browser = null;
private string fileName;
public TestCapture(IWebDriver iWebDriver, string type = "Failed")
{
fileName = $@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\{DateTime.Now.Ticks}.{type}";
_browser = iWebDriver;
}
public void CaptureWebPage()
{
WebDriverLogsLogs();
PageSource();
ScreenShot();
}
public void PageSource()
{
string htmlFile = $"{fileName}.html";
using (var sw = new StreamWriter(htmlFile, false))
sw.Write(_browser.PageSource);
}
public void ScreenShot()
{
_browser.TakeScreenShot(fileName + ".jpeg", ScreenshotImageFormat.Jpeg);
}
public void WebDriverLogsLogs()
{
foreach (var log in _browser.Manage().Logs.AvailableLogTypes)
using (var sw = new StreamWriter($"{fileName}.{log}.log", false))
foreach (var logentry in _browser.Manage().Logs.GetLog(log))
sw.WriteLine(logentry);
}
}
}
|
using System;
using System.Drawing.Imaging;
using System.IO;
using OpenQA.Selenium;
namespace Selenium.WebDriver.Equip
{
public class TestCapture
{
private IWebDriver _browser = null;
private string fileName;
public TestCapture(IWebDriver iWebDriver, string type = "Failed")
{
fileName = string.Format(@"{0}\{1}.{2}", Directory.GetCurrentDirectory(), DateTime.Now.Ticks, type);
_browser = iWebDriver;
}
public void CaptureWebPage()
{
WebDriverLogsLogs();
PageSource();
ScreenShot();
}
public void PageSource()
{
string htmlFile = string.Format(@"{0}.html", fileName);
using (var sw = new StreamWriter(htmlFile, false))
sw.Write(_browser.PageSource);
}
public void ScreenShot()
{
_browser.TakeScreenShot(fileName + ".jpeg", ScreenshotImageFormat.Jpeg);
}
public void WebDriverLogsLogs()
{
foreach (var log in _browser.Manage().Logs.AvailableLogTypes)
using (var sw = new StreamWriter(string.Format(@"{0}.{1}.log", fileName, log), false))
foreach (var logentry in _browser.Manage().Logs.GetLog(log))
sw.WriteLine(logentry);
}
}
}
|
mit
|
C#
|
c4621ca3170f10863c48bdf41dc0a784d47afa43
|
Load resources from multiple sources
|
k-t/SharpHaven
|
SharpHaven/Resources/ResourceManager.cs
|
SharpHaven/Resources/ResourceManager.cs
|
using System;
using System.Collections.Generic;
using System.Drawing;
using NLog;
using OpenTK;
using SharpFont;
using SharpHaven.Game;
using SharpHaven.Graphics;
using SharpHaven.Graphics.Sprites;
namespace SharpHaven.Resources
{
public class ResourceManager
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private readonly List<IResourceSource> sources;
private readonly Dictionary<Type, ResourceObjectCache> objectCaches;
private readonly Dictionary<Type, IObjectFactory<object>> objectFactories;
public ResourceManager()
{
sources = new List<IResourceSource>();
objectCaches = new Dictionary<Type, ResourceObjectCache>();
objectFactories = new Dictionary<Type, IObjectFactory<object>>();
var drawableFactory = new DrawableFactory();
RegisterType(typeof(Drawable), drawableFactory);
RegisterType(typeof(Skill), new SkillFactory(drawableFactory));
RegisterType(typeof(Bitmap), new BitmapFactory());
RegisterType(typeof(MouseCursor), new MouseCursorFactory());
RegisterType(typeof(Face), new FontFaceFactory());
RegisterType(typeof(Tileset), new TilesetFactory());
RegisterType(typeof(SpriteMaker), new SpriteMakerFactory());
RegisterType(typeof(GameAction), new GameActionFactory());
RegisterType(typeof(ItemMold), new ItemMoldFactory(drawableFactory));
RegisterType(typeof(BuffMold), new BuffMoldFactory(drawableFactory));
AddSource(new FolderSource("Data"));
AddSource(new JarSource("haven-res.jar"));
}
public void AddSource(IResourceSource source)
{
sources.Add(source);
}
public T Get<T>(string resName) where T : class
{
var cache = objectCaches[typeof(T)];
var obj = cache.Get(resName) as T;
if (obj == null)
{
var res = Load(resName);
var factory = objectFactories[typeof(T)];
obj = (T)factory.Create(resName, res);
cache.Add(resName, obj);
}
return obj;
}
public ISprite GetSprite(string resName, byte[] state = null)
{
var maker = Get<SpriteMaker>(resName);
return maker.MakeInstance(state);
}
public Resource Load(string resName)
{
foreach (var source in sources)
{
try
{
var res = source.Get(resName);
if (res != null)
return res;
}
catch (Exception ex)
{
Log.Debug(ex);
}
}
throw new ResourceException("Couldn't load resource " + resName);
}
private void RegisterType(Type type, IObjectFactory<object> factory)
{
objectFactories[type] = factory;
objectCaches[type] = new ResourceObjectCache();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using OpenTK;
using SharpFont;
using SharpHaven.Game;
using SharpHaven.Graphics;
using SharpHaven.Graphics.Sprites;
namespace SharpHaven.Resources
{
public class ResourceManager
{
private readonly IResourceSource defaultSource = new FolderSource("Data");
private readonly Dictionary<Type, ResourceObjectCache> objectCaches;
private readonly Dictionary<Type, IObjectFactory<object>> objectFactories;
public ResourceManager()
{
objectCaches = new Dictionary<Type, ResourceObjectCache>();
objectFactories = new Dictionary<Type, IObjectFactory<object>>();
var drawableFactory = new DrawableFactory();
RegisterType(typeof(Drawable), drawableFactory);
RegisterType(typeof(Skill), new SkillFactory(drawableFactory));
RegisterType(typeof(Bitmap), new BitmapFactory());
RegisterType(typeof(MouseCursor), new MouseCursorFactory());
RegisterType(typeof(Face), new FontFaceFactory());
RegisterType(typeof(Tileset), new TilesetFactory());
RegisterType(typeof(SpriteMaker), new SpriteMakerFactory());
RegisterType(typeof(GameAction), new GameActionFactory());
RegisterType(typeof(ItemMold), new ItemMoldFactory(drawableFactory));
RegisterType(typeof(BuffMold), new BuffMoldFactory(drawableFactory));
}
public T Get<T>(string resName) where T : class
{
var cache = objectCaches[typeof(T)];
var obj = cache.Get(resName) as T;
if (obj == null)
{
var res = Load(resName);
var factory = objectFactories[typeof(T)];
obj = (T)factory.Create(resName, res);
cache.Add(resName, obj);
}
return obj;
}
public ISprite GetSprite(string resName, byte[] state = null)
{
var maker = Get<SpriteMaker>(resName);
return maker.MakeInstance(state);
}
public Resource Load(string resName)
{
return defaultSource.Get(resName);
}
private void RegisterType(Type type, IObjectFactory<object> factory)
{
objectFactories[type] = factory;
objectCaches[type] = new ResourceObjectCache();
}
}
}
|
mit
|
C#
|
b5ac5c46ec4e330cac2e8c9dbbc8594ed0571dd3
|
Switch simple array diff to default until Efficient array diffing is implemented
|
wbish/jsondiffpatch.net,arbitertl/jsondiffpatch.net
|
Src/Options.cs
|
Src/Options.cs
|
namespace JsonDiffPatchDotNet
{
public sealed class Options
{
public Options()
{
ArrayDiff = ArrayDiffMode.Simple;
TextDiff = TextDiffMode.Efficient;
MinEfficientTextDiffLength = 50;
}
public ArrayDiffMode ArrayDiff { get; set; }
public TextDiffMode TextDiff { get; set; }
public long MinEfficientTextDiffLength { get; set; }
}
}
|
namespace JsonDiffPatchDotNet
{
public sealed class Options
{
public Options()
{
ArrayDiff = ArrayDiffMode.Efficient;
TextDiff = TextDiffMode.Efficient;
MinEfficientTextDiffLength = 50;
}
public ArrayDiffMode ArrayDiff
{ get; set; }
public TextDiffMode TextDiff
{ get; set; }
public long MinEfficientTextDiffLength
{ get; set; }
}
}
|
mit
|
C#
|
11e7ed4b302b730b99e9451b49b6e7a50de9b4c7
|
Fix FindChildByRole for ShaderLab
|
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
|
resharper/src/resharper-unity/Psi/ShaderLab/Parsing/ShaderLabTokenType.ShaderLabTokenNodeType.cs
|
resharper/src/resharper-unity/Psi/ShaderLab/Parsing/ShaderLabTokenType.ShaderLabTokenNodeType.cs
|
using System;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree;
using JetBrains.ReSharper.Psi.Parsing;
using JetBrains.Text;
namespace JetBrains.ReSharper.Plugins.Unity.Psi.ShaderLab.Parsing
{
public interface IShaderLabTokenNodeType : ITokenNodeType
{
}
public static partial class ShaderLabTokenType
{
public abstract class ShaderLabTokenNodeType : TokenNodeType, IShaderLabTokenNodeType
{
protected ShaderLabTokenNodeType(string s, int index)
: base(s, index)
{
}
public override LeafElementBase Create(IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset)
{
throw new InvalidOperationException($"TokenNodeType.Create needs to be overridden in {GetType()}");
}
public override bool IsWhitespace => false; // this == WHITESPACE || this == NEW_LINE;
public override bool IsComment => false;
public override bool IsStringLiteral => false; // this == STRING_LITERAL
public override bool IsConstantLiteral => false; // LITERALS[this]
public override bool IsIdentifier => false; // this == IDENTIFIER
public override bool IsKeyword => false; // KEYWORDS[this]
}
}
}
|
using System;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree;
using JetBrains.ReSharper.Psi.Parsing;
using JetBrains.Text;
namespace JetBrains.ReSharper.Plugins.Unity.Psi.ShaderLab.Parsing
{
public interface IShaderLabTokenNodeType : ITokenNodeType
{
}
public static partial class ShaderLabTokenType
{
public abstract class ShaderLabTokenNodeType : TokenNodeType, IShaderLabTokenNodeType
{
private const int BASE_INDEX = 10000;
protected ShaderLabTokenNodeType(string s, int index)
: base(s, BASE_INDEX + index)
{
}
public override LeafElementBase Create(IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset)
{
throw new InvalidOperationException($"TokenNodeType.Create needs to be overridden in {GetType()}");
}
public override bool IsWhitespace => false; // this == WHITESPACE || this == NEW_LINE;
public override bool IsComment => false;
public override bool IsStringLiteral => false; // this == STRING_LITERAL
public override bool IsConstantLiteral => false; // LITERALS[this]
public override bool IsIdentifier => false; // this == IDENTIFIER
public override bool IsKeyword => false; // KEYWORDS[this]
}
}
}
|
apache-2.0
|
C#
|
52da9467b58dc90d1b27cd3ac16ae8d1079c27b3
|
save as file
|
RyotaMurohoshi/unity_snippets
|
unity/Assets/Scripts/Common/ShowMethod.cs
|
unity/Assets/Scripts/Common/ShowMethod.cs
|
using UnityEngine;
using System.Reflection;
using System.Linq;
using System;
using System.Collections.Generic;
using System.IO;
public class ShowMethod : MonoBehaviour
{
void Start()
{
var info = new AssemblyDebugInfo("UnityEngine.dll");
File.WriteAllText("result.json", JsonUtility.ToJson(info, true));
}
}
[Serializable]
class AssemblyDebugInfo
{
public string AssemblyName;
public List<TypeDebugInfo> Types;
public AssemblyDebugInfo(string assemblyName)
{
var assembly = Assembly.Load(assemblyName);
AssemblyName = assembly.FullName;
Types = assembly
.GetTypes()
.Where(it => it.IsPublic)
.Select(it => new TypeDebugInfo(it))
.ToList();
}
}
[Serializable]
class TypeDebugInfo
{
public string Name;
public List<ConstructorDebugInfo> Constructors;
public List<MethodDebugInfo> Methods;
private static readonly BindingFlags Flags = BindingFlags.Instance
| BindingFlags.Static
| BindingFlags.DeclaredOnly
| BindingFlags.Public;
public TypeDebugInfo(Type type)
{
Name = type.FullName;
Constructors = type.GetConstructors().Select(it => new ConstructorDebugInfo(it)).ToList();
Methods = type.GetMethods(Flags).Select(it => new MethodDebugInfo(it)).ToList();
}
}
[Serializable]
class ConstructorDebugInfo
{
public List<string> ParameterTypeNames;
public ConstructorDebugInfo(ConstructorInfo constructorInfo)
{
ParameterTypeNames = constructorInfo
.GetParameters()
.Select(it => it.ParameterType.Name)
.ToList();
}
}
[Serializable]
class MethodDebugInfo
{
public string MethodName;
public string ReturnTypeName;
public List<string> ParameterTypeNames;
public bool IsStatic;
public MethodDebugInfo(MethodInfo methodInfo)
{
MethodName = methodInfo.Name;
ReturnTypeName = methodInfo.ReturnType.Name;
ParameterTypeNames = methodInfo.GetParameters().Select(it => it.ParameterType.Name).ToList();
IsStatic = methodInfo.IsStatic;
}
}
|
using UnityEngine;
using System.Reflection;
using System.Linq;
using System;
using System.Collections.Generic;
public class ShowMethod : MonoBehaviour
{
void Start()
{
var info = new AssemblyDebugInfo("UnityEngine.dll");
Debug.Log(JsonUtility.ToJson(info, true));
}
}
[Serializable]
class AssemblyDebugInfo
{
public string AssemblyName;
public List<TypeDebugInfo> Types;
public AssemblyDebugInfo(string assemblyName)
{
var assembly = Assembly.Load(assemblyName);
AssemblyName = assembly.FullName;
Types = assembly
.GetTypes()
.Where(it => it.IsPublic)
.Select(it => new TypeDebugInfo(it))
.ToList();
}
}
[Serializable]
class TypeDebugInfo
{
public string Name;
public List<ConstructorDebugInfo> Constructors;
public List<MethodDebugInfo> Methods;
private static readonly BindingFlags Flags = BindingFlags.Instance
| BindingFlags.Static
| BindingFlags.DeclaredOnly
| BindingFlags.Public;
public TypeDebugInfo(Type type)
{
Name = type.FullName;
Constructors = type.GetConstructors().Select(it => new ConstructorDebugInfo(it)).ToList();
Methods = type.GetMethods(Flags).Select(it => new MethodDebugInfo(it)).ToList();
}
}
[Serializable]
class ConstructorDebugInfo
{
public List<string> ParameterTypeNames;
public ConstructorDebugInfo(ConstructorInfo constructorInfo)
{
ParameterTypeNames = constructorInfo
.GetParameters()
.Select(it => it.ParameterType.Name)
.ToList();
}
}
[Serializable]
class MethodDebugInfo
{
public string MethodName;
public string ReturnTypeName;
public List<string> ParameterTypeNames;
public bool IsStatic;
public MethodDebugInfo(MethodInfo methodInfo)
{
MethodName = methodInfo.Name;
ReturnTypeName = methodInfo.ReturnType.Name;
ParameterTypeNames = methodInfo.GetParameters().Select(it => it.ParameterType.Name).ToList();
IsStatic = methodInfo.IsStatic;
}
}
|
mit
|
C#
|
9074cdf3401b3fb891d09b2079ab07976e84435e
|
Add a hover effect to video player seek bar
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
video/TweetDuck.Video/Controls/SeekBar.cs
|
video/TweetDuck.Video/Controls/SeekBar.cs
|
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace TweetDuck.Video.Controls{
sealed class SeekBar : ProgressBar{
private readonly SolidBrush brushFore;
private readonly SolidBrush brushHover;
private readonly SolidBrush brushOverlap;
public SeekBar(){
brushFore = new SolidBrush(Color.White);
brushHover = new SolidBrush(Color.White);
brushOverlap = new SolidBrush(Color.White);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e){
if (brushFore.Color != ForeColor){
brushFore.Color = ForeColor;
brushHover.Color = Color.FromArgb(128, ForeColor);
brushOverlap.Color = Color.FromArgb(80+ForeColor.R*11/16, 80+ForeColor.G*11/16, 80+ForeColor.B*11/16);
}
Rectangle rect = e.ClipRectangle;
Point cursor = PointToClient(Cursor.Position);
int width = rect.Width;
int progress = (int)(width*((double)Value/Maximum));
rect.Width = progress;
e.Graphics.FillRectangle(brushFore, rect);
if (cursor.X >= 0 && cursor.Y >= 0 && cursor.X <= width && cursor.Y <= rect.Height){
if (progress >= cursor.X){
rect.Width = cursor.X;
e.Graphics.FillRectangle(brushOverlap, rect);
}
else{
rect.X = progress;
rect.Width = cursor.X-rect.X;
e.Graphics.FillRectangle(brushHover, rect);
}
}
}
protected override void Dispose(bool disposing){
base.Dispose(disposing);
if (disposing){
brushFore.Dispose();
brushHover.Dispose();
brushOverlap.Dispose();
}
}
}
}
|
using System.Drawing;
using System.Windows.Forms;
namespace TweetDuck.Video.Controls{
sealed class SeekBar : ProgressBar{
private readonly SolidBrush brush;
public SeekBar(){
brush = new SolidBrush(Color.White);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e){
if (brush.Color != ForeColor){
brush.Color = ForeColor;
}
Rectangle rect = e.ClipRectangle;
rect.Width = (int)(rect.Width*((double)Value/Maximum));
e.Graphics.FillRectangle(brush, rect);
}
protected override void Dispose(bool disposing){
base.Dispose(disposing);
if (disposing){
brush.Dispose();
}
}
}
}
|
mit
|
C#
|
76a4cee31a651f0a4be824b9db3102efa2e6707f
|
Reset the mocks before disposing
|
NServiceKit/NServiceKit.Logging,NServiceKit/NServiceKit.Logging
|
tests/NServiceKit.Logging.Tests/Support/TestBase.cs
|
tests/NServiceKit.Logging.Tests/Support/TestBase.cs
|
using System;
using System.Diagnostics;
using NUnit.Framework;
using Rhino.Mocks;
namespace NServiceKit.Logging.Tests.Support
{
public class TestBase
{
private MockRepository mocks;
protected virtual MockRepository Mocks
{
get { return mocks; }
}
[SetUp]
protected virtual void SetUp()
{
mocks = new MockRepository();
}
[TearDown]
protected virtual void TearDown()
{
mocks.BackToRecordAll();
mocks = null;
}
protected virtual void ReplayAll()
{
Mocks.ReplayAll();
}
protected virtual void VerifyAll()
{
try
{
Mocks.VerifyAll();
}
catch (InvalidOperationException ex)
{
Debug.Print("InvalidOperationException thrown: {0}", ex.Message);
}
}
}
}
|
using System;
using System.Diagnostics;
using NUnit.Framework;
using Rhino.Mocks;
namespace NServiceKit.Logging.Tests.Support
{
public class TestBase
{
private MockRepository mocks;
protected virtual MockRepository Mocks
{
get { return mocks; }
}
[SetUp]
protected virtual void SetUp()
{
mocks = new MockRepository();
}
[TearDown]
protected virtual void TearDown()
{
mocks = null;
}
protected virtual void ReplayAll()
{
Mocks.ReplayAll();
}
protected virtual void VerifyAll()
{
try
{
Mocks.VerifyAll();
}
catch (InvalidOperationException ex)
{
Debug.Print("InvalidOperationException thrown: {0}", ex.Message);
}
}
}
}
|
bsd-3-clause
|
C#
|
cca58f3ec06b40bb8273ab3f7c84768850d2e10d
|
Replace SQLite path for MBTiles files with full path, so that doesn't throw an exception on UWP
|
charlenni/Mapsui,charlenni/Mapsui,pauldendulk/Mapsui
|
Samples/Mapsui.Samples.Common/Maps/MbTilesSample.cs
|
Samples/Mapsui.Samples.Common/Maps/MbTilesSample.cs
|
using System.IO;
using BruTile.MbTiles;
using Mapsui.Layers;
using Mapsui.UI;
using SQLite;
namespace Mapsui.Samples.Common.Maps
{
public class MbTilesSample : ISample
{
// This is a hack used for iOS/Android deployment
public static string MbTilesLocation { get; set; } = @"." + Path.DirectorySeparatorChar + "MbTiles";
public string Name => "1 MbTiles";
public string Category => "Data";
public void Setup(IMapControl mapControl)
{
mapControl.Map = CreateMap();
}
public static Map CreateMap()
{
var map = new Map();
map.Layers.Add(CreateMbTilesLayer(Path.GetFullPath(Path.Combine(MbTilesLocation, "world.mbtiles")), "regular"));
return map;
}
public static TileLayer CreateMbTilesLayer(string path, string name)
{
var mbTilesTileSource = new MbTilesTileSource(new SQLiteConnectionString(path, true));
var mbTilesLayer = new TileLayer(mbTilesTileSource) { Name = name};
return mbTilesLayer;
}
}
}
|
using System.IO;
using BruTile.MbTiles;
using Mapsui.Layers;
using Mapsui.UI;
using SQLite;
namespace Mapsui.Samples.Common.Maps
{
public class MbTilesSample : ISample
{
// This is a hack used for iOS/Android deployment
public static string MbTilesLocation { get; set; } = @"." + Path.DirectorySeparatorChar + "MbTiles";
public string Name => "1 MbTiles";
public string Category => "Data";
public void Setup(IMapControl mapControl)
{
mapControl.Map = CreateMap();
}
public static Map CreateMap()
{
var map = new Map();
map.Layers.Add(CreateMbTilesLayer(Path.Combine(MbTilesLocation, "world.mbtiles"), "regular"));
return map;
}
public static TileLayer CreateMbTilesLayer(string path, string name)
{
var mbTilesTileSource = new MbTilesTileSource(new SQLiteConnectionString(path, true));
var mbTilesLayer = new TileLayer(mbTilesTileSource) { Name = name};
return mbTilesLayer;
}
}
}
|
mit
|
C#
|
6c2b447530b12a041417acebef7baa5cf14275e8
|
Fix filename
|
ycaihua/sharpcompress,catester/sharpcompress,Wagnerp/sharpcompress,majorsilence/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress,tablesmit/sharpcompress,Icenium/sharpcompress,adamhathcock/sharpcompress,KOLANICH/sharpcompress,weltkante/sharpcompress,sepehr1014/sharpcompress,RainsSoft/sharpcompress,Gert-Jan/sharpcompress
|
SharpCompress.Test/Rar/Unit/RarHeaderFactoryTest.cs
|
SharpCompress.Test/Rar/Unit/RarHeaderFactoryTest.cs
|
using System;
using System.IO;
using System.Net.Security;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SharpCompress.Common;
using SharpCompress.Common.Rar.Headers;
using SharpCompress.IO;
namespace SharpCompress.Test.Rar.Unit
{
/// <summary>
/// Summary description for RarFactoryReaderTest
/// </summary>
[TestClass]
public class RarHeaderFactoryTest : TestBase
{
private RarHeaderFactory rarHeaderFactory;
[TestInitialize]
public void Initialize()
{
ResetScratch();
rarHeaderFactory = new RarHeaderFactory(StreamingMode.Seekable, Options.KeepStreamsOpen);
}
[TestMethod]
public void ReadHeaders_RecognizeEncryptedFlag()
{
ReadEncryptedFlag("Rar.Encrypted_filesAndHeader.rar", true);
}
private void ReadEncryptedFlag(string testArchive, bool isEncrypted)
{
using (var stream = GetReaderStream(testArchive))
foreach (var header in rarHeaderFactory.ReadHeaders(stream))
{
if (header.HeaderType == HeaderType.ArchiveHeader)
{
Assert.AreEqual(isEncrypted, rarHeaderFactory.IsEncrypted);
break;
}
}
}
[TestMethod]
public void ReadHeaders_RecognizeNoEncryptedFlag()
{
ReadEncryptedFlag("Rar.rar", false);
}
private FileStream GetReaderStream(string testArchive)
{
return new FileStream(Path.Combine(TEST_ARCHIVES_PATH, testArchive),
FileMode.Open);
}
}
}
|
using System;
using System.IO;
using System.Net.Security;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SharpCompress.Common;
using SharpCompress.Common.Rar.Headers;
using SharpCompress.IO;
namespace SharpCompress.Test.Rar.Unit
{
/// <summary>
/// Summary description for RarFactoryReaderTest
/// </summary>
[TestClass]
public class RarHeaderFactoryTest : TestBase
{
private RarHeaderFactory rarHeaderFactory;
[TestInitialize]
public void Initialize()
{
ResetScratch();
rarHeaderFactory = new RarHeaderFactory(StreamingMode.Seekable, Options.KeepStreamsOpen);
}
[TestMethod]
public void ReadHeaders_RecognizeEncryptedFlag()
{
ReadEncryptedFlag("Rar.Encrypted.rar", true);
}
private void ReadEncryptedFlag(string testArchive, bool isEncrypted)
{
using (var stream = GetReaderStream(testArchive))
foreach (var header in rarHeaderFactory.ReadHeaders(stream))
{
if (header.HeaderType == HeaderType.ArchiveHeader)
{
Assert.AreEqual(isEncrypted, rarHeaderFactory.IsEncrypted);
break;
}
}
}
[TestMethod]
public void ReadHeaders_RecognizeNoEncryptedFlag()
{
ReadEncryptedFlag("Rar.rar", false);
}
private FileStream GetReaderStream(string testArchive)
{
return new FileStream(Path.Combine(TEST_ARCHIVES_PATH, testArchive),
FileMode.Open);
}
}
}
|
mit
|
C#
|
0cd3027c289aa42d90c59b3121497849b978d07a
|
Disable naming warning
|
JohnnyCrazy/SpotifyAPI-NET,JohnnyCrazy/SpotifyAPI-NET,JohnnyCrazy/SpotifyAPI-NET,JohnnyCrazy/SpotifyAPI-NET
|
SpotifyAPI.Web/Clients/Interfaces/IArtistsClient.cs
|
SpotifyAPI.Web/Clients/Interfaces/IArtistsClient.cs
|
using System.Threading.Tasks;
namespace SpotifyAPI.Web
{
public interface IArtistsClient
{
Task<ArtistsResponse> GetSeveral(ArtistsRequest request);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716")]
Task<FullArtist> Get(string artistId);
Task<Paging<SimpleAlbum>> GetAlbums(string artistId);
Task<Paging<SimpleAlbum>> GetAlbums(string artistId, ArtistsAlbumsRequest request);
Task<ArtistsTopTracksResponse> GetTopTracks(string artistId, ArtistsTopTracksRequest request);
Task<ArtistsRelatedArtistsResponse> GetRelatedArtists(string artistId);
}
}
|
using System.Threading.Tasks;
namespace SpotifyAPI.Web
{
public interface IArtistsClient
{
Task<ArtistsResponse> GetSeveral(ArtistsRequest request);
Task<FullArtist> Get(string artistId);
Task<Paging<SimpleAlbum>> GetAlbums(string artistId);
Task<Paging<SimpleAlbum>> GetAlbums(string artistId, ArtistsAlbumsRequest request);
Task<ArtistsTopTracksResponse> GetTopTracks(string artistId, ArtistsTopTracksRequest request);
Task<ArtistsRelatedArtistsResponse> GetRelatedArtists(string artistId);
}
}
|
mit
|
C#
|
bf83e7cf03795f325293000954c5f3a5004349a5
|
Update RangeValidatorTests.cs
|
pushrbx/squidex,pushrbx/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,pushrbx/squidex,Squidex/squidex,pushrbx/squidex,Squidex/squidex,pushrbx/squidex
|
tests/Squidex.Domain.Apps.Core.Tests/Operations/ValidateContent/Validators/RangeValidatorTests.cs
|
tests/Squidex.Domain.Apps.Core.Tests/Operations/ValidateContent/Validators/RangeValidatorTests.cs
|
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Squidex.Domain.Apps.Core.ValidateContent.Validators;
using Xunit;
namespace Squidex.Domain.Apps.Core.Operations.ValidateContent.Validators
{
public class RangeValidatorTests
{
private readonly List<string> errors = new List<string>();
[Fact]
public async Task Should_not_add_error_if_value_is_null()
{
var sut = new RangeValidator<int>(100, 200);
await sut.ValidateAsync(null, errors);
Assert.Empty(errors);
}
[Theory]
[InlineData(null, null)]
[InlineData(1000, null)]
[InlineData(1000, 2000)]
[InlineData(null, 2000)]
public async Task Should_not_add_error_if_value_is_within_range(int? min, int? max)
{
var sut = new RangeValidator<int>(min, max);
await sut.ValidateAsync(1500, errors);
Assert.Empty(errors);
}
[Theory]
[InlineData(20, 10)]
[InlineData(10, 10)]
public void Should_throw_error_if_min_greater_than_max(int? min, int? max)
{
Assert.Throws<ArgumentException>(() => new RangeValidator<int>(min, max));
}
[Fact]
public async Task Should_add_error_if_value_is_smaller_than_min()
{
var sut = new RangeValidator<int>(2000, null);
await sut.ValidateAsync(1500, errors);
errors.Should().BeEquivalentTo(
new[] { "Must be greater than or equal to '2000'." });
}
[Fact]
public async Task Should_add_error_if_value_is_greater_than_max()
{
var sut = new RangeValidator<int>(null, 1000);
await sut.ValidateAsync(1500, errors);
errors.Should().BeEquivalentTo(
new[] { "Must be less than or equal to '1000'." });
}
}
}
|
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Squidex.Domain.Apps.Core.ValidateContent.Validators;
using Xunit;
namespace Squidex.Domain.Apps.Core.Operations.ValidateContent.Validators
{
public class RangeValidatorTests
{
private readonly List<string> errors = new List<string>();
[Fact]
public async Task Should_not_add_error_if_value_is_null()
{
var sut = new RangeValidator<int>(100, 200);
await sut.ValidateAsync(null, errors);
Assert.Empty(errors);
}
[Theory]
[InlineData(null, null)]
[InlineData(1000, null)]
[InlineData(1000, 2000)]
[InlineData(null, 2000)]
public async Task Should_not_add_error_if_value_is_within_range(int? min, int? max)
{
var sut = new RangeValidator<int>(min, max);
await sut.ValidateAsync(1500, errors);
Assert.Empty(errors);
}
[Theory]
[InlineData(20, 10)]
[InlineData(10, 10)]
public void Should_throw_error_if_min_greater_than_max(int? min, int? max)
{
Assert.Throws<ArgumentException>(() => new RangeValidator<int>(min, max));
}
[Fact]
public async Task Should_add_error_if_value_is_smaller_than_min()
{
var sut = new RangeValidator<int>(2000, null);
await sut.ValidateAsync(1500, errors);
errors.Should().BeEquivalentTo(
new[] { "Must be greater or equals than '2000'." });
}
[Fact]
public async Task Should_add_error_if_value_is_greater_than_max()
{
var sut = new RangeValidator<int>(null, 1000);
await sut.ValidateAsync(1500, errors);
errors.Should().BeEquivalentTo(
new[] { "Must be less or equals than '1000'." });
}
}
}
|
mit
|
C#
|
d98640a0249aab8edbbe8cfec49594a6358d9da5
|
Fix smoke test to use common LocationName
|
googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/gcloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet
|
apis/Google.Cloud.Redis.V1Beta1/Google.Cloud.Redis.V1Beta1.SmokeTests/CloudRedisClientSmokeTest.cs
|
apis/Google.Cloud.Redis.V1Beta1/Google.Cloud.Redis.V1Beta1.SmokeTests/CloudRedisClientSmokeTest.cs
|
// Copyright 2019 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
//
// https://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 Google.Api.Gax.ResourceNames;
namespace Google.Cloud.Redis.V1Beta1.SmokeTests
{
public class CloudRedisClientSmokeTest
{
public static int Main(string[] args)
{
var client = CloudRedisClient.Create();
var locationName = new LocationName(args[0], "-");
var instances = client.ListInstances(locationName);
foreach (var instance in instances)
{
Console.WriteLine(instance.Name);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
|
// Copyright 2019 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
//
// https://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;
namespace Google.Cloud.Redis.V1Beta1.SmokeTests
{
public class CloudRedisClientSmokeTest
{
public static int Main(string[] args)
{
var client = CloudRedisClient.Create();
var locationName = new LocationName(args[0], "-");
var instances = client.ListInstances(locationName);
foreach (var instance in instances)
{
Console.WriteLine(instance.Name);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
|
apache-2.0
|
C#
|
2c29a7c24800d9024973e368ad081049036b8e03
|
Update FieldUtilities.cs
|
OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core
|
Core/OfficeDevPnP.Core/Framework/Provisioning/ObjectHandlers/Utilities/FieldUtilities.cs
|
Core/OfficeDevPnP.Core/Framework/Provisioning/ObjectHandlers/Utilities/FieldUtilities.cs
|
using Microsoft.SharePoint.Client;
using System;
using System.Xml.Linq;
namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Utilities
{
public static class FieldUtilities
{
public static string FixLookupField(string fieldXml, Web web)
{
var fieldElement = XElement.Parse(fieldXml);
var fieldType = (string)fieldElement.Attribute("Type");
if (fieldType == "Lookup" || fieldType == "LookupMulti")
{
var listAttr = (string)fieldElement.Attribute("List");
Guid g;
if (!Guid.TryParse(listAttr, out g))
{
var targetList = web.GetList($"{web.ServerRelativeUrl.TrimEnd('/')}/{listAttr}");
fieldElement.SetAttributeValue("List", targetList.EnsureProperty(l => l.Id).ToString("B"));
return fieldElement.ToString();
}
}
return fieldXml;
}
}
}
|
using Microsoft.SharePoint.Client;
using System;
using System.Xml.Linq;
namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Utilities
{
public static class FieldUtilities
{
public static string FixLookupField(string fieldXml, Web web)
{
var fieldElement = XElement.Parse(fieldXml);
if ((string)fieldElement.Attribute("Type") == "Lookup")
{
var listAttr = (string)fieldElement.Attribute("List");
Guid g;
if (!Guid.TryParse(listAttr, out g))
{
var targetList = web.GetList($"{web.ServerRelativeUrl.TrimEnd('/')}/{listAttr}");
fieldElement.SetAttributeValue("List", targetList.EnsureProperty(l => l.Id).ToString("B"));
return fieldElement.ToString();
}
}
return fieldXml;
}
}
}
|
mit
|
C#
|
ea6f7751779f2d3ce434dc907c23a646073a2c2b
|
Remove unnecessary using statements
|
smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework
|
osu.Framework.Templates/templates/template-flappy/FlappyDon.Game.Tests/Visual/TestSceneFlappyDonGame.cs
|
osu.Framework.Templates/templates/template-flappy/FlappyDon.Game.Tests/Visual/TestSceneFlappyDonGame.cs
|
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace FlappyDon.Game.Tests.Visual
{
/// <summary>
/// A test scene wrapping the entire game,
/// including audio.
/// </summary>
public class TestSceneFlappyDonGame : TestScene
{
private FlappyDonGame game;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
game = new FlappyDonGame();
game.SetHost(host);
Add(game);
}
}
}
|
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace FlappyDon.Game.Tests.Visual
{
/// <summary>
/// A test scene wrapping the entire game,
/// including audio.
/// </summary>
public class TestSceneFlappyDonGame : TestScene
{
private FlappyDonGame game;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
game = new FlappyDonGame();
game.SetHost(host);
Add(game);
}
}
}
|
mit
|
C#
|
1dd0b71505938752b2e2ba01574e6dbb4870bf7c
|
Enable auto-connection on pre-block bursting screen
|
HelloKitty/Booma.Proxy
|
src/Booma.Proxy.Client.Unity.Common/Engine/Initializables/NetworkClientConnectionOnInitInitializable.cs
|
src/Booma.Proxy.Client.Unity.Common/Engine/Initializables/NetworkClientConnectionOnInitInitializable.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using GladNet;
namespace Booma.Proxy
{
[SceneTypeCreate(GameSceneType.PreBlockBurstingScene)]
[SceneTypeCreate(GameSceneType.ServerSelectionScreen)]
[SceneTypeCreate(GameSceneType.PreShipSelectionScene)]
[SceneTypeCreate(GameSceneType.CharacterSelectionScreen)] //probably more than just the character screen.
public sealed class NetworkClientConnectionOnInitInitializable : IGameInitializable
{
private IConnectionService ConnectionService { get; }
private IGameConnectionEndpointDetails ConnectionDetails { get; }
private ILog Logger { get; }
/// <inheritdoc />
public NetworkClientConnectionOnInitInitializable([NotNull] IConnectionService connectionService, [NotNull] IGameConnectionEndpointDetails connectionDetails, [NotNull] ILog logger)
{
ConnectionService = connectionService ?? throw new ArgumentNullException(nameof(connectionService));
ConnectionDetails = connectionDetails ?? throw new ArgumentNullException(nameof(connectionDetails));
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <inheritdoc />
public Task OnGameInitialized()
{
if(Logger.IsInfoEnabled)
Logger.Info($"Connectiong to: {ConnectionDetails.IpAddress}:{ConnectionDetails.Port}");
//This initializable actually just
//connects a IConnectionService with the provided game details.
return ConnectionService.ConnectAsync(ConnectionDetails.IpAddress, ConnectionDetails.Port);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using GladNet;
namespace Booma.Proxy
{
[SceneTypeCreate(GameSceneType.ServerSelectionScreen)]
[SceneTypeCreate(GameSceneType.PreShipSelectionScene)]
[SceneTypeCreate(GameSceneType.CharacterSelectionScreen)] //probably more than just the character screen.
public sealed class NetworkClientConnectionOnInitInitializable : IGameInitializable
{
private IConnectionService ConnectionService { get; }
private IGameConnectionEndpointDetails ConnectionDetails { get; }
private ILog Logger { get; }
/// <inheritdoc />
public NetworkClientConnectionOnInitInitializable([NotNull] IConnectionService connectionService, [NotNull] IGameConnectionEndpointDetails connectionDetails, [NotNull] ILog logger)
{
ConnectionService = connectionService ?? throw new ArgumentNullException(nameof(connectionService));
ConnectionDetails = connectionDetails ?? throw new ArgumentNullException(nameof(connectionDetails));
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <inheritdoc />
public Task OnGameInitialized()
{
if(Logger.IsInfoEnabled)
Logger.Info($"Connectiong to: {ConnectionDetails.IpAddress}:{ConnectionDetails.Port}");
//This initializable actually just
//connects a IConnectionService with the provided game details.
return ConnectionService.ConnectAsync(ConnectionDetails.IpAddress, ConnectionDetails.Port);
}
}
}
|
agpl-3.0
|
C#
|
670d732b5ab531eafde00ad91c042f56866eef46
|
Address PR feedback
|
mmitche/coreclr,krk/coreclr,cshung/coreclr,krk/coreclr,poizan42/coreclr,cshung/coreclr,wtgodbe/coreclr,poizan42/coreclr,cshung/coreclr,krk/coreclr,krk/coreclr,wtgodbe/coreclr,mmitche/coreclr,krk/coreclr,wtgodbe/coreclr,poizan42/coreclr,mmitche/coreclr,mmitche/coreclr,mmitche/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,cshung/coreclr,poizan42/coreclr,cshung/coreclr,poizan42/coreclr,wtgodbe/coreclr,mmitche/coreclr,wtgodbe/coreclr,cshung/coreclr
|
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.cs
|
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.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
{
/// <summary>Indicates whether a method is an asynchronous iterator.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute
{
/// <summary>Initializes a new instance of the <see cref="AsyncIteratorStateMachineAttribute"/> class.</summary>
/// <param name="stateMachineType">The type object for the underlying state machine type that's used to implement a state machine method.</param>
public AsyncIteratorStateMachineAttribute(Type stateMachineType)
: base(stateMachineType)
{
}
}
}
|
// 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
{
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute
{
public AsyncIteratorStateMachineAttribute(Type stateMachineType)
: base(stateMachineType)
{
}
}
}
|
mit
|
C#
|
cff632d29efd954700947fceccab6c49ab6df42b
|
Remove commented permission
|
adjust/xamarin_sdk,adjust/xamarin_sdk
|
Android/Example/Properties/AssemblyInfo.cs
|
Android/Example/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Example")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) Pedro Silva")]
[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.0.0")]
// 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;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Example")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) Pedro Silva")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//[assembly: UsesPermission("com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE")]
// 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.0.0")]
// 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#
|
cf29a0502bcf95210319e5fea86d03fb97a6d04f
|
Set MicrogameCollection dirty in editor update
|
NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare
|
Assets/Editor/MicrogameCollectionEditor.cs
|
Assets/Editor/MicrogameCollectionEditor.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
public override void OnInspectorGUI()
{
MicrogameCollection collection = (MicrogameCollection)target;
if (GUILayout.Button("Update Microgames"))
{
collection.updateMicrogames();
EditorUtility.SetDirty(collection);
}
DrawDefaultInspector();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
public override void OnInspectorGUI()
{
MicrogameCollection collection = (MicrogameCollection)target;
if (GUILayout.Button("Update Microgames"))
{
collection.updateMicrogames();
}
DrawDefaultInspector();
}
}
|
mit
|
C#
|
0f9c1a4686d5b1101cb44effdd3ef636e49f47ca
|
Add a link on Credit card registrations that have not paid
|
ucdavis/CRP,ucdavis/CRP,ucdavis/CRP
|
CRP.Mvc/Views/Payments/Confirmation.cshtml
|
CRP.Mvc/Views/Payments/Confirmation.cshtml
|
@using Microsoft.Web.Mvc
@model CRP.Controllers.ViewModels.PaymentConfirmationViewModel
@{
ViewBag.Title = "Confirmation";
}
<div class="boundary">
<h2>Registration Confirmation</h2>
<p>You have successfully registered for the following event:</p>
<div>
<label>Item: </label>
@Model.Transaction.Item.Name
</div>
<div>
<label>Amount: </label>
@($"{Model.Transaction.Total:C}")
</div>
@if (Model.Transaction.Credit)
{
<div>
<p>Payment is still due:</p>
<form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px">
@foreach (var pair in Model.PaymentDictionary)
{
<input type="hidden" name="@pair.Key" value="@pair.Value"/>
}
<input type="hidden" name="signature" value="@Model.Signature"/>
<input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/>
</form>
</div>
}
else if (Model.Transaction.Total > 0)
{
<div>
@Html.Raw(Model.Transaction.Item.CheckPaymentInstructions)
</div>
}
</div>
|
@using Microsoft.Web.Mvc
@model CRP.Controllers.ViewModels.PaymentConfirmationViewModel
@{
ViewBag.Title = "Confirmation";
}
<div class="boundary">
<h2>Registration Confirmation</h2>
<p>You have successfully registered for the following event:</p>
<div>
<label>Item: </label>
@Model.Transaction.Item.Name
</div>
<div>
<label>Amount: </label>
@($"{Model.Transaction.Total:C}")
</div>
@if (Model.Transaction.Credit)
{
<div>
<p>Payment is still due:</p>
<form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px">
@foreach (var pair in Model.PaymentDictionary)
{
<input type="hidden" name="@pair.Key" value="@pair.Value"/>
}
<input type="hidden" name="signature" value="@Model.Signature"/>
@Html.SubmitButton("Submit", "Click here to be taken to our payment site")
</form>
</div>
}
else if (Model.Transaction.Total > 0)
{
<div>
@Html.Raw(Model.Transaction.Item.CheckPaymentInstructions)
</div>
}
</div>
|
mit
|
C#
|
5ed2cf72f682e74eebdf386b10a353bcc6902c78
|
Put GET back in.
|
kylebjones/CertiPay.Services.PDF
|
CertiPay.Services.PDF/Modules/PdfModule.cs
|
CertiPay.Services.PDF/Modules/PdfModule.cs
|
using CertiPay.Common;
using CertiPay.PDF;
using Nancy;
using Nancy.ModelBinding;
using Nancy.Responses;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
namespace CertiPay.Services.PDF.Modules
{
public class PdfModule : NancyModule
{
private static String AppName { get { return ConfigurationManager.AppSettings["ApplicationName"]; } }
public PdfModule(IPDFService pdfSvc)
{
Get["/"] = _ =>
{
return Response.AsJson(new
{
Application = AppName,
Version = CertiPay.Common.Utilities.Version<PdfModule>(),
Environment = EnvUtil.Current.DisplayName(),
Server = Environment.MachineName
});
};
Get["/Pdf/GenerateDocument"] = p =>
{
var url = this.Request.Query["url"];
var useLandscape = (bool?)this.Request.Query["landscape"] ?? null;
var settings = new PDFService.Settings()
{
UseLandscapeOrientation = useLandscape ?? false,
Uris = new List<string>()
{
url
}
};
var stream = new MemoryStream(pdfSvc.CreatePdf(settings));
//Future change. Add ability for FileName to be passed in from Caller.
var response = new StreamResponse(() => stream, MimeTypes.GetMimeType("Generated-Document.pdf"));
return response;
};
Post["/Pdf/GenerateDocument"] = p =>
{
var settings = this.Bind<PDFService.Settings>();
var stream = new MemoryStream(pdfSvc.CreatePdf(settings));
//Future change. Add ability for FileName to be passed in from Caller.
var response = new StreamResponse(() => stream, MimeTypes.GetMimeType("Generated-Document.pdf"));
return response;
};
}
}
}
|
using CertiPay.Common;
using CertiPay.PDF;
using Nancy;
using Nancy.ModelBinding;
using Nancy.Responses;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
namespace CertiPay.Services.PDF.Modules
{
public class PdfModule : NancyModule
{
private static String AppName { get { return ConfigurationManager.AppSettings["ApplicationName"]; } }
public PdfModule(IPDFService pdfSvc)
{
Get["/"] = _ =>
{
return Response.AsJson(new
{
Application = AppName,
Version = CertiPay.Common.Utilities.Version<PdfModule>(),
Environment = EnvUtil.Current.DisplayName(),
Server = Environment.MachineName
});
};
Post["/Pdf/GenerateDocument"] = p =>
{
var settings = this.Bind<PDFService.Settings>();
var stream = new MemoryStream(pdfSvc.CreatePdf(settings));
//Future change. Add ability for FileName to be passed in from Caller.
var response = new StreamResponse(() => stream, MimeTypes.GetMimeType("Generated-Document.pdf"));
return response;
};
}
}
}
|
mit
|
C#
|
ab5f2dafc0e39adb1d220e05a92d67c463f1731c
|
Fix parent issues.
|
tiagomartines11/ggj17
|
Assets/Scripts/Projectile.cs
|
Assets/Scripts/Projectile.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
float pRange;
float pAngle;
float pSpeed = 0.1f;
Vector3 dir;
// Use this for initialization
void Start () {
}
public void SetupProjectile(float range, float angle)
{
this.pAngle = angle;
this.pRange = range;
Quaternion rot = new Quaternion ();
rot.eulerAngles = new Vector3 (0, 0, pAngle);
this.transform.rotation = rot;
dir = new Vector3 (Mathf.Cos (angle / 180.0f * Mathf.PI), Mathf.Sin (angle / 180.0f * Mathf.PI), 0);
}
// Update is called once per frame
void Update () {
this.transform.localPosition = this.transform.localPosition + pSpeed * dir;
if (this.transform.localPosition.magnitude >= pRange) {
Debug.Log (this.transform.localPosition.magnitude);
GameObject.Destroy (gameObject);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Eletron") && collision.transform.parent.gameObject.layer != transform.parent.gameObject.layer)
{
GameObject.Destroy(gameObject);
collision.gameObject.GetComponent<PointBehaviour>().activate();
}
if (collision.gameObject.layer == LayerMask.NameToLayer("Shield"))
{
GameObject.Destroy(gameObject);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
float pRange;
float pAngle;
float pSpeed = 0.1f;
Vector3 dir;
// Use this for initialization
void Start () {
}
public void SetupProjectile(float range, float angle)
{
this.pAngle = angle;
this.pRange = range;
Quaternion rot = new Quaternion ();
rot.eulerAngles = new Vector3 (0, 0, pAngle);
this.transform.rotation = rot;
dir = new Vector3 (Mathf.Cos (angle / 180.0f * Mathf.PI), Mathf.Sin (angle / 180.0f * Mathf.PI), 0);
}
// Update is called once per frame
void Update () {
this.transform.localPosition = this.transform.localPosition + pSpeed * dir;
if (this.transform.localPosition.magnitude >= pRange) {
Debug.Log (this.transform.localPosition.magnitude);
GameObject.Destroy (gameObject);
}
}
void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject != this.transform.parent.gameObject) {
if (collision.gameObject.layer == LayerMask.NameToLayer("Eletron"))
{
GameObject.Destroy(gameObject);
collision.gameObject.GetComponent<PointBehaviour>().activate();
}
if (collision.gameObject.layer == LayerMask.NameToLayer("Shield"))
{
GameObject.Destroy(gameObject);
}
}
}
}
|
apache-2.0
|
C#
|
1c0d0ea9ef63a1dd9d3a7e42624263ad36535de3
|
Bump version to v0.2.
|
arookas/flaaffy
|
mareep/main.cs
|
mareep/main.cs
|
using System;
namespace arookas {
static partial class mareep {
static Version sVersion = new Version(0, 2);
static void Main(string[] arguments) {
Console.Title = String.Format("mareep v{0} arookas", sVersion);
mareep.WriteMessage("mareep v{0} arookas\n", sVersion);
mareep.WriteSeparator('=');
mareep.WriteMessage("Reading action...\n");
var action = mareep.ReadAction(arguments);
mareep.WriteMessage("Initializing performer...\n");
var performer = mareep.InitPerformer(action);
mareep.WriteMessage("Reading command-line parameters...\n");
performer.LoadParams(arguments);
mareep.WriteSeparator('-');
mareep.WriteMessage("Calling action...\n");
performer.Perform();
mareep.WriteLine();
mareep.WriteSeparator('-');
if (sWarningCount > 0) {
mareep.WriteMessage("Completed with {0} warning(s).\n", sWarningCount);
Console.ReadKey();
} else {
mareep.WriteMessage("Completed successfully!\n");
}
}
}
}
|
using System;
namespace arookas {
static partial class mareep {
static Version sVersion = new Version(0, 1);
static void Main(string[] arguments) {
Console.Title = String.Format("mareep v{0} arookas", sVersion);
mareep.WriteMessage("mareep v{0} arookas\n", sVersion);
mareep.WriteSeparator('=');
mareep.WriteMessage("Reading action...\n");
var action = mareep.ReadAction(arguments);
mareep.WriteMessage("Initializing performer...\n");
var performer = mareep.InitPerformer(action);
mareep.WriteMessage("Reading command-line parameters...\n");
performer.LoadParams(arguments);
mareep.WriteSeparator('-');
mareep.WriteMessage("Calling action...\n");
performer.Perform();
mareep.WriteLine();
mareep.WriteSeparator('-');
if (sWarningCount > 0) {
mareep.WriteMessage("Completed with {0} warning(s).\n", sWarningCount);
Console.ReadKey();
} else {
mareep.WriteMessage("Completed successfully!\n");
}
}
}
}
|
mit
|
C#
|
76325ff54e72b5ff28595f5d4d836e24ca8b7f2d
|
Update D2RS to handle new networking infrastructure.
|
wynandpieterse/SharpBattleNet
|
Source/Reaper.SharpBattleNet.Framework.DiabloIIRealmServer/Details/DiabloIIRealmServer.cs
|
Source/Reaper.SharpBattleNet.Framework.DiabloIIRealmServer/Details/DiabloIIRealmServer.cs
|
namespace Reaper.SharpBattleNet.Framework.DiabloIIRealmServer.Details
{
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Nini;
using Nini.Config;
using Nini.Ini;
using Nini.Util;
using NLog;
using Reaper;
using Reaper.SharpBattleNet;
using Reaper.SharpBattleNet.Framework;
using Reaper.SharpBattleNet.Framework.Networking;
using Reaper.SharpBattleNet.Framework.DiabloIIRealmServer;
internal sealed class DiabloIIRealmServer : IDiabloIIRealmServer
{
private readonly IConfigSource _configuration = null;
private readonly INetworkManager _networkManager = null;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public DiabloIIRealmServer(IConfigSource configuration, INetworkManager networkManager)
{
_configuration = configuration;
_networkManager = networkManager;
return;
}
public async Task Start(string[] commandArguments)
{
await _networkManager.StartNetworking();
return;
}
public async Task Stop()
{
await _networkManager.StopNetworking();
return;
}
}
}
|
namespace Reaper.SharpBattleNet.Framework.DiabloIIRealmServer.Details
{
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Nini;
using Nini.Config;
using Nini.Ini;
using Nini.Util;
using NLog;
using Reaper;
using Reaper.SharpBattleNet;
using Reaper.SharpBattleNet.Framework;
using Reaper.SharpBattleNet.Framework.DiabloIIRealmServer;
internal sealed class DiabloIIRealmServer : IDiabloIIRealmServer
{
private readonly IConfigSource _configuration = null;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public DiabloIIRealmServer(IConfigSource configuration)
{
_configuration = configuration;
return;
}
public async Task Start(string[] commandArguments)
{
return;
}
public async Task Stop()
{
return;
}
}
}
|
mit
|
C#
|
ee0da53636fb8ba291f1690eb9f0157d67ba2374
|
rename Use methods to have ApplicationInsights prefix
|
hackathonvixion/ApplicationInsights-aspnet5,hackathonvixion/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnetcore,gzepeda/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,gzepeda/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnetcore,hackathonvixion/ApplicationInsights-aspnet5,gzepeda/ApplicationInsights-aspnetcore
|
TemplateIntegrationExample/src/Microsoft.ApplicationInsights.AspNet/ApplicationInsightMiddlewareExtensions.cs
|
TemplateIntegrationExample/src/Microsoft.ApplicationInsights.AspNet/ApplicationInsightMiddlewareExtensions.cs
|
namespace Microsoft.ApplicationInsights.AspNet
{
using Microsoft.AspNet.Builder;
using System;
public static class ApplicationInsightMiddlewareExtensions
{
public static IApplicationBuilder UseApplicationInsightsRequestTelemetry(this IApplicationBuilder app)
{
app.UseMiddleware<ApplicationInsightsMiddleware>();
return app;
}
public static IApplicationBuilder UseApplicationInsightsTelemetry(this IApplicationBuilder app)
{
app.UseMiddleware<ApplicationInsightsMiddleware>();
return app;
}
public static IApplicationBuilder SetApplicationInsightsTelemetryDeveloperMode(this IApplicationBuilder app)
{
//do something
return app;
}
}
}
|
namespace Microsoft.ApplicationInsights.AspNet
{
using Microsoft.AspNet.Builder;
using System;
public static class ApplicationInsightMiddlewareExtensions
{
public static IApplicationBuilder UseRequestTelemetry(this IApplicationBuilder app)
{
app.UseMiddleware<ApplicationInsightsMiddleware>();
return app;
}
public static IApplicationBuilder UseExceptionsTelemetry(this IApplicationBuilder app)
{
app.UseMiddleware<ApplicationInsightsMiddleware>();
return app;
}
public static IApplicationBuilder SetTelemetryDeveloperMode(this IApplicationBuilder app)
{
//do something
return app;
}
}
}
|
mit
|
C#
|
775c6c83748df35e1ac23869124f461589b31ea6
|
Fix potential crash in editor from transform time going below zero
|
ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
|
osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyFollowCircle.cs
|
osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyFollowCircle.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
public class LegacyFollowCircle : FollowCircle
{
public LegacyFollowCircle(Drawable animationContent)
{
// follow circles are 2x the hitcircle resolution in legacy skins (since they are scaled down from >1x
animationContent.Scale *= 0.5f;
animationContent.Anchor = Anchor.Centre;
animationContent.Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = animationContent;
}
protected override void OnTrackingChanged(ValueChangedEvent<bool> tracking)
{
Debug.Assert(ParentObject != null);
if (ParentObject.Judged)
return;
double remainingTime = Math.Max(0, ParentObject.HitStateUpdateTime - Time.Current);
// Note that the scale adjust here is 2 instead of DrawableSliderBall.FOLLOW_AREA to match legacy behaviour.
// This means the actual tracking area for gameplay purposes is larger than the sprite (but skins may be accounting for this).
if (tracking.NewValue)
{
// TODO: Follow circle should bounce on each slider tick.
this.ScaleTo(0.5f).ScaleTo(2f, Math.Min(180f, remainingTime), Easing.Out)
.FadeTo(0).FadeTo(1f, Math.Min(60f, remainingTime));
}
else
{
// TODO: Should animate only at the next slider tick if we want to match stable perfectly.
this.ScaleTo(4f, 100)
.FadeTo(0f, 100);
}
}
protected override void OnSliderEnd()
{
this.ScaleTo(1.6f, 200, Easing.Out)
.FadeOut(200, Easing.In);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
public class LegacyFollowCircle : FollowCircle
{
public LegacyFollowCircle(Drawable animationContent)
{
// follow circles are 2x the hitcircle resolution in legacy skins (since they are scaled down from >1x
animationContent.Scale *= 0.5f;
animationContent.Anchor = Anchor.Centre;
animationContent.Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = animationContent;
}
protected override void OnTrackingChanged(ValueChangedEvent<bool> tracking)
{
Debug.Assert(ParentObject != null);
if (ParentObject.Judged)
return;
double remainingTime = ParentObject.HitStateUpdateTime - Time.Current;
// Note that the scale adjust here is 2 instead of DrawableSliderBall.FOLLOW_AREA to match legacy behaviour.
// This means the actual tracking area for gameplay purposes is larger than the sprite (but skins may be accounting for this).
if (tracking.NewValue)
{
// TODO: Follow circle should bounce on each slider tick.
this.ScaleTo(0.5f).ScaleTo(2f, Math.Min(180f, remainingTime), Easing.Out)
.FadeTo(0).FadeTo(1f, Math.Min(60f, remainingTime));
}
else
{
// TODO: Should animate only at the next slider tick if we want to match stable perfectly.
this.ScaleTo(4f, 100)
.FadeTo(0f, 100);
}
}
protected override void OnSliderEnd()
{
this.ScaleTo(1.6f, 200, Easing.Out)
.FadeOut(200, Easing.In);
}
}
}
|
mit
|
C#
|
2aa330da6abd2bad9c754930099766c0fefc93b2
|
add hyperlink to layout page
|
rippo/CQSMediatorPattern
|
Cqs.Mediator.Pattern.Mvc/Views/Shared/_Layout.cshtml
|
Cqs.Mediator.Pattern.Mvc/Views/Shared/_Layout.cshtml
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/login">/Login</a></li>
<li><a href="/contact">/Contact</a></li>
<li><a href="/sitemap">/SiteMap</a></li>
<li><a href="/test">/test</a></li>
<li><a href="/sitemap.xml">/SiteMap.xml</a></li>
<li><a href="/products/widget/a">/products/widget/a</a></li>
<li><a href="/products/widget/b">/products/widget/b</a></li>
<li><a href="@Url.Action("Index","Customer")">Customers</a></li>
</ul>
@RenderBody()
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/login">/Login</a></li>
<li><a href="/contact">/Contact</a></li>
<li><a href="/sitemap">/SiteMap</a></li>
<li><a href="/test">/test</a></li>
<li><a href="/sitemap.xml">/SiteMap.xml</a></li>
<li><a href="/products/widget/a">/products/widget/a</a></li>
<li><a href="/products/widget/b">/products/widget/b</a></li>
</ul>
@RenderBody()
</body>
</html>
|
mit
|
C#
|
6e41e501555edbe27134c5ded151a43d47d9e2b1
|
Implement MainViewModel
|
sakapon/Tools-2017
|
EpidemicSimulator/EpidemicSimulator/MainViewModel.cs
|
EpidemicSimulator/EpidemicSimulator/MainViewModel.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Reactive.Bindings;
namespace EpidemicSimulator
{
public class MainViewModel
{
static readonly TimeSpan RenderingInterval = TimeSpan.FromSeconds(1 / 30.0);
const int PopulationBarWidth = 1000;
public AppModel AppModel { get; } = new AppModel();
public ReactiveProperty<InfectionModel> InfectionModel { get; } = new ReactiveProperty<InfectionModel>(mode: ReactivePropertyMode.DistinctUntilChanged);
public ReadOnlyReactiveProperty<byte[]> PopulationImage { get; }
public ReadOnlyReactiveProperty<PopulationSummary> PopulationSummary { get; }
public ReadOnlyReactiveProperty<PopulationLayout> PopulationLayout { get; }
IDisposable subscription;
public MainViewModel()
{
PopulationImage = InfectionModel.Select(DataModel.GetBitmapBinary).ToReadOnlyReactiveProperty();
PopulationSummary = InfectionModel.Select(DataModel.ToSummary).ToReadOnlyReactiveProperty();
PopulationLayout = PopulationSummary.Select(ToLayout).ToReadOnlyReactiveProperty();
AppModel.IsRunning
.Where(b => b)
.Subscribe(b =>
{
subscription = Observable.Interval(RenderingInterval)
.Subscribe(_ => InfectionModel.Value = AppModel.CurrentInfection);
});
AppModel.IsRunning
.Where(b => !b)
.Subscribe(b =>
{
subscription?.Dispose();
subscription = null;
});
}
static PopulationLayout ToLayout(PopulationSummary s)
{
var width_s = (int)Math.Round(PopulationBarWidth * ((double)s.Susceptible / s.Total), MidpointRounding.AwayFromZero);
var width_i = (int)Math.Round(PopulationBarWidth * ((double)s.Infectious / s.Total), MidpointRounding.AwayFromZero);
return new PopulationLayout
{
SusceptibleWidth = width_s,
InfectiousWidth = width_i,
RecoveredWidth = PopulationBarWidth - width_s - width_i,
};
}
}
public struct PopulationLayout
{
public int SusceptibleWidth { get; set; }
public int InfectiousWidth { get; set; }
public int RecoveredWidth { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EpidemicSimulator
{
public class MainViewModel
{
public AppModel AppModel { get; } = new AppModel();
}
}
|
mit
|
C#
|
7ab9caac0bff416d3830655b93916cee80a7c223
|
fix exit command.
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Shell/Commands/SystemCommands.cs
|
WalletWasabi.Gui/Shell/Commands/SystemCommands.cs
|
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using AvalonStudio.Commands;
using ReactiveUI;
using System;
using System.Composition;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class SystemCommands
{
public Global Global { get; }
[DefaultKeyGesture("ALT+F4", osxKeyGesture: "CMD+Q")]
[ExportCommandDefinition("File.Exit")]
public CommandDefinition ExitCommand { get; }
[ImportingConstructor]
public SystemCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = Guard.NotNull(nameof(Global), global.Global);
var exit = ReactiveCommand.Create(OnExit);
exit.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex));
ExitCommand = new CommandDefinition(
"Quit WasabiWallet",
commandIconService.GetCompletionKindImage("Exit"),
exit);
}
private void OnExit()
{
(Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow.Close();
}
}
}
|
using Avalonia;
using AvalonStudio.Commands;
using ReactiveUI;
using System;
using System.Composition;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class SystemCommands
{
public Global Global { get; }
[ExportCommandDefinition("File.Exit")]
public CommandDefinition ExitCommand { get; }
[ImportingConstructor]
public SystemCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = Guard.NotNull(nameof(Global), global.Global);
var exit = ReactiveCommand.Create(OnExit);
exit.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex));
ExitCommand = new CommandDefinition(
"Quit WasabiWallet",
commandIconService.GetCompletionKindImage("Exit"),
exit);
}
private void OnExit()
{
//Application.Current.MainWindow.Close();
}
}
}
|
mit
|
C#
|
7c694927291cd9a4faaa2b31bc1cafd9309bd413
|
Comment test
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Tests/UnitTests/UpdateStatusTests.cs
|
WalletWasabi.Tests/UnitTests/UpdateStatusTests.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Models;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class UpdateStatusTests
{
[Fact]
public void TestEquality()
{
var backendCompatible = false;
var clientUpToDate = false;
var legalVersion = new Version(1, 1);
ushort backendVersion = 1;
// Create a new instance with the same parameters and make sure they're equal.
var x = new UpdateStatus(backendCompatible, clientUpToDate, legalVersion, backendVersion);
var y = new UpdateStatus(backendCompatible, clientUpToDate, legalVersion, backendVersion);
Assert.Equal(x, y);
Assert.Equal(x.GetHashCode(), y.GetHashCode());
// Change one parameter at a time and make sure they aren't equal.
y = new UpdateStatus(true, clientUpToDate, legalVersion, backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(backendCompatible, true, legalVersion, backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(backendCompatible, clientUpToDate, new Version(2, 2), backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(backendCompatible, clientUpToDate, legalVersion, 2);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
// Mess around with the versions a bit and make sure they aren't equal.
y = new UpdateStatus(backendCompatible, clientUpToDate, new Version(1, 1, 1), backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Models;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class UpdateStatusTests
{
[Fact]
public void TestEquality()
{
var backendCompatible = false;
var clientUpToDate = false;
var legalVersion = new Version(1, 1);
ushort backendVersion = 1;
var x = new UpdateStatus(backendCompatible, clientUpToDate, legalVersion, backendVersion);
var y = new UpdateStatus(backendCompatible, clientUpToDate, legalVersion, backendVersion);
Assert.Equal(x, y);
Assert.Equal(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(true, clientUpToDate, legalVersion, backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(backendCompatible, true, legalVersion, backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(backendCompatible, clientUpToDate, new Version(2, 2), backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(backendCompatible, clientUpToDate, new Version(1, 1, 1), backendVersion);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
y = new UpdateStatus(backendCompatible, clientUpToDate, legalVersion, 2);
Assert.NotEqual(x, y);
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
}
}
}
|
mit
|
C#
|
b77f29e50da1cc5192442813d1e35f214999f274
|
Use build in methods to check if a character is printable.
|
jesterret/ReClass.NET,jesterret/ReClass.NET,jesterret/ReClass.NET
|
ReClass.NET/Extensions/StringExtensions.cs
|
ReClass.NET/Extensions/StringExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text.RegularExpressions;
namespace ReClassNET.Extensions
{
public static class StringExtension
{
[Pure]
[DebuggerStepThrough]
public static bool IsPrintable(this char c)
{
return !char.IsControl(c) || char.IsWhiteSpace(c);
}
[DebuggerStepThrough]
public static IEnumerable<char> InterpretAsUtf8(this IEnumerable<byte> source)
{
Contract.Requires(source != null);
return source.Select(b => (char)b);
}
[DebuggerStepThrough]
public static IEnumerable<char> InterpretAsUtf16(this IEnumerable<byte> source)
{
Contract.Requires(source != null);
var bytes = source.ToArray();
var chars = new char[bytes.Length / 2];
Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return chars;
}
[DebuggerStepThrough]
public static bool IsPrintableData(this IEnumerable<char> source)
{
Contract.Requires(source != null);
return CalculatePrintableDataThreshold(source) >= 1.0f;
}
[DebuggerStepThrough]
public static bool IsLikelyPrintableData(this IEnumerable<char> source)
{
Contract.Requires(source != null);
return CalculatePrintableDataThreshold(source) >= 0.75f;
}
[DebuggerStepThrough]
public static float CalculatePrintableDataThreshold(this IEnumerable<char> source)
{
var doCountValid = true;
var countValid = 0;
var countAll = 0;
foreach (var c in source)
{
countAll++;
if (doCountValid)
{
if (c.IsPrintable())
{
countValid++;
}
else
{
doCountValid = false;
}
}
}
if (countAll == 0)
{
return 0.0f;
}
return countValid / (float)countAll;
}
[Pure]
[DebuggerStepThrough]
public static string LimitLength(this string s, int length)
{
Contract.Requires(s != null);
Contract.Ensures(Contract.Result<string>() != null);
if (s.Length <= length)
{
return s;
}
return s.Substring(0, length);
}
private static readonly Regex HexRegex = new Regex("(0x|h)?([0-9A-F]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static bool TryGetHexString(this string s, out string value)
{
var match = HexRegex.Match(s);
value = match.Success ? match.Groups[2].Value : null;
return match.Success;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text.RegularExpressions;
namespace ReClassNET.Extensions
{
public static class StringExtension
{
[Pure]
[DebuggerStepThrough]
public static bool IsPrintable(this char c)
{
return ' ' <= c && c <= '~';
}
[DebuggerStepThrough]
public static IEnumerable<char> InterpretAsUtf8(this IEnumerable<byte> source)
{
Contract.Requires(source != null);
return source.Select(b => (char)b);
}
[DebuggerStepThrough]
public static IEnumerable<char> InterpretAsUtf16(this IEnumerable<byte> source)
{
Contract.Requires(source != null);
var bytes = source.ToArray();
var chars = new char[bytes.Length / 2];
Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return chars;
}
[DebuggerStepThrough]
public static bool IsPrintableData(this IEnumerable<char> source)
{
Contract.Requires(source != null);
return CalculatePrintableDataThreshold(source) >= 1.0f;
}
[DebuggerStepThrough]
public static bool IsLikelyPrintableData(this IEnumerable<char> source)
{
Contract.Requires(source != null);
return CalculatePrintableDataThreshold(source) >= 0.75f;
}
[DebuggerStepThrough]
public static float CalculatePrintableDataThreshold(this IEnumerable<char> source)
{
var doCountValid = true;
var countValid = 0;
var countAll = 0;
foreach (var c in source)
{
countAll++;
if (doCountValid)
{
if (c.IsPrintable())
{
countValid++;
}
else
{
doCountValid = false;
}
}
}
return countValid / (float)countAll;
}
[Pure]
[DebuggerStepThrough]
public static string LimitLength(this string s, int length)
{
Contract.Requires(s != null);
Contract.Ensures(Contract.Result<string>() != null);
if (s.Length <= length)
{
return s;
}
return s.Substring(0, length);
}
private static readonly Regex HexRegex = new Regex("(0x|h)?([0-9A-F]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static bool TryGetHexString(this string s, out string value)
{
var match = HexRegex.Match(s);
value = match.Success ? match.Groups[2].Value : null;
return match.Success;
}
}
}
|
mit
|
C#
|
5da1e35fb6e60bb09fadfce4d10d679e8c21882f
|
add AttributeInterceptorCache
|
AspectCore/Lite,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Abstractions
|
src/AspectCore.Lite/Internal/AttributeInterceptorMatcher.cs
|
src/AspectCore.Lite/Internal/AttributeInterceptorMatcher.cs
|
using System.Collections.Concurrent;
using AspectCore.Lite.Abstractions;
using AspectCore.Lite.Common;
using AspectCore.Lite.Extensions;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace AspectCore.Lite.Internal
{
internal class AttributeInterceptorMatcher : IInterceptorMatcher
{
private static readonly ConcurrentDictionary<MethodInfo, IInterceptor[]> AttributeInterceptorCache =
new ConcurrentDictionary<MethodInfo, IInterceptor[]>();
private static IEnumerable<IInterceptor> InterceptorsIterator(MethodInfo methodInfo, TypeInfo typeInfo)
{
foreach (var attribute in typeInfo.GetCustomAttributes())
{
var interceptor = attribute as IInterceptor;
if (interceptor != null) yield return interceptor;
}
foreach (var attribute in methodInfo.GetCustomAttributes())
{
var interceptor = attribute as IInterceptor;
if (interceptor != null) yield return interceptor;
}
}
public IInterceptor[] Match(MethodInfo method, TypeInfo typeInfo)
{
ExceptionHelper.ThrowArgumentNull(method, nameof(method));
ExceptionHelper.ThrowArgumentNull(typeInfo, nameof(typeInfo));
return AttributeInterceptorCache.GetOrAdd(method, key =>
{
var interceptorAttributes = InterceptorsIterator(method, typeInfo);
return interceptorAttributes.Distinct(i => i.GetType()).OrderBy(i => i.Order).ToArray();
});
}
}
}
|
using AspectCore.Lite.Abstractions;
using AspectCore.Lite.Common;
using AspectCore.Lite.Extensions;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace AspectCore.Lite.Internal
{
internal class AttributeInterceptorMatcher : IInterceptorMatcher
{
private static IEnumerable<IInterceptor> InterceptorsIterator(MethodInfo methodInfo, TypeInfo typeInfo)
{
foreach (var attribute in typeInfo.GetCustomAttributes())
{
var interceptor = attribute as IInterceptor;
if (interceptor != null) yield return interceptor;
}
foreach (var attribute in methodInfo.GetCustomAttributes())
{
var interceptor = attribute as IInterceptor;
if (interceptor != null) yield return interceptor;
}
}
public IInterceptor[] Match(MethodInfo method, TypeInfo typeInfo)
{
ExceptionHelper.ThrowArgumentNull(method, nameof(method));
ExceptionHelper.ThrowArgumentNull(typeInfo, nameof(typeInfo));
var interceptorAttributes = InterceptorsIterator(method, typeInfo);
return interceptorAttributes.Distinct(i => i.GetType()).OrderBy(i => i.Order).ToArray();
}
}
}
|
mit
|
C#
|
7adbd75d41de363b9be151d573fff4f78c4e6b0e
|
Add edit links to noitces admin
|
planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS
|
src/Orchard.Web/Modules/LETS/Views/NoticesAdmin/List.cshtml
|
src/Orchard.Web/Modules/LETS/Views/NoticesAdmin/List.cshtml
|
@using LETS.Helpers;
@model LETS.ViewModels.MemberNoticesViewModel
<h1>@string.Format("{0}'s {1}", @Model.Member.FirstLastName, T("notices"))</h1>
@if (Model.Notices.Count().Equals(0))
{
<p>@T("This member doesn't have any active notices")</p>
}
@foreach (var notice in Model.Notices)
{
var id = notice.ContentItem.Id;
@Display(notice)
@Html.ActionLink(T("Edit").ToString(), "Edit", "Notice", new { area = "LETS", id = id }, new { @class = "edit" }) @:|
@Html.ActionLink(T("Delete").ToString(), "Delete", "Notice", new { area = "LETS", id = id }, new { @class = "edit", itemprop = "UnsafeUrl RemoveUrl" }) @:|
@*var published = Helpers.IsPublished(notice.ContentPart.Id);
if (published)
{
@Html.Link(T("Archive").Text, Url.Action("Unpublish", "Notice", new { area = "LETS", id = notice.Id }), new { @class = "edit", itemprop = "UnsafeUrl ArchiveUrl" })
}
else
{
@Html.ActionLink(T("Publish").ToString(), "Publish", "Notice", new { area = "LETS", id = notice.Id }, new { @class = "edit", itemprop = "UnsafeUrl" })
}*@
}
@{
<div id="archivedNotices">
<h2>@T("Archived notices")</h2>
<p><strong>@T("Expired notices will show up here until they are deleted or re-activated by publishing them.")</strong></p>
<p>@T("Notices can also be archived if you don't want to delete them yet")</p>
@if (Model.ArchivedNotices.Any())
{
foreach (var archivedNotice in Model.ArchivedNotices)
{
@Display(archivedNotice)
}
}
</div>
}
@Html.AntiForgeryTokenOrchard()
|
@model LETS.ViewModels.MemberNoticesViewModel
<h1>@string.Format("{0}'s {1}", @Model.Member.FirstLastName, T("notices"))</h1>
@if (Model.Notices.Count().Equals(0))
{
<p>@T("This member doesn't have any active notices")</p>
}
@foreach (var notice in Model.Notices)
{
@Display(notice)
}
@{
<div id="archivedNotices">
<h2>@T("Archived notices")</h2>
<p><strong>@T("Expired notices will show up here until they are deleted or re-activated by publishing them.")</strong></p>
<p>@T("Notices can also be archived if you don't want to delete them yet")</p>
@if (Model.ArchivedNotices.Any())
{
foreach (var archivedNotice in Model.ArchivedNotices)
{
@Display(archivedNotice)
}
}
</div>
}
|
bsd-3-clause
|
C#
|
1c029acaba010dd099b2417e10da9d62680ac130
|
Make tests pass
|
christophertrml/rassoodock,christophertrml/rassoodock,cjqed/rassoodock
|
Rassoodock.Tests.Base/WhenRunningIntegrationTests.cs
|
Rassoodock.Tests.Base/WhenRunningIntegrationTests.cs
|
using System;
using System.Data.SqlClient;
using Dapper;
using Rassoodock.Common;
using Rassoodock.Startup;
namespace Rassoodock.Tests.Base
{
public class WhenRunningIntegrationTests
{
protected readonly LinkedDatabase Database;
private const string EnvironmentVariableName = "TestSqlServer";
public WhenRunningIntegrationTests()
{
if (Environment.GetEnvironmentVariable(EnvironmentVariableName) == null)
{
Environment.SetEnvironmentVariable(
EnvironmentVariableName,
"Data Source=localhost;Integrated Security=True;");
}
Database = new LinkedDatabase
{
DatabaseType = DatabaseType.SqlServer,
ConnectionString = Environment.GetEnvironmentVariable(EnvironmentVariableName),
Name = EnhancedRandom.String(10, 20)
};
using (var conn = new SqlConnection(Database.ConnectionString))
{
conn.Open();
var exists = conn.ExecuteScalar<bool>("SELECT 1 FROM sys.databases WHERE name = @name",
new
{
name = Database.Name
});
if (!exists)
{
conn.Execute($"CREATE DATABASE {Database.Name}");
}
else
{
conn.Execute($"DROP DATABASE {Database.Name}");
conn.Execute($"CREATE DATABASE {Database.Name}");
}
}
var automapperStartup = new AutomapperStartup();
automapperStartup.Startup(null);
}
}
}
|
using System;
using System.Data.SqlClient;
using Dapper;
using Rassoodock.Common;
using Rassoodock.Startup;
namespace Rassoodock.Tests.Base
{
public class WhenRunningIntegrationTests
{
protected readonly LinkedDatabase Database;
private const string EnvironmentVariableName = "TestSqlServer";
public WhenRunningIntegrationTests()
{
// if (Environment.GetEnvironmentVariable(EnvironmentVariableName) == null)
// {
// Environment.SetEnvironmentVariable(
// EnvironmentVariableName,
// "Data Source=localhost;Integrated Security=True;");
// }
Console.WriteLine("Env var: " + Environment.GetEnvironmentVariable(EnvironmentVariableName));
Database = new LinkedDatabase
{
DatabaseType = DatabaseType.SqlServer,
ConnectionString = Environment.GetEnvironmentVariable(EnvironmentVariableName),
Name = EnhancedRandom.String(10, 20)
};
using (var conn = new SqlConnection(Database.ConnectionString))
{
conn.Open();
var exists = conn.ExecuteScalar<bool>("SELECT 1 FROM sys.databases WHERE name = @name",
new
{
name = Database.Name
});
if (!exists)
{
conn.Execute($"CREATE DATABASE {Database.Name}");
}
else
{
conn.Execute($"DROP DATABASE {Database.Name}");
conn.Execute($"CREATE DATABASE {Database.Name}");
}
}
var automapperStartup = new AutomapperStartup();
automapperStartup.Startup(null);
}
}
}
|
apache-2.0
|
C#
|
4f3d66e8509430b0e9062093d6eec4aca0aa561f
|
remove a keyword
|
gregsdennis/Manatee.Json,gregsdennis/Manatee.Json
|
Manatee.Json/Schema/SchemaKeywordCatalog.cs
|
Manatee.Json/Schema/SchemaKeywordCatalog.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Manatee.Json.Serialization;
using Manatee.Json.Serialization.Internal;
namespace Manatee.Json.Schema
{
public static class SchemaKeywordCatalog
{
private static readonly Dictionary<string, List<Type>> _cache = new Dictionary<string, List<Type>>();
private static readonly ConstructorResolver _resolver = new ConstructorResolver();
static SchemaKeywordCatalog()
{
var keywordTypes = typeof(IJsonSchemaKeyword).GetTypeInfo().Assembly.DefinedTypes
.Where(t => typeof(IJsonSchemaKeyword).GetTypeInfo().IsAssignableFrom(t) &&
!t.IsAbstract)
.Select(ti => ti.AsType());
var method = typeof(SchemaKeywordCatalog).GetTypeInfo().DeclaredMethods
.Single(m => m.Name == nameof(Add));
foreach (var keywordType in keywordTypes)
{
method.MakeGenericMethod(keywordType).Invoke(null, new object[] { });
}
}
public static void Add<T>()
where T : IJsonSchemaKeyword, new()
{
var keyword = (T) _resolver.Resolve(typeof(T));
if (!_cache.TryGetValue(keyword.Name, out var list))
{
list = new List<Type>();
_cache[keyword.Name] = list;
}
if (!list.Contains(typeof(T)))
list.Add(typeof(T));
}
public static void Remove<T>()
where T : IJsonSchemaKeyword, new()
{
var keyword = (T) _resolver.Resolve(typeof(T));
if (!_cache.TryGetValue(keyword.Name, out var list)) return;
list.Remove(typeof(T));
}
internal static IJsonSchemaKeyword Build(string keywordName, JsonValue json, JsonSerializer serializer)
{
if (!_cache.TryGetValue(keywordName, out var list) || !list.Any())
return null;
IJsonSchemaKeyword keyword = null;
var specials = list.Where(t => t.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IJsonSchemaKeywordPlus)))
.Select(t => (IJsonSchemaKeywordPlus) _resolver.Resolve(t))
.ToList();
if (specials.Any())
keyword = specials.FirstOrDefault(k => k.Handles(json));
if (keyword == null)
keyword = (IJsonSchemaKeyword) _resolver.Resolve(list.First());
keyword.FromJson(json, serializer);
return keyword;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Manatee.Json.Serialization;
using Manatee.Json.Serialization.Internal;
namespace Manatee.Json.Schema
{
public static class SchemaKeywordCatalog
{
private static readonly Dictionary<string, List<Type>> _cache = new Dictionary<string, List<Type>>();
private static readonly ConstructorResolver _resolver = new ConstructorResolver();
static SchemaKeywordCatalog()
{
var keywordTypes = typeof(IJsonSchemaKeyword).GetTypeInfo().Assembly.DefinedTypes
.Where(t => typeof(IJsonSchemaKeyword).GetTypeInfo().IsAssignableFrom(t) &&
!t.IsAbstract)
.Select(ti => ti.AsType());
var method = typeof(SchemaKeywordCatalog).GetTypeInfo().DeclaredMethods
.Single(m => m.Name == nameof(Add));
foreach (var keywordType in keywordTypes)
{
method.MakeGenericMethod(keywordType).Invoke(null, new object[] { });
}
}
public static void Add<T>()
where T : IJsonSchemaKeyword, new()
{
var keyword = (T) _resolver.Resolve(typeof(T));
if (!_cache.TryGetValue(keyword.Name, out var list))
{
list = new List<Type>();
_cache[keyword.Name] = list;
}
if (!list.Contains(typeof(T)))
list.Add(typeof(T));
}
internal static IJsonSchemaKeyword Build(string keywordName, JsonValue json, JsonSerializer serializer)
{
if (!_cache.TryGetValue(keywordName, out var list) || !list.Any())
return null;
IJsonSchemaKeyword keyword = null;
var specials = list.Where(t => t.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IJsonSchemaKeywordPlus)))
.Select(t => (IJsonSchemaKeywordPlus) _resolver.Resolve(t))
.ToList();
if (specials.Any())
keyword = specials.FirstOrDefault(k => k.Handles(json));
if (keyword == null)
keyword = (IJsonSchemaKeyword) _resolver.Resolve(list.First());
keyword.FromJson(json, serializer);
return keyword;
}
}
}
|
mit
|
C#
|
fdedff3ad762727c0dda615118abdf53c60f7de1
|
Fix comments
|
takenet/blip-sdk-csharp
|
src/Take.Blip.Client/Content/InputExpirationTimeDocument.cs
|
src/Take.Blip.Client/Content/InputExpirationTimeDocument.cs
|
using Lime.Protocol;
using System.Runtime.Serialization;
namespace Take.Blip.Client.Content
{
/// <summary>
/// Represents an expired input with an user's <see cref="Identity"/> to make a fake input
/// </summary>
[DataContract]
public class InputExpirationTimeDocument : Document
{
public const string MIME_TYPE = "application/vnd.blip-client.inputexpirationtime+json";
/// <summary>
/// Identity of the user whose input was expired. This identity will be used to make a fake input.
/// </summary>
[DataMember(Name = "identity")]
public Identity Identity { get; set; }
public InputExpirationTimeDocument(): base(MediaType.Parse(MIME_TYPE))
{ }
}
}
|
using Lime.Protocol;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace Take.Blip.Client.Content
{
/// <summary>
/// Represents a expired input with a <see cref="Identity"/> of user to make a fake input
/// </summary>
[DataContract]
public class InputExpirationTimeDocument : Document
{
public const string MIME_TYPE = "application/vnd.blip-client.inputexpirationtime+json";
/// <summary>
/// Identity of user that input was expired. This identity will be used to make a fake input.
/// </summary>
[DataMember(Name = "identity")]
public Identity Identity { get; set; }
public InputExpirationTimeDocument(): base(MediaType.Parse(MIME_TYPE))
{ }
}
}
|
apache-2.0
|
C#
|
380f7a190b464cd09bdbbf45f0c2a9425f48591b
|
Increase version to 1.1.1.0
|
ladimolnar/BitcoinBlockchain
|
Sources/BitcoinBlockchain/Properties/AssemblyInfo.cs
|
Sources/BitcoinBlockchain/Properties/AssemblyInfo.cs
|
//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BitcoinBlockchain")]
[assembly: AssemblyDescription("A .NET Class Library that provides parsing functionality over files containing the Bitcoin blockchain.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ladislau Molnar")]
[assembly: AssemblyProduct("BitcoinBlockchain")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("4d8ebb2b-d182-4106-8d15-5fb864de6706")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
|
//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BitcoinBlockchain")]
[assembly: AssemblyDescription("A .NET Class Library that provides parsing functionality over files containing the Bitcoin blockchain.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ladislau Molnar")]
[assembly: AssemblyProduct("BitcoinBlockchain")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("4d8ebb2b-d182-4106-8d15-5fb864de6706")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
apache-2.0
|
C#
|
8e7c5bfd6a4e9e296d18a719388810e1f12db270
|
Increase assembly version
|
Puchaczov/TQL.RDL
|
TQL.RDL/TQL.RDL.Converter/Properties/AssemblyInfo.cs
|
TQL.RDL/TQL.RDL.Converter/Properties/AssemblyInfo.cs
|
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("TQL.RDL")]
[assembly: AssemblyDescription("Small language used to querying time")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TQL")]
[assembly: AssemblyProduct("TQL.RDL")]
[assembly: AssemblyCopyright("Jakub Puchała © 2016")]
[assembly: AssemblyTrademark("TQL")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("0.5.1.0")]
[assembly: AssemblyFileVersion("0.5.1.0")]
|
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("TQL.RDL")]
[assembly: AssemblyDescription("Small language used to querying time")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TQL")]
[assembly: AssemblyProduct("TQL.RDL")]
[assembly: AssemblyCopyright("Jakub Puchała © 2016")]
[assembly: AssemblyTrademark("TQL")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("0.5.0.4")]
[assembly: AssemblyFileVersion("0.5.0.4")]
|
apache-2.0
|
C#
|
1ad6ffe90003a7af33cc92c4d695f34ac5b84593
|
Add an endpoint for the view page
|
Ranger1230/IoTClass-SmartCam,Ranger1230/IoTClass-SmartCam
|
SmartCam/Controllers/SmartCamController.cs
|
SmartCam/Controllers/SmartCamController.cs
|
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;
namespace SmartCam.Controllers
{
public class SmartCamController : Controller
{
private static byte[] currentImage = new byte[0];
[HttpPost]
public string PostImage(HttpPostedFileBase file)
{
Stream fileStream = file.InputStream;
using (MemoryStream ms = new MemoryStream())
{
fileStream.CopyTo(ms);
currentImage = ms.GetBuffer();
}
return "Success";
}
[HttpGet]
public FileResult GetPicture()
{
return new FileStreamResult(new MemoryStream(currentImage), "image/jpeg");
}
[HttpGet]
public ActionResult ShowFeed()
{
return View();
}
[HttpGet]
public string SendNotification()
{
var fromAddress = new MailAddress(from, "From Name");
var toAddress = new MailAddress(to, "To Name");
const string fromPassword = ;
const string subject = "SmartCam";
const string body = "Motion Detected!";
using (SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
})
{
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
return "Success";
}
}
}
|
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;
namespace SmartCam.Controllers
{
public class SmartCamController : Controller
{
private static byte[] currentImage = new byte[0];
[HttpPost]
public string PostImage(HttpPostedFileBase file)
{
Stream fileStream = file.InputStream;
using (MemoryStream ms = new MemoryStream())
{
fileStream.CopyTo(ms);
currentImage = ms.GetBuffer();
}
return "Success";
}
[HttpGet]
public FileResult GetPicture()
{
return new FileStreamResult(new MemoryStream(currentImage), "image/jpeg");
}
[HttpGet]
public string SendNotification()
{
var fromAddress = new MailAddress(from, "From Name");
var toAddress = new MailAddress(to, "To Name");
const string fromPassword = ;
const string subject = "SmartCam";
const string body = "Motion Detected!";
using (SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
})
{
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
return "Success";
}
}
}
|
mit
|
C#
|
42e575085484d2dfe2ca7ae003ff9118bb9b9ff4
|
Adjust to new CorePlugin API #CHANGE: Adjusted the DualStickSpaceShooter sample to use the new OnGameStarted CorePlugin API instead of waiting for the first frame update to arrive.
|
BraveSirAndrew/duality,Barsonax/duality,mfep/duality,AdamsLair/duality,SirePi/duality
|
Samples/DualStickSpaceShooter/CorePlugin.cs
|
Samples/DualStickSpaceShooter/CorePlugin.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Duality;
namespace DualStickSpaceShooter
{
public class DualStickSpaceShooterCorePlugin : CorePlugin
{
protected override void OnGameStarting()
{
base.OnGameStarting();
// Load all available content so we don't need on-demand loading at runtime.
// It's probably not a good idea for content-rich games, consider having a per-level
// loading screen instead, or something similar.
Log.Game.Write("Loading game content...");
Log.Game.PushIndent();
{
List<ContentRef<Resource>> availableContent = ContentProvider.GetAvailableContent<Resource>();
foreach (ContentRef<Resource> resourceReference in availableContent)
{
resourceReference.MakeAvailable();
}
}
Log.Game.PopIndent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Duality;
namespace DualStickSpaceShooter
{
public class DualStickSpaceShooterCorePlugin : CorePlugin
{
private bool contentLoaded = false;
protected override void OnBeforeUpdate()
{
base.OnBeforeUpdate();
// Load all available content so we don't need on-demand loading during runtime.
// It's probably not a good idea for content-rich games, consider having a per-level
// loading screen instead, or something similar.
if (!this.contentLoaded && DualityApp.ExecContext == DualityApp.ExecutionContext.Game)
{
Log.Game.Write("Loading game content...");
Log.Game.PushIndent();
{
List<ContentRef<Resource>> availableContent = ContentProvider.GetAvailableContent<Resource>();
foreach (ContentRef<Resource> resourceReference in availableContent)
{
resourceReference.MakeAvailable();
}
}
Log.Game.PopIndent();
this.contentLoaded = true;
}
}
}
}
|
mit
|
C#
|
2b5e0c64a01a86e665dbb7a242c27d82a1d6d87d
|
improve payment status update logic
|
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
|
src/SFA.DAS.Commitments.Application/Commands/UpdateApprenticeshipStatus/UpdateApprenticeshipStatusCommandHandler.cs
|
src/SFA.DAS.Commitments.Application/Commands/UpdateApprenticeshipStatus/UpdateApprenticeshipStatusCommandHandler.cs
|
using System;
using System.Threading.Tasks;
using FluentValidation;
using MediatR;
using NLog;
using SFA.DAS.Commitments.Application.Exceptions;
using SFA.DAS.Commitments.Domain.Data;
using SFA.DAS.Commitments.Domain.Entities;
namespace SFA.DAS.Commitments.Application.Commands.UpdateApprenticeshipStatus
{
public sealed class UpdateApprenticeshipStatusCommandHandler : AsyncRequestHandler<UpdateApprenticeshipStatusCommand>
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly ICommitmentRepository _commitmentRepository;
private readonly UpdateApprenticeshipStatusValidator _validator;
public UpdateApprenticeshipStatusCommandHandler(ICommitmentRepository commitmentRepository, UpdateApprenticeshipStatusValidator validator)
{
_commitmentRepository = commitmentRepository;
_validator = validator;
}
protected override async Task HandleCore(UpdateApprenticeshipStatusCommand message)
{
Logger.Info($"Employer: {message.AccountId} has called UpdateApprenticeshipStatusCommand");
var validationResult = _validator.Validate(message);
if (!validationResult.IsValid)
throw new ValidationException(validationResult.Errors);
var commitment = await _commitmentRepository.GetById(message.CommitmentId);
CheckAuthorization(message, commitment);
var apprenticeship = await _commitmentRepository.GetApprenticeship(message.ApprenticeshipId);
var newPaymentStatus = (PaymentStatus) message.PaymentStatus.GetValueOrDefault((Api.Types.PaymentStatus) apprenticeship.PaymentStatus);
await _commitmentRepository.UpdateApprenticeshipStatus(message.CommitmentId, message.ApprenticeshipId, newPaymentStatus);
}
private static void CheckAuthorization(UpdateApprenticeshipStatusCommand message, Commitment commitment)
{
if (commitment.EmployerAccountId != message.AccountId)
throw new UnauthorizedException($"Employer unauthorized to view commitment: {message.CommitmentId}");
}
}
}
|
using System;
using System.Threading.Tasks;
using FluentValidation;
using MediatR;
using NLog;
using SFA.DAS.Commitments.Application.Exceptions;
using SFA.DAS.Commitments.Domain.Data;
using SFA.DAS.Commitments.Domain.Entities;
namespace SFA.DAS.Commitments.Application.Commands.UpdateApprenticeshipStatus
{
public sealed class UpdateApprenticeshipStatusCommandHandler : AsyncRequestHandler<UpdateApprenticeshipStatusCommand>
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly ICommitmentRepository _commitmentRepository;
private readonly UpdateApprenticeshipStatusValidator _validator;
public UpdateApprenticeshipStatusCommandHandler(ICommitmentRepository commitmentRepository, UpdateApprenticeshipStatusValidator validator)
{
_commitmentRepository = commitmentRepository;
_validator = validator;
}
protected override async Task HandleCore(UpdateApprenticeshipStatusCommand message)
{
Logger.Info(BuildInfoMessage(message));
var validationResult = _validator.Validate(message);
if (!validationResult.IsValid)
throw new ValidationException(validationResult.Errors);
var commitment = await _commitmentRepository.GetById(message.CommitmentId);
CheckAuthorization(message, commitment);
//todo: mg check status
var apprenticeship = await _commitmentRepository.GetApprenticeship(message.ApprenticeshipId);
await _commitmentRepository.UpdateApprenticeshipStatus(message.CommitmentId, message.ApprenticeshipId, (PaymentStatus) message.PaymentStatus);
}
private static void CheckAuthorization(UpdateApprenticeshipStatusCommand message, Commitment commitment)
{
if (commitment.EmployerAccountId != message.AccountId)
throw new UnauthorizedException($"Employer unauthorized to view commitment: {message.CommitmentId}");
}
private string BuildInfoMessage(UpdateApprenticeshipStatusCommand cmd)
{
return $"Employer: {cmd.AccountId} has called UpdateApprenticeshipStatusCommand";
}
}
}
|
mit
|
C#
|
e7f91b879c54e59366128959b77466762ba6ff77
|
Update version num
|
mrkno/TitleCleaner
|
TitleCleanerGui/Properties/AssemblyInfo.cs
|
TitleCleanerGui/Properties/AssemblyInfo.cs
|
#region
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TitleCleaner")]
[assembly: AssemblyDescription("Clean Media file names")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Knox Enterprises")]
[assembly: AssemblyProduct("TitleCleanerGui")]
[assembly: AssemblyCopyright("Copyright © Matthew Knox 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f62f1e52-5a22-479d-8017-f41b4d5bc45d")]
// 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.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
[assembly: NeutralResourcesLanguage("en-NZ")]
|
#region
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TitleCleaner")]
[assembly: AssemblyDescription("Clean Media file names")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Knox Enterprises")]
[assembly: AssemblyProduct("TitleCleanerGui")]
[assembly: AssemblyCopyright("Copyright © Matthew Knox 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f62f1e52-5a22-479d-8017-f41b4d5bc45d")]
// 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")]
[assembly: NeutralResourcesLanguage("en-NZ")]
|
mit
|
C#
|
62e0ede51bab7deea3316695eb80de0a55fd7a41
|
update version to 1.5.0.2
|
todor-dk/HTML-Renderer,Perspex/HTML-Renderer,drickert5/HTML-Renderer,slagou/HTML-Renderer,todor-dk/HTML-Renderer,tinygg/graphic-HTML-Renderer,evitself/HTML-Renderer,todor-dk/HTML-Renderer,tinygg/graphic-HTML-Renderer,Perspex/HTML-Renderer,ArthurHub/HTML-Renderer,windygu/HTML-Renderer,evitself/HTML-Renderer,ArthurHub/HTML-Renderer,drickert5/HTML-Renderer,verdesgrobert/HTML-Renderer,tinygg/graphic-HTML-Renderer,verdesgrobert/HTML-Renderer,slagou/HTML-Renderer,windygu/HTML-Renderer
|
Source/SharedAssemblyInfo.cs
|
Source/SharedAssemblyInfo.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("HTML Renderer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Open source hosted on CodePlex")]
[assembly: AssemblyProduct("HTML Renderer")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")]
// Version information for an assembly consists of the following four values:
[assembly: AssemblyVersion("1.5.0.2")]
|
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("HTML Renderer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Open source hosted on CodePlex")]
[assembly: AssemblyProduct("HTML Renderer")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")]
// Version information for an assembly consists of the following four values:
[assembly: AssemblyVersion("1.5.0.1")]
|
bsd-3-clause
|
C#
|
d3a54adc606e293f7992612584176d8869c77a5a
|
Update ValuesController.cs
|
cayodonatti/TopGearApi
|
TopGearApi/Controllers/ValuesController.cs
|
TopGearApi/Controllers/ValuesController.cs
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace TopGearApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
[HttpGet]
[Route("Test")]
public Object Obter()
{
return new { ab = "teste1", cd = "teste2 " };
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace TopGearApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
[HttpGet]
[Route("Test")]
public IHttpActionResult Obter()
{
var content = JsonConvert.SerializeObject(new { ab = "teste1", cd = "teste2 " });
return base.Json(content);
}
}
}
|
mit
|
C#
|
10d0e02ff7e4d28d4253e816658c89f499f9d04a
|
Fix for error in comment and minor style update.
|
autofac/Autofac
|
src/Autofac/NamedParameter.cs
|
src/Autofac/NamedParameter.cs
|
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// https://autofac.org
//
// 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 Autofac.Core;
using Autofac.Util;
namespace Autofac
{
/// <summary>
/// A parameter identified by name. When applied to a reflection-based
/// component, <see cref="Name"/> will be matched against
/// the name of the component's constructor arguments. When applied to
/// a delegate-based component, the parameter can be accessed using
/// <see cref="ParameterExtensions.Named{T}"/>.
/// </summary>
/// <example>
/// <para>
/// Component with parameter...
/// </para>
/// <code>
/// public class MyComponent
/// {
/// public MyComponent(int amount) { ... }
/// }
/// </code>
/// <para>
/// Providing the parameter...
/// </para>
/// <code>
/// var builder = new ContainerBuilder();
/// builder.RegisterType<MyComponent>();
/// var container = builder.Build();
/// var myComponent = container.Resolve<MyComponent>(new NamedParameter("amount", 123));
/// </code>
/// </example>
public class NamedParameter : ConstantParameter
{
/// <summary>
/// Gets the name of the parameter.
/// </summary>
public string Name { get; }
/// <summary>
/// Initializes a new instance of the <see cref="NamedParameter"/> class.
/// </summary>
/// <param name="name">The name of the parameter.</param>
/// <param name="value">The parameter value.</param>
public NamedParameter(string name, object value)
: base(value, pi => pi.Name == name) =>
Name = Enforce.ArgumentNotNullOrEmpty(name, "name");
}
}
|
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// https://autofac.org
//
// 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 Autofac.Core;
using Autofac.Util;
namespace Autofac
{
/// <summary>
/// A parameter identified by name. When applied to a reflection-based
/// component, <see cref="NamedParameter.Name"/> will be matched against
/// the name of the component's constructor arguments. When applied to
/// a delegate-based component, the parameter can be accessed using
/// <see cref="ParameterExtensions.Named"/>.
/// </summary>
/// <example>
/// <para>
/// Component with parameter...
/// </para>
/// <code>
/// public class MyComponent
/// {
/// public MyComponent(int amount) { ... }
/// }
/// </code>
/// <para>
/// Providing the parameter...
/// </para>
/// <code>
/// var builder = new ContainerBuilder();
/// builder.RegisterType<MyComponent>();
/// var container = builder.Build();
/// var myComponent = container.Resolve<MyComponent>(new NamedParameter("amount", 123));
/// </code>
/// </example>
public class NamedParameter : ConstantParameter
{
/// <summary>
/// Gets the name of the parameter.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="NamedParameter"/> class.
/// </summary>
/// <param name="name">The name of the parameter.</param>
/// <param name="value">The parameter value.</param>
public NamedParameter(string name, object value)
: base(value, pi => pi.Name == name)
{
Name = Enforce.ArgumentNotNullOrEmpty(name, "name");
}
}
}
|
mit
|
C#
|
9bd775c5a6c529d7983374cd5af7c06919e9aa5f
|
Check header null
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Backend/Models/FilterModel.cs
|
WalletWasabi/Backend/Models/FilterModel.cs
|
using NBitcoin;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Text;
using WalletWasabi.Blockchain.Blocks;
using WalletWasabi.Helpers;
using WalletWasabi.Interfaces;
using WalletWasabi.JsonConverters;
using WalletWasabi.Models;
namespace WalletWasabi.Backend.Models
{
public class FilterModel
{
public SmartHeader Header { get; }
public GolombRiceFilter Filter { get; }
public FilterModel(SmartHeader header, GolombRiceFilter filter)
{
Header = Guard.NotNull(nameof(header), header);
Filter = Guard.NotNull(nameof(filter), filter);
}
// https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
// The parameter k MUST be set to the first 16 bytes of the hash of the block for which the filter
// is constructed.This ensures the key is deterministic while still varying from block to block.
public byte[] FilterKey => Header.BlockHash.ToBytes().Take(16).ToArray();
public string ToLine()
{
var builder = new StringBuilder();
builder.Append(Header.Height);
builder.Append(":");
builder.Append(Header.BlockHash);
builder.Append(":");
builder.Append(Filter);
builder.Append(":");
builder.Append(Header.PrevHash);
builder.Append(":");
builder.Append(Header.BlockTime.ToUnixTimeSeconds());
return builder.ToString();
}
public static FilterModel FromLine(string line)
{
Guard.NotNullOrEmptyOrWhitespace(nameof(line), line);
string[] parts = line.Split(':');
if (parts.Length < 5)
{
throw new ArgumentException(nameof(line), line);
}
var blockHeight = uint.Parse(parts[0]);
var blockHash = uint256.Parse(parts[1]);
var filterData = Encoders.Hex.DecodeData(parts[2]);
GolombRiceFilter filter = new GolombRiceFilter(filterData, 20, 1 << 20);
var prevBlockHash = uint256.Parse(parts[3]);
var blockTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(parts[4]));
return new FilterModel(new SmartHeader(blockHash, prevBlockHash, blockHeight, blockTime), filter);
}
}
}
|
using NBitcoin;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Text;
using WalletWasabi.Blockchain.Blocks;
using WalletWasabi.Helpers;
using WalletWasabi.Interfaces;
using WalletWasabi.JsonConverters;
using WalletWasabi.Models;
namespace WalletWasabi.Backend.Models
{
public class FilterModel
{
public SmartHeader Header { get; }
public GolombRiceFilter Filter { get; }
public FilterModel(SmartHeader header, GolombRiceFilter filter)
{
Header = header;
Filter = Guard.NotNull(nameof(filter), filter);
}
// https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
// The parameter k MUST be set to the first 16 bytes of the hash of the block for which the filter
// is constructed.This ensures the key is deterministic while still varying from block to block.
public byte[] FilterKey => Header.BlockHash.ToBytes().Take(16).ToArray();
public string ToLine()
{
var builder = new StringBuilder();
builder.Append(Header.Height);
builder.Append(":");
builder.Append(Header.BlockHash);
builder.Append(":");
builder.Append(Filter);
builder.Append(":");
builder.Append(Header.PrevHash);
builder.Append(":");
builder.Append(Header.BlockTime.ToUnixTimeSeconds());
return builder.ToString();
}
public static FilterModel FromLine(string line)
{
Guard.NotNullOrEmptyOrWhitespace(nameof(line), line);
string[] parts = line.Split(':');
if (parts.Length < 5)
{
throw new ArgumentException(nameof(line), line);
}
var blockHeight = uint.Parse(parts[0]);
var blockHash = uint256.Parse(parts[1]);
var filterData = Encoders.Hex.DecodeData(parts[2]);
GolombRiceFilter filter = new GolombRiceFilter(filterData, 20, 1 << 20);
var prevBlockHash = uint256.Parse(parts[3]);
var blockTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(parts[4]));
return new FilterModel(new SmartHeader(blockHash, prevBlockHash, blockHeight, blockTime), filter);
}
}
}
|
mit
|
C#
|
818198edabf81fa3be4f6e5d9e6b55f476d86111
|
Add comment.
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Extensions/StreamExtensions.cs
|
WalletWasabi/Extensions/StreamExtensions.cs
|
using System.Buffers;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public static class StreamExtensions
{
/// <summary>
/// Reads a single byte from <paramref name="stream"/>.
/// </summary>
/// <param name="stream">Stream to read from.</param>
/// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param>
/// <returns><c>-1</c> when no byte could be read, otherwise valid byte value (cast <see cref="int"/> result to <see cref="byte"/>).</returns>
public static async Task<int> ReadByteAsync(this Stream stream, CancellationToken cancellationToken = default)
{
ArrayPool<byte> pool = ArrayPool<byte>.Shared;
byte[] buffer = pool.Rent(1);
try
{
int len = await stream.ReadAsync(buffer.AsMemory(0, 1), cancellationToken).ConfigureAwait(false);
// End of stream.
if (len == 0)
{
return -1;
}
return buffer[0];
}
finally
{
pool.Return(buffer);
}
}
/// <summary>
/// Attempts to read <paramref name="count"/> bytes from <paramref name="stream"/>.
/// </summary>
/// <param name="stream">Stream to read from.</param>
/// <param name="buffer">Buffer whose length must be at least <paramref name="count"/> elements.</param>
/// <param name="count">Number of bytes to read.</param>
/// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param>
/// <returns>Number of read bytes. At most <paramref name="count"/>.</returns>
public static async Task<int> ReadBlockAsync(this Stream stream, byte[] buffer, int count, CancellationToken cancellationToken = default)
{
int remaining = count;
while (remaining != 0)
{
int read = await stream.ReadAsync(buffer.AsMemory(count - remaining, remaining), cancellationToken).ConfigureAwait(false);
// End of stream.
if (read == 0)
{
break;
}
remaining -= read;
}
return count - remaining;
}
}
}
|
using System.Buffers;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public static class StreamExtensions
{
public static async Task<int> ReadByteAsync(this Stream stream, CancellationToken ctsToken = default)
{
ArrayPool<byte> pool = ArrayPool<byte>.Shared;
byte[] buffer = pool.Rent(1);
try
{
int len = await stream.ReadAsync(buffer.AsMemory(0, 1), ctsToken).ConfigureAwait(false);
// End of stream.
if (len == 0)
{
return -1;
}
return buffer[0];
}
finally
{
pool.Return(buffer);
}
}
/// <summary>
/// Attempts to read <paramref name="count"/> bytes from <paramref name="stream"/>.
/// </summary>
/// <param name="stream">Stream to read from.</param>
/// <param name="buffer">Buffer whose length must be at least <paramref name="count"/> elements.</param>
/// <param name="count">Number of bytes to read.</param>
/// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param>
/// <returns>Number of read bytes. At most <paramref name="count"/>.</returns>
public static async Task<int> ReadBlockAsync(this Stream stream, byte[] buffer, int count, CancellationToken cancellationToken = default)
{
int remaining = count;
while (remaining != 0)
{
int read = await stream.ReadAsync(buffer.AsMemory(count - remaining, remaining), cancellationToken).ConfigureAwait(false);
// End of stream.
if (read == 0)
{
break;
}
remaining -= read;
}
return count - remaining;
}
}
}
|
mit
|
C#
|
eba099fc81f41b2e670a800ad2d009047fbac7e2
|
Fix IndexOutOfBounds exception on application closing
|
SVss/SPP_3
|
XmlParserWpf/XmlParserWpf/FilesViewModel.cs
|
XmlParserWpf/XmlParserWpf/FilesViewModel.cs
|
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
namespace XmlParserWpf
{
public class FilesViewModel: ObservableCollection<FilesListItem>
{
public const int NoneSelection = -1;
private int _selectedIndex = NoneSelection;
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
if (_selectedIndex != value)
{
_selectedIndex = value;
OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex"));
OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile"));
}
}
}
public FilesListItem SelectedFile => ((Count > 0) && (SelectedIndex != NoneSelection)) ? this[SelectedIndex] : null;
public void AddAndSelect(FilesListItem item)
{
Add(item);
SelectedIndex = IndexOf(item);
}
public bool HasFile(string path)
{
return this.Any(x => x.Path.Equals(path));
}
public void SelectIfExists(string path)
{
if (HasFile(path))
SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path)));
}
public void RemoveSelected()
{
if (SelectedIndex < 0)
return;
RemoveAt(SelectedIndex);
if (Count == 0)
SelectedIndex = NoneSelection;
}
}
}
|
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
namespace XmlParserWpf
{
public class FilesViewModel: ObservableCollection<FilesListItem>
{
public const int NoneSelection = -1;
private int _selectedIndex = NoneSelection;
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
if (_selectedIndex != value)
{
_selectedIndex = value;
OnPropertyChanged(new PropertyChangedEventArgs("SelectedIndex"));
OnPropertyChanged(new PropertyChangedEventArgs("SelectedFile"));
}
}
}
public FilesListItem SelectedFile => (SelectedIndex != NoneSelection ? this[SelectedIndex] : null);
public void AddAndSelect(FilesListItem item)
{
Add(item);
SelectedIndex = IndexOf(item);
}
public bool HasFile(string path)
{
return this.Any(x => x.Path.Equals(path));
}
public void SelectIfExists(string path)
{
if (HasFile(path))
SelectedIndex = IndexOf(this.First(x => x.Path.Equals(path)));
}
public void RemoveSelected()
{
if (SelectedIndex < 0)
return;
RemoveAt(SelectedIndex);
if (Count == 0)
SelectedIndex = NoneSelection;
}
}
}
|
mit
|
C#
|
24758a7bd3813f6c6be7443ac4a54290e98dbd3d
|
Update RoutineRunner.cs
|
strangeioc/strangerocks
|
StrangeRocks/Assets/scripts/strangerocks/common/util/RoutineRunner.cs
|
StrangeRocks/Assets/scripts/strangerocks/common/util/RoutineRunner.cs
|
//This is a common service/model pattern in Strange:
//We want something usually reserved to MonoBehaviours to be available
//elsewhere. Maybe someday we'll write a version that
//eschews MonoBehaviours altogether...but for now we simply leverage
//that behavior and provide it in injectable form.
//In this case, we're making Coroutines available everywhere in the app
//by attaching a MonoBehaviour to the ContextView.
//IRoutineRunner can be injected anywhere, minimizing direct dependency
//on MonoBehaviours.
using System;
using strange.extensions.context.api;
using UnityEngine;
using System.Collections;
using strange.extensions.injector.api;
namespace strange.examples.strangerocks
{
//An implicit binding. We map this binding as Cross-Context by default.
[Implements(typeof(IRoutineRunner), InjectionBindingScope.CROSS_CONTEXT)]
public class RoutineRunner : IRoutineRunner
{
[Inject(ContextKeys.CONTEXT_VIEW)]
public GameObject contextView{ get; set; }
private RoutineRunnerBehaviour mb;
[PostConstruct]
public void PostConstruct()
{
mb = contextView.AddComponent<RoutineRunnerBehaviour> ();
}
public Coroutine StartCoroutine(IEnumerator routine)
{
return mb.StartCoroutine(routine);
}
}
public class RoutineRunnerBehaviour : MonoBehaviour
{
}
}
|
//This is a common service/model pattern in Strange:
//We want something usually reserved to MonoBehaviours to be available
//elsewhere. Maybe someday we'll write a version that
//eschews MonoBehaviours altogether...but for now we simply leverage
//that behavior and provide it in injectable form.
//In this case, we're making Coroutines available everywhere in the app
//by attaching a MonoBehaviour to the ContextView.
//IRoutineRunner can be injected anywhere, minimizing direct dependency
//on MonoBehaviours.
using System;
using strange.extensions.context.api;
using UnityEngine;
using System.Collections;
using strange.extensions.injector.api;
namespace strange.examples.strangerocks
{
[Implements(typeof(IRoutineRunner), InjectionBindingScope.CROSS_CONTEXT)]
public class RoutineRunner : IRoutineRunner
{
[Inject(ContextKeys.CONTEXT_VIEW)]
public GameObject contextView{ get; set; }
private RoutineRunnerBehaviour mb;
[PostConstruct]
public void PostConstruct()
{
mb = contextView.AddComponent<RoutineRunnerBehaviour> ();
}
public Coroutine StartCoroutine(IEnumerator routine)
{
return mb.StartCoroutine(routine);
}
}
public class RoutineRunnerBehaviour : MonoBehaviour
{
}
}
|
apache-2.0
|
C#
|
b5a2008360b7f6c60faf6ee15fe29211f1890f37
|
Tweak WPF0043.
|
DotNetAnalyzers/WpfAnalyzers
|
WpfAnalyzers.Analyzers/WPF0043DontUseSetCurrentValueForDataContext.cs
|
WpfAnalyzers.Analyzers/WPF0043DontUseSetCurrentValueForDataContext.cs
|
namespace WpfAnalyzers
{
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class WPF0043DontUseSetCurrentValueForDataContext : DiagnosticAnalyzer
{
public const string DiagnosticId = "WPF0043";
private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
id: DiagnosticId,
title: "Don't set DataContext using SetCurrentValue.",
messageFormat: "Use SetValue({0}, {1})",
category: AnalyzerCategory.DependencyProperties,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: AnalyzerConstants.EnabledByDefault,
description: "Set DataContext using SetValue.",
helpLinkUri: HelpLink.ForId(DiagnosticId));
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(HandleInvocation, SyntaxKind.InvocationExpression);
}
private static void HandleInvocation(SyntaxNodeAnalysisContext context)
{
if (context.IsExcludedFromAnalysis())
{
return;
}
if (context.Node is InvocationExpressionSyntax invocation)
{
if (DependencyObject.TryGetSetCurrentValueArguments(invocation, context.SemanticModel, context.CancellationToken, out ArgumentSyntax _, out IFieldSymbol setField, out ArgumentSyntax value) &&
setField == KnownSymbol.FrameworkElement.DataContextProperty)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, invocation.GetLocation(), setField.Name, value));
}
}
}
}
}
|
namespace WpfAnalyzers
{
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class WPF0043DontUseSetCurrentValueForDataContext : DiagnosticAnalyzer
{
public const string DiagnosticId = "WPF0043";
private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
id: DiagnosticId,
title: "Don't set DataContext using SetCurrentValue.",
messageFormat: "Use SetValue({0}, {1})",
category: AnalyzerCategory.DependencyProperties,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: AnalyzerConstants.EnabledByDefault,
description: "Set DataContext using SetValue.",
helpLinkUri: HelpLink.ForId(DiagnosticId));
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(HandleInvocation, SyntaxKind.InvocationExpression);
}
private static void HandleInvocation(SyntaxNodeAnalysisContext context)
{
if (context.IsExcludedFromAnalysis())
{
return;
}
var invocation = context.Node as InvocationExpressionSyntax;
if (invocation == null || context.SemanticModel == null)
{
return;
}
var method = context.SemanticModel.GetSymbolSafe(invocation, context.CancellationToken) as IMethodSymbol;
if (method != KnownSymbol.DependencyObject.SetCurrentValue)
{
return;
}
if (!DependencyObject.TryGetSetCurrentValueArguments(invocation, context.SemanticModel, context.CancellationToken, out ArgumentSyntax _, out IFieldSymbol setField, out ArgumentSyntax value))
{
return;
}
if (setField != KnownSymbol.FrameworkElement.DataContextProperty)
{
return;
}
context.ReportDiagnostic(Diagnostic.Create(Descriptor, invocation.GetLocation(), setField.Name, value));
}
}
}
|
mit
|
C#
|
97eec9d898b120e79f0f30e9d7f202e2d98bf610
|
Update AutofacServiceProvider.cs
|
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
|
utilities/ServiceProvider.Autofac/AutofacServiceProvider.cs
|
utilities/ServiceProvider.Autofac/AutofacServiceProvider.cs
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Autofac;
namespace ServiceProvider.Autofac
{
/// <summary>
/// Service provider based on lifetime scope.
/// </summary>
public class AutofacServiceProvider : IServiceProvider
{
private readonly ILifetimeScope _scope;
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceProvider"/> class.
/// </summary>
/// <param name="scope">The lifetime scope.</param>
public AutofacServiceProvider(ILifetimeScope scope)
{
_scope = scope;
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">The type of resolved service object.</param>
/// <returns>The instance of type <paramref name="serviceType"/>.</returns>
object IServiceProvider.GetService(Type serviceType)
{
return _scope.Resolve(serviceType);
}
}
}
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Autofac;
namespace ServiceProvider.Autofac
{
/// <summary>
/// Service provider based on lifetime scope.
/// </summary>
public class AutofacServiceProvider : IServiceProvider
{
private readonly ILifetimeScope _scope;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceProvider"/> class.
/// </summary>
/// <param name="scope">The lifetime scope.</param>
public ServiceProvider(ILifetimeScope scope)
{
_scope = scope;
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">The type of resolved service object.</param>
/// <returns>The instance of type <paramref name="serviceType"/>.</returns>
object IServiceProvider.GetService(Type serviceType)
{
return _scope.Resolve(serviceType);
}
}
}
|
mit
|
C#
|
7c7d536ea45d6175e9993545ef3176cbd7f4413a
|
Fix gestione codici chiamata in Trasferimento Chiamata
|
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
|
src/backend/SO115App.Persistence.MongoDB/GestioneTrasferimentiChiamate/CodiciChiamate/GetCodiciChiamate.cs
|
src/backend/SO115App.Persistence.MongoDB/GestioneTrasferimentiChiamate/CodiciChiamate/GetCodiciChiamate.cs
|
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Organigramma;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.ServizioSede;
using System.Collections.Generic;
using System.Linq;
namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate
{
public class GetCodiciChiamate : IGetCodiciChiamate
{
private readonly DbContext _dbContext;
private readonly IGetAlberaturaUnitaOperative _getAlberaturaUnitaOperative;
public GetCodiciChiamate(DbContext dbContext, IGetAlberaturaUnitaOperative getAlberaturaUnitaOperative)
{
_dbContext = dbContext;
_getAlberaturaUnitaOperative = getAlberaturaUnitaOperative;
}
public List<string> Get(string CodSede)
{
var listaSediAlberate = _getAlberaturaUnitaOperative.ListaSediAlberata();
var pinNodi = new List<PinNodo>();
pinNodi.Add(new PinNodo(CodSede, true));
foreach (var figlio in listaSediAlberate.GetSottoAlbero(pinNodi))
{
pinNodi.Add(new PinNodo(figlio.Codice, true));
}
var filtroSediCompetenti = Builders<RichiestaAssistenza>.Filter
.In(richiesta => richiesta.CodSOCompetente, pinNodi.Select(uo => uo.Codice));
var lista = _dbContext.RichiestaAssistenzaCollection.Find(filtroSediCompetenti).ToList();
return lista.Where(c => c.TestoStatoRichiesta == "C")
.Select(c => c.Codice).ToList();
}
}
}
|
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Persistence.MongoDB;
using SO115App.Models.Servizi.Infrastruttura.GestioneTrasferimentiChiamate.CodiciChiamate;
using System.Collections.Generic;
namespace SO115App.Persistence.MongoDB.GestioneTrasferimentiChiamate.CodiciChiamate
{
public class GetCodiciChiamate : IGetCodiciChiamate
{
private readonly DbContext _dbContext;
public GetCodiciChiamate(DbContext dbContext) => _dbContext = dbContext;
public List<string> Get(string CodSede)
{
return _dbContext.RichiestaAssistenzaCollection.AsQueryable()
.Where(c => c.TestoStatoRichiesta == "C" && c.CodSOCompetente == CodSede)
.Select(c => c.Codice)
.ToList();
}
}
}
|
agpl-3.0
|
C#
|
ab5c1b760be4e3a67fecfebecdfb37dda88cea57
|
Change of Feature to be the correct String Key
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerAccounts.UnitTests/Commands/CreateLegalEntityCommandTests/WhenTheUserIsNotWhitelistedForExpressionOfInterest.cs
|
src/SFA.DAS.EmployerAccounts.UnitTests/Commands/CreateLegalEntityCommandTests/WhenTheUserIsNotWhitelistedForExpressionOfInterest.cs
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using SFA.DAS.Common.Domain.Types;
using SFA.DAS.EmployerAccounts.Models.Account;
namespace SFA.DAS.EmployerAccounts.UnitTests.Commands.CreateLegalEntityCommandTests
{
public class WhenTheUserIsNotWhitelistedForExpressionOfInterest : CreateLegalEntityCommandTests
{
[SetUp]
public override void Arrange()
{
base.Arrange();
AuthorizationService.Setup(x => x.IsAuthorized("EmployerFeature.ExpressionOfInterest")).Returns(false);
}
[Test]
public async Task ThenAnExpressionOfInterestAgreementIsCreated()
{
var accountId = 12345;
HashingService.Setup(x => x.DecodeValue(Command.HashedAccountId)).Returns(accountId);
EmployerAgreementRepository.Setup(x => x.GetAccountAgreements(accountId)).ReturnsAsync(
new List<EmployerAgreement>
{
new EmployerAgreement { Template = new AgreementTemplate { AgreementType = AgreementType.Levy } }
});
await CommandHandler.Handle(Command);
AccountRepository.Verify(x =>
x.CreateLegalEntityWithAgreement(It.Is<CreateLegalEntityWithAgreementParams>(y =>
y.AgreementType == AgreementType.Levy)));
}
[Test]
public async Task IfAnExpressionOfInterestAgreementAlreadyExistsThenAnExpressionOfInterestAgreementIsCreated()
{
EmployerAgreementRepository.Setup(x => x.GetAccountAgreements(AccountId)).ReturnsAsync(
new List<EmployerAgreement>
{
new EmployerAgreement { Template = new AgreementTemplate { AgreementType = AgreementType.NonLevyExpressionOfInterest } }
});
await CommandHandler.Handle(Command);
AccountRepository.Verify(x =>
x.CreateLegalEntityWithAgreement(It.Is<CreateLegalEntityWithAgreementParams>(y =>
y.AgreementType == AgreementType.NonLevyExpressionOfInterest)));
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using SFA.DAS.Common.Domain.Types;
using SFA.DAS.EmployerAccounts.Models.Account;
namespace SFA.DAS.EmployerAccounts.UnitTests.Commands.CreateLegalEntityCommandTests
{
public class WhenTheUserIsNotWhitelistedForExpressionOfInterest : CreateLegalEntityCommandTests
{
[SetUp]
public override void Arrange()
{
base.Arrange();
AuthorizationService.Setup(x => x.IsAuthorized("Feature.ExpressionOfInterest")).Returns(false);
}
[Test]
public async Task ThenAnExpressionOfInterestAgreementIsCreated()
{
var accountId = 12345;
HashingService.Setup(x => x.DecodeValue(Command.HashedAccountId)).Returns(accountId);
EmployerAgreementRepository.Setup(x => x.GetAccountAgreements(accountId)).ReturnsAsync(
new List<EmployerAgreement>
{
new EmployerAgreement { Template = new AgreementTemplate { AgreementType = AgreementType.Levy } }
});
await CommandHandler.Handle(Command);
AccountRepository.Verify(x =>
x.CreateLegalEntityWithAgreement(It.Is<CreateLegalEntityWithAgreementParams>(y =>
y.AgreementType == AgreementType.Levy)));
}
[Test]
public async Task IfAnExpressionOfInterestAgreementAlreadyExistsThenAnExpressionOfInterestAgreementIsCreated()
{
EmployerAgreementRepository.Setup(x => x.GetAccountAgreements(AccountId)).ReturnsAsync(
new List<EmployerAgreement>
{
new EmployerAgreement { Template = new AgreementTemplate { AgreementType = AgreementType.NonLevyExpressionOfInterest } }
});
await CommandHandler.Handle(Command);
AccountRepository.Verify(x =>
x.CreateLegalEntityWithAgreement(It.Is<CreateLegalEntityWithAgreementParams>(y =>
y.AgreementType == AgreementType.NonLevyExpressionOfInterest)));
}
}
}
|
mit
|
C#
|
3fb0eac8194fe4ef98b5feb3380a1ee77c7fb1f1
|
add additional Equation constructor for tests
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
|
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
|
using NBitcoin.Secp256k1;
using System.Linq;
using WalletWasabi.Crypto.Groups;
using WalletWasabi.Helpers;
namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation
{
// Each proof of a linear relation consists of multiple knowledge of
// representation equations, all sharing a single witness comprised of several
// secret scalars.
//
// Knowledge of representation means that given a curve point P, the prover
// knows how to construct P from a set of predetermined generators. This is
// commonly referred to as multi-exponentiation but that term implies
// multiplicative notation for the group operation. Written additively and
// indexing by `i`, each equation is of the form:
//
// P_i = x_1 * G_{i,1} + x_2 * G_{i,2} + ... + x_n * G_{i,n}
//
// Note that some of the generators for an equation can be the point at
// infinity when a term in the witness does not play a part in the
// representation of a specific point.
public class Equation
{
public Equation(GroupElement publicPoint, params GroupElement[] generators)
: this(publicPoint, new GroupElementVector(generators))
{
}
public Equation(GroupElement publicPoint, GroupElementVector generators)
{
Guard.NotNullOrEmpty(nameof(generators), generators);
PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint);
Generators = generators;
}
// Knowledge of representation asserts
// P = x_1*G_1 + x_2*G_2 + ...
// so we need a single public input and several generators
public GroupElement PublicPoint { get; }
public GroupElementVector Generators { get; }
// Evaluate the verification equation corresponding to the one in the statement
internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses)
{
// the verification equation (for 1 generator case) is:
// sG =? R + eP
// where:
// - R = kG is the public nonce, k is the secret nonce
// - P = xG is the public input, x is the secret
// - e is the challenge
// - s is the response
return responses * Generators == (publicNonce + challenge * PublicPoint);
}
// Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness
internal static ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge)
{
// By canceling G on both sides of the verification equation above we can
// obtain a formula for the response s given k, e and x:
// s = k + ex
return secretNonces + challenge * witness;
}
internal bool VerifySolution(ScalarVector witness)
{
return PublicPoint == witness * Generators;
}
}
}
|
using NBitcoin.Secp256k1;
using System.Linq;
using WalletWasabi.Crypto.Groups;
using WalletWasabi.Helpers;
namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation
{
// Each proof of a linear relation consists of multiple knowledge of
// representation equations, all sharing a single witness comprised of several
// secret scalars.
//
// Knowledge of representation means that given a curve point P, the prover
// knows how to construct P from a set of predetermined generators. This is
// commonly referred to as multi-exponentiation but that term implies
// multiplicative notation for the group operation. Written additively and
// indexing by `i`, each equation is of the form:
//
// P_i = x_1 * G_{i,1} + x_2 * G_{i,2} + ... + x_n * G_{i,n}
//
// Note that some of the generators for an equation can be the point at
// infinity when a term in the witness does not play a part in the
// representation of a specific point.
public class Equation
{
public Equation(GroupElement publicPoint, GroupElementVector generators)
{
Guard.NotNullOrEmpty(nameof(generators), generators);
PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint);
Generators = generators;
}
// Knowledge of representation asserts
// P = x_1*G_1 + x_2*G_2 + ...
// so we need a single public input and several generators
public GroupElement PublicPoint { get; }
public GroupElementVector Generators { get; }
// Evaluate the verification equation corresponding to the one in the statement
internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses)
{
// the verification equation (for 1 generator case) is:
// sG =? R + eP
// where:
// - R = kG is the public nonce, k is the secret nonce
// - P = xG is the public input, x is the secret
// - e is the challenge
// - s is the response
return responses * Generators == (publicNonce + challenge * PublicPoint);
}
// Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness
internal static ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge)
{
// By canceling G on both sides of the verification equation above we can
// obtain a formula for the response s given k, e and x:
// s = k + ex
return secretNonces + challenge * witness;
}
internal bool VerifySolution(ScalarVector witness)
{
return PublicPoint == witness * Generators;
}
}
}
|
mit
|
C#
|
915dcbccaae007a233602c18eb08076ecec12d90
|
Change tracing syntax
|
KpdApps/KpdApps.Common.MsCrm2015
|
BasePlugin.cs
|
BasePlugin.cs
|
using System;
using KpdApps.Common.MsCrm2015.Extensions;
using Microsoft.Xrm.Sdk;
namespace KpdApps.Common.MsCrm2015
{
public abstract class BasePlugin : IPlugin
{
public readonly string UnsecureConfiguration;
public readonly string SecureConfiguration;
/// <summary>
/// Constructor
/// </summary>
/// <param name="unsecureConfiguration"></param>
/// <param name="secureConfiguration"></param>
public BasePlugin(string unsecureConfiguration, string secureConfiguration)
{
UnsecureConfiguration = unsecureConfiguration;
SecureConfiguration = secureConfiguration;
}
/// <summary>
/// Constructor
/// </summary>
public BasePlugin()
{
}
public PluginState State { get; private set; }
public void Execute(IServiceProvider serviceProvider)
{
State = CreatePluginState(serviceProvider);
try
{
ExecuteInternal(State);
}
catch (Exception ex)
{
State?.TracingService.TraceError(ex);
throw;
}
}
public abstract void ExecuteInternal(PluginState state);
public virtual PluginState CreatePluginState(IServiceProvider serviceProvider)
{
return new PluginState(serviceProvider);
}
}
}
|
using System;
using KpdApps.Common.MsCrm2015.Extensions;
using Microsoft.Xrm.Sdk;
namespace KpdApps.Common.MsCrm2015
{
public abstract class BasePlugin : IPlugin
{
public readonly string UnsecureConfiguration;
public readonly string SecureConfiguration;
/// <summary>
/// Constructor
/// </summary>
/// <param name="unsecureConfiguration"></param>
/// <param name="secureConfiguration"></param>
public BasePlugin(string unsecureConfiguration, string secureConfiguration)
{
UnsecureConfiguration = unsecureConfiguration;
SecureConfiguration = secureConfiguration;
}
/// <summary>
/// Constructor
/// </summary>
public BasePlugin()
{
}
public void Execute(IServiceProvider serviceProvider)
{
PluginState state = CreatePluginState(serviceProvider);
try
{
ExecuteInternal(state);
}
catch (Exception ex)
{
state?.TraceError(ex);
throw;
}
}
public abstract void ExecuteInternal(PluginState state);
public virtual PluginState CreatePluginState(IServiceProvider serviceProvider)
{
return new PluginState(serviceProvider);
}
}
}
|
mit
|
C#
|
0dab70cc05be0711ba0f4efa6ebcf89f8ca9888b
|
Fix license header
|
NeoAdonis/osu,peppy/osu-new,smoogipooo/osu,ppy/osu,naoey/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu,2yangk23/osu,Frontear/osuKyzer,peppy/osu,ppy/osu,2yangk23/osu,ZLima12/osu,EVAST9919/osu,DrabWeb/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,naoey/osu,DrabWeb/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,ZLima12/osu,Nabile-Rahmani/osu,ppy/osu
|
osu.Game/Utils/ZipUtils.cs
|
osu.Game/Utils/ZipUtils.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using SharpCompress.Archives.Zip;
namespace osu.Game.Utils
{
public static class ZipUtils
{
public static bool IsZipArchive(string path)
{
try
{
using (var arc = ZipArchive.Open(path))
{
foreach (var entry in arc.Entries)
{
using (entry.OpenEntryStream())
{
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using SharpCompress.Archives.Zip;
namespace osu.Game.Utils
{
public static class ZipUtils
{
public static bool IsZipArchive(string path)
{
try
{
using (var arc = ZipArchive.Open(path))
{
foreach (var entry in arc.Entries)
{
using (entry.OpenEntryStream())
{
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
|
mit
|
C#
|
ffde389641a15f0b0faceb8e1e900fa186509bda
|
Add difficulty calculator beatmap decoder fallback
|
NeoAdonis/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu-new,2yangk23/osu,ppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,ZLima12/osu,ZLima12/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,johnneijzen/osu
|
osu.Game/Beatmaps/Formats/LegacyDifficultyCalculatorBeatmapDecoder.cs
|
osu.Game/Beatmaps/Formats/LegacyDifficultyCalculatorBeatmapDecoder.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.Linq;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Formats
{
/// <summary>
/// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
/// <remarks>
/// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
/// Doing so will override any existing <see cref="Beatmap"/> decoders.
/// </remarks>
/// </summary>
public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
{
public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
: base(version)
{
ApplyOffsets = false;
}
public new static void Register()
{
AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder());
}
protected override TimingControlPoint CreateTimingControlPoint()
=> new LegacyDifficultyCalculatorControlPoint();
private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint
{
public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH;
}
}
}
|
// 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.Linq;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Beatmaps.Formats
{
/// <summary>
/// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s
/// <remarks>
/// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>.
/// Doing so will override any existing <see cref="Beatmap"/> decoders.
/// </remarks>
/// </summary>
public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder
{
public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION)
: base(version)
{
ApplyOffsets = false;
}
public new static void Register()
{
AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last())));
}
protected override TimingControlPoint CreateTimingControlPoint()
=> new LegacyDifficultyCalculatorControlPoint();
private class LegacyDifficultyCalculatorControlPoint : TimingControlPoint
{
public override double BeatLength { get; set; } = DEFAULT_BEAT_LENGTH;
}
}
}
|
mit
|
C#
|
9607e0e55d0a9c08fa655ddc53127b39d5742bdf
|
Update PayButtonEnable.cshtml (#1952)
|
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
|
BTCPayServer/Views/Stores/PayButtonEnable.cshtml
|
BTCPayServer/Views/Stores/PayButtonEnable.cshtml
|
@{
Layout = "../Shared/_NavLayout.cshtml";
ViewData.SetActivePageAndTitle(StoreNavPages.PayButton, "Pay Button");
}
<div class="row">
<div class="col-md-10">
<form method="post">
<div class="form-group">
<p>
To start using Pay Buttons you need to explicitly turn on this feature.
Once you do so, any 3rd party entity will be able to create an invoice on your instance store (via API for example).
The POS app is preauthorised and does not need this enabled.
</p>
@Html.Hidden("EnableStore", true)
<button name="command" type="submit" value="save" class="btn btn-lg btn-primary px-4">
Allow outside world to create invoices via API
</button>
</div>
</form>
</div>
</div>
|
@{
Layout = "../Shared/_NavLayout.cshtml";
ViewData.SetActivePageAndTitle(StoreNavPages.PayButton, "Please confirm you want to allow outside world to create invoices in your store (via API).");
ViewBag.MainTitle = "Pay Button";
}
<div class="row">
<div class="col-md-10">
<form method="post">
<div class="form-group">
<p>
To start using Pay Buttons you need to explicitly turn on this feature.
Once you do so, any 3rd party entity will be able to create an invoice on your instance store (via API for example).
The POS app is preauthorised and does not need this enabled.
</p>
@Html.Hidden("EnableStore", true)
<button name="command" type="submit" value="save" class="btn btn-lg btn-primary px-4">
Allow outside world to create invoices via API
</button>
</div>
</form>
</div>
</div>
|
mit
|
C#
|
2f5d3f62e9e091e752b8eb974b4175639f4ffca5
|
Add list display for veh attributes
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Views/Vehicles/List.cshtml
|
Battery-Commander.Web/Views/Vehicles/List.cshtml
|
@model IEnumerable<Vehicle>
@{
ViewBag.Title = "Vehicle Tracker";
}
<div class="page-header">
<h1>@ViewBag.Title <span class="badge">@Model.Count()</span> @Html.ActionLink("Add New", "New", "Vehicles", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped" id="dt">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Bumper)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Seats)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Nomenclature)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Registration)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Serial)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Notes)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var vehicle in Model)
{
<tr>
<td>@Html.DisplayFor(_ => vehicle.Unit)</td>
<td>@Html.DisplayFor(_ => vehicle.Bumper)</td>
<td>@Html.DisplayFor(_ => vehicle.Type)</td>
<td>@Html.DisplayFor(_ => vehicle.Status)</td>
<td>@Html.DisplayFor(_ => vehicle.Seats)</td>
<td>@Html.DisplayFor(_ => vehicle.Nomenclature)</td>
<td>@Html.DisplayFor(_ => vehicle.Registration)</td>
<td>@Html.DisplayFor(_ => vehicle.Serial)</td>
<td>@Html.DisplayFor(_ => vehicle.Notes)</td>
<td>@Html.ActionLink("Edit", "Edit", new { vehicle.Id })
</tr>
}
</tbody>
</table>
|
@model IEnumerable<Vehicle>
@{
ViewBag.Title = "Vehicle Tracker";
}
<div class="page-header">
<h1>@ViewBag.Title <span class="badge">@Model.Count()</span> @Html.ActionLink("Add New", "New", "Vehicles", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped" id="dt">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Bumper)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Seats)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var vehicle in Model)
{
<tr>
<td>@Html.DisplayFor(_ => vehicle.Bumper)</td>
<td>@Html.DisplayFor(_ => vehicle.Type)</td>
<td>@Html.DisplayFor(_ => vehicle.Status)</td>
<td>@Html.DisplayFor(_ => vehicle.Seats)</td>
<td>@Html.DisplayFor(_ => vehicle.Unit)</td>
<td>@Html.ActionLink("Edit", "Edit", new { vehicle.Id })
</tr>
}
</tbody>
</table>
|
mit
|
C#
|
6cc6f5e7c8a8cf9dd79f89c4413d50c71a63e486
|
Optimize hash
|
StevenThuriot/Horizon
|
TypeHash.cs
|
TypeHash.cs
|
#region License
//
// Copyright 2015 Steven Thuriot
//
// 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;
using System.Linq;
namespace Invocation
{
struct TypeHash
{
private readonly Type[] _types;
private readonly Lazy<int> _hashCode;
public TypeHash(IEnumerable<Type> types)
{
var typeArray = _types = types.ToArray();
_hashCode = new Lazy<int>(() => unchecked(typeArray.Aggregate(17, (current, element) => current*31 + element.GetHashCode())));
}
public IReadOnlyList<Type> Types
{
get { return _types; }
}
public bool Equals(TypeHash other)
{
return _types.SequenceEqual(other._types);
}
public override bool Equals(object obj)
{
return obj is TypeHash && Equals((TypeHash) obj);
}
public static bool operator ==(TypeHash left, TypeHash right)
{
return Equals(left, right);
}
public static bool operator !=(TypeHash left, TypeHash right)
{
return !Equals(left, right);
}
public override int GetHashCode()
{
return _hashCode.Value;
}
}
}
|
#region License
//
// Copyright 2015 Steven Thuriot
//
// 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;
using System.Linq;
namespace Invocation
{
struct TypeHash
{
private readonly Type[] _types;
public TypeHash(IEnumerable<Type> types)
{
_types = types.ToArray();
}
public IReadOnlyList<Type> Types
{
get { return _types; }
}
public bool Equals(TypeHash other)
{
//if (_types == null)
// return other._types == null;
//if (other._types == null)
// return false;
return _types.SequenceEqual(other._types);
}
public override bool Equals(object obj)
{
//if (ReferenceEquals(null, obj)) return false;
return obj is TypeHash && Equals((TypeHash) obj);
}
public static bool operator ==(TypeHash left, TypeHash right)
{
return Equals(left, right);
}
public static bool operator !=(TypeHash left, TypeHash right)
{
return !Equals(left, right);
}
public override int GetHashCode()
{
unchecked
{
//if (_types == null)
// return 0;
var elementComparer = EqualityComparer<Type>.Default;
return _types.Aggregate(17, (current, element) => current*31 + elementComparer.GetHashCode(element));
}
}
}
}
|
mit
|
C#
|
a46f82d4d2a09325258d13b6b20c08be6a4759c2
|
Fix typo in HomeController namespace (#9327)
|
stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2
|
src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Module/Controllers/HomeController.cs
|
src/Templates/OrchardCore.ProjectTemplates/content/OrchardCore.Templates.Mvc.Module/Controllers/HomeController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace OrchardCore.Templates.Mvc.Module.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Module1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
|
bsd-3-clause
|
C#
|
53c254c6a5ca0b59f1471a670beaf81d083f0450
|
Replace Array.IndexOf() with Contains()
|
UselessToucan/osu,johnneijzen/osu,ppy/osu,ZLima12/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,johnneijzen/osu,NeoAdonis/osu,smoogipooo/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,ppy/osu
|
osu.Game/Graphics/UserInterface/HoverClickSounds.cs
|
osu.Game/Graphics/UserInterface/HoverClickSounds.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.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Input.Events;
using osuTK.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover and click sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverClickSounds : HoverSounds
{
private SampleChannel sampleClick;
private readonly MouseButton[] buttons;
/// <summary>
/// Creates an instance that adds sounds on hover and on click for any of the buttons specified.
/// </summary>
/// <param name="sampleSet">Set of click samples to play.</param>
/// <param name="buttons">
/// Array of button codes which should trigger the click sound.
/// If this optional parameter is omitted or set to <code>null</code>, the click sound will only be added on left click.
/// </param>
public HoverClickSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal, MouseButton[] buttons = null)
: base(sampleSet)
{
this.buttons = buttons ?? new[] { MouseButton.Left };
}
protected override bool OnMouseUp(MouseUpEvent e)
{
bool shouldPlayEffect = buttons.Contains(e.Button);
// examine the button pressed first for short-circuiting
// in most usages it is more likely that another button was pressed than that the cursor left the drawable bounds
if (shouldPlayEffect && Contains(e.ScreenSpaceMousePosition))
sampleClick?.Play();
return base.OnMouseUp(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Samples.Get($@"UI/generic-select{SampleSet.GetDescription()}");
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Input.Events;
using osuTK.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover and click sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverClickSounds : HoverSounds
{
private SampleChannel sampleClick;
private readonly MouseButton[] buttons;
/// <summary>
/// Creates an instance that adds sounds on hover and on click for any of the buttons specified.
/// </summary>
/// <param name="sampleSet">Set of click samples to play.</param>
/// <param name="buttons">
/// Array of button codes which should trigger the click sound.
/// If this optional parameter is omitted or set to <code>null</code>, the click sound will only be added on left click.
/// </param>
public HoverClickSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal, MouseButton[] buttons = null)
: base(sampleSet)
{
this.buttons = buttons ?? new[] { MouseButton.Left };
}
protected override bool OnMouseUp(MouseUpEvent e)
{
var index = Array.IndexOf(buttons, e.Button);
bool shouldPlayEffect = index > -1 && index < buttons.Length;
// examine the button pressed first for short-circuiting
// in most usages it is more likely that another button was pressed than that the cursor left the drawable bounds
if (shouldPlayEffect && Contains(e.ScreenSpaceMousePosition))
sampleClick?.Play();
return base.OnMouseUp(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Samples.Get($@"UI/generic-select{SampleSet.GetDescription()}");
}
}
}
|
mit
|
C#
|
87e88f9fffca78c8a99410dc85174ba5c1c1b49f
|
Add broken test to testproj
|
JetBrains/teamcity-dotmemory,JetBrains/teamcity-dotmemory
|
testproj/UnitTest1.cs
|
testproj/UnitTest1.cs
|
namespace testproj
{
using System;
using System.Collections.Generic;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var strs = new List<string>();
var memoryCheckPoint = dotMemory.Check();
strs.Add(GenStr());
strs.Add(GenStr());
strs.Add(GenStr());
dotMemory.Check(
memory =>
{
var strCount = memory
.GetDifference(memoryCheckPoint)
.GetNewObjects()
.GetObjects(i => i.Type == typeof(string))
.ObjectsCount;
Assert.LessOrEqual(strCount, 2);
});
strs.Clear();
}
[Test]
public void TestMethod2()
{
var strs = new List<string>();
var memoryCheckPoint = dotMemory.Check();
strs.Add(GenStr());
strs.Add(GenStr());
dotMemory.Check(
memory =>
{
var strCount = memory
.GetDifference(memoryCheckPoint)
.GetNewObjects()
.GetObjects(i => i.Type == typeof(string))
.ObjectsCount;
Assert.LessOrEqual(strCount, 2);
});
strs.Clear();
}
private static string GenStr()
{
return Guid.NewGuid().ToString();
}
}
}
|
namespace testproj
{
using System;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
var str1 = "1";
var str2 = "2";
var str3 = "3";
Assert.LessOrEqual(2, memory.ObjectsCount);
Console.WriteLine(str1 + str2 + str3);
});
}
}
}
|
apache-2.0
|
C#
|
7e27baee152d2ffe18562b4d33b26cb6d8d2107a
|
Enable PersonaBar tests
|
valadas/Dnn.Platform,nvisionative/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,valadas/Dnn.Platform
|
Build/Cake/unit-tests.cs
|
Build/Cake/unit-tests.cs
|
using Cake.Common.IO;
using Cake.Common.Tools.MSBuild;
using Cake.Common.Tools.VSTest;
using Cake.Common.Tools.VSWhere;
using Cake.Common.Tools.VSWhere.Latest;
using Cake.Core.Diagnostics;
using Cake.Frosting;
/// <summary>
/// Runs units tests on solution. Make sure to build the solution before running this task.
/// </summary>
public sealed class UnitTests : FrostingTask<Context>
{
public override void Run(Context context)
{
var testAssemblies = context.GetFiles($@"**\bin\{context.configuration}\DotNetNuke.Tests.*.dll");
testAssemblies += context.GetFiles($@"**\bin\{context.configuration}\Dnn.PersonaBar.*.Tests.dll");
testAssemblies -= context.GetFiles(@"**\DotNetNuke.Tests.Utilities.dll");
// TODO: address issues to allow these tests to run
testAssemblies -= context.GetFiles(@"**\DotNetNuke.Tests.Integration.dll");
testAssemblies -= context.GetFiles(@"**\DotNetNuke.Tests.Urls.dll");
foreach (var file in testAssemblies)
{
context.VSTest(file.FullPath,
FixToolPath(context, new VSTestSettings()
{
Logger = $"trx;LogFileName={file.GetFilename()}.xml",
Parallel = true,
EnableCodeCoverage = true,
FrameworkVersion = VSTestFrameworkVersion.NET45,
TestAdapterPath = @"tools\NUnitTestAdapter.2.3.0\build"
}));
}
}
// https://github.com/cake-build/cake/issues/1522
VSTestSettings FixToolPath(Context context, VSTestSettings settings)
{
// #tool vswhere
settings.ToolPath =
context.VSWhereLatest(new VSWhereLatestSettings {Requires = "Microsoft.VisualStudio.PackageGroup.TestTools.Core"})
.CombineWithFilePath(context.File(@"Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"));
return settings;
}
}
|
using Cake.Common.IO;
using Cake.Common.Tools.MSBuild;
using Cake.Common.Tools.VSTest;
using Cake.Common.Tools.VSWhere;
using Cake.Common.Tools.VSWhere.Latest;
using Cake.Core.Diagnostics;
using Cake.Frosting;
/// <summary>
/// Runs units tests on solution. Make sure to build the solution before running this task.
/// </summary>
public sealed class UnitTests : FrostingTask<Context>
{
public override void Run(Context context)
{
var testAssemblies = context.GetFiles($@"**\bin\{context.configuration}\DotNetNuke.Tests.*.dll");
testAssemblies -= context.GetFiles(@"**\DotNetNuke.Tests.Integration.dll");
testAssemblies -= context.GetFiles(@"**\DotNetNuke.Tests.Utilities.dll");
testAssemblies -= context.GetFiles(@"**\DotNetNuke.Tests.Urls.dll");
foreach (var file in testAssemblies)
{
context.VSTest(file.FullPath,
FixToolPath(context, new VSTestSettings()
{
Logger = $"trx;LogFileName={file.GetFilename()}.xml",
Parallel = true,
EnableCodeCoverage = true,
FrameworkVersion = VSTestFrameworkVersion.NET45,
TestAdapterPath = @"tools\NUnitTestAdapter.2.3.0\build"
}));
}
}
// https://github.com/cake-build/cake/issues/1522
VSTestSettings FixToolPath(Context context, VSTestSettings settings)
{
// #tool vswhere
settings.ToolPath =
context.VSWhereLatest(new VSWhereLatestSettings {Requires = "Microsoft.VisualStudio.PackageGroup.TestTools.Core"})
.CombineWithFilePath(context.File(@"Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"));
return settings;
}
}
|
mit
|
C#
|
f25a735fc9a08f7450fa259abb68ee150324f971
|
Split TriangleTest method into multiple methods.
|
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
|
ChamberLibTests/TriangleTest.cs
|
ChamberLibTests/TriangleTest.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ChamberLib;
namespace ChamberLibTests
{
[TestFixture]
public class TriangleTest
{
[Test]
public void TriangleIntersectsRay1()
{
// when
var triangle = new Triangle(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
var ray = new Ray(Vector3.Zero, new Vector3(1, 1, 1).Normalized());
// expect
Assert.True(triangle.Intersects(ray));
}
[Test]
public void TriangleIntersectsRay2()
{
// given
var triangle = new Triangle(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
var n111 = new Vector3(1,1,1).Normalized();
var ray = new Ray(n111, n111);
// expect
Assert.True(triangle.Intersects(ray));
}
[Test]
public void TriangleIntersectsRay3()
{
// given
var triangle = new Triangle(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
var n111 = new Vector3(1, 1, 1).Normalized();
var ray = new Ray(new Vector3(1, 1, 1), n111);
// expect
Assert.False(triangle.Intersects(ray));
}
[Test]
public void TriangleIntersectsRay4()
{
// given
var triangle = new Triangle(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
var ray = new Ray(Vector3.Zero, Vector3.UnitX);
// expect
Assert.IsTrue(triangle.Intersects(ray));
}
[Test]
public void TriangleIntersectsRay5()
{
// given
var triangle = new Triangle(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
var ray = new Ray(Vector3.Zero, Vector3.UnitY);
// expect
Assert.IsTrue(triangle.Intersects(ray));
}
[Test]
public void TriangleIntersectsRay6()
{
// given
var triangle = new Triangle(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
var ray = new Ray(Vector3.Zero, Vector3.UnitZ);
// expect
Assert.IsTrue(triangle.Intersects(ray));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ChamberLib;
namespace ChamberLibTests
{
[TestFixture]
public class TriangleTest
{
[Test]
public void TriangleIntersectsRay()
{
// given
Triangle triangle;
Ray ray;
// when
triangle = new Triangle(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
ray = new Ray(Vector3.Zero, new Vector3(1, 1, 1).Normalized());
// then
Assert.True(triangle.Intersects(ray));
// when
var n111 = new Vector3(1,1,1).Normalized();
ray = new Ray(n111, n111);
// then
Assert.True(triangle.Intersects(ray));
// when
ray = new Ray(new Vector3(1, 1, 1), n111);
// then
Assert.False(triangle.Intersects(ray));
// when
ray = new Ray(Vector3.Zero, Vector3.UnitX);
// then
Assert.IsTrue(triangle.Intersects(ray));
// when
ray = new Ray(Vector3.Zero, Vector3.UnitY);
// then
Assert.IsTrue(triangle.Intersects(ray));
// when
ray = new Ray(Vector3.Zero, Vector3.UnitZ);
// then
Assert.IsTrue(triangle.Intersects(ray));
}
}
}
|
lgpl-2.1
|
C#
|
c204053c3361a14274e6705d316803359cf95968
|
Update HeightMapGenerator.cs
|
Domiii/UnityLoopyLoops
|
Assets/Scripts/HeightMapGenerator.cs
|
Assets/Scripts/HeightMapGenerator.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeightMapGenerator : MonoBehaviour {
// 兩個地形,這個數值如果是一樣的話,會看到的樣子也是一樣的
public int seed = 1;
// length或長度或解析度,也就是 x 與 z 緯度有幾個格子
public int length = 65;
// 最高的高度
public float height = 50;
// 頻率
public float frequency = 2f;
public float[] layers = new float[] { 2, 4, 8, 16 };
void Reset () {
RandomizeSeed ();
Clear ();
}
public void Generate () {
// 首先清掉~
Clear();
// 取得地形的資料
var terrain = GetComponent<Terrain> ();
var terrainData = terrain.terrainData;
// 我們用 heightMap 來存 length x length 個高度
var heightMap = new float[length, length];
// 開始算 length x length 個高度
for (int x = 0; x < length; x++) {
for (int z = 0; z < length; z++) {
float worldX = transform.position.x + x;
float worldZ = transform.position.z + z;
heightMap [z, x] = GenerateHeight (worldX/length, worldZ/length);
}
}
terrainData.SetHeights (0, 0, heightMap);
}
/// <summary>
/// Generates the height at fractions of x and z.
/// For any generated patch:
/// The smallest and biggest values of xFraction should ideally have a distance of 1, and not more than 1
/// Same goes for z.
/// Example: If you want to create terrain from real-world coordinates x_min = 1 to x_max = 11,
/// then let length = x_max - x_min = 10, and thus xFrac_min = x_min/length = 0.1 and xFrac_max = x_max/length = 1.1
/// </summary>
float GenerateHeight (float xFraction, float zFraction) {
var h = 0.0f;
for (int i = 0; i < layers.Length; i++) {
var gain = layers [i];
h += Mathf.PerlinNoise (seed + xFraction * gain * frequency, seed + zFraction * gain * frequency) * 1 / gain;
}
return h;
}
public void Clear () {
// sanity checks!
if (!Mathf.IsPowerOfTwo (length - 1)) {
print("Height map size must equal: 1 + (a power of 2) - e.g. 33, 65, 127, 255, 511 etc.");
length = Mathf.ClosestPowerOfTwo (length) + 1;
}
var terrainData = GetComponent<Terrain>().terrainData;
terrainData.size = new Vector3 (length, height, length);
terrainData.heightmapResolution = length;
}
public void RandomizeSeed () {
seed = Random.Range (1, (int)1e5);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeightMapGenerator : MonoBehaviour {
// 兩個地形,這個數值如果是一樣的話,會看到的樣子也是一樣的
public int seed = 1;
// length或長度或解析度,也就是 x 與 z 緯度有幾個格子
public int length = 65;
// 最高的高度
public float height = 50;
// 頻率
public float frequency = 2f;
public float[] layers = new float[] { 2, 4, 8, 16 };
void Reset () {
RandomizeSeed ();
Clear ();
}
public void Generate () {
// 首先清掉~
Clear();
// 取得地形的資料
var terrain = GetComponent<Terrain> ();
var terrainData = terrain.terrainData;
// 我們用 heightMap 來存 length x length 個高度
var heightMap = new float[length, length];
// 開始算 length x length 個高度
for (int x = 0; x < length; x++) {
for (int z = 0; z < length; z++) {
float worldX = transform.position.x + x;
float worldZ = transform.position.z + z;
heightMap [z, x] = GenerateHeight (worldX/length, worldZ/length);
}
}
terrainData.SetHeights (0, 0, heightMap);
}
/// <summary>
/// Generates the height at fractions of x and z.
/// "Normalized" in this case means: That the smallest and biggest values of x should ideally have a distance of 1, and not more than 1
/// Same goes for z.
/// Example: If you want to create terrain from real-world coordinates x=1 to x=10, then you want to normalize in such a way that x=1 becomes 0 and
/// </summary>
float GenerateHeight (float xFraction, float zFraction) {
var h = 0.0f;
for (int i = 0; i < layers.Length; i++) {
var gain = layers [i];
h += Mathf.PerlinNoise (seed + xFraction * gain * frequency, seed + zFraction * gain * frequency) * 1 / gain;
}
return h;
}
public void Clear () {
// sanity checks!
if (!Mathf.IsPowerOfTwo (length - 1)) {
print("Height map size must equal: 1 + (a power of 2) - e.g. 33, 65, 127, 255, 511 etc.");
length = Mathf.ClosestPowerOfTwo (length) + 1;
}
var terrainData = GetComponent<Terrain>().terrainData;
terrainData.size = new Vector3 (length, height, length);
terrainData.heightmapResolution = length;
}
public void RandomizeSeed () {
seed = Random.Range (1, (int)1e5);
}
}
|
mit
|
C#
|
358b8cc2ddcb8829b61ff8b0c7c5419d7178b7b9
|
Fix the player score counter (IsFaking always returned true)
|
Nagasaki45/UnsocialVR,Nagasaki45/UnsocialVR
|
Assets/Scripts/Player/PlayerState.cs
|
Assets/Scripts/Player/PlayerState.cs
|
using System;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerState : NetworkBehaviour {
[SyncVar]
string fakingTheory;
[SyncVar]
int score;
void Start()
{
fakingTheory = null;
score = 0;
}
[Command]
public void CmdSetFakingState(string newFakingTheory)
{
fakingTheory = newFakingTheory;
}
[Command]
public void CmdAddScore(int value)
{
score += value;
}
public bool IsFaking()
{
return !String.IsNullOrEmpty(fakingTheory);
}
void OnGUI()
{
if (!isLocalPlayer)
{
return;
}
GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200));
GUILayout.Label("Score: " + score);
if (IsFaking())
{
GUILayout.Label("Faking using " + fakingTheory);
}
GUI.EndGroup();
}
}
|
using UnityEngine;
using UnityEngine.Networking;
public class PlayerState : NetworkBehaviour {
[SyncVar]
string fakingTheory;
[SyncVar]
int score;
void Start()
{
fakingTheory = null;
score = 0;
}
[Command]
public void CmdSetFakingState(string newFakingTheory)
{
fakingTheory = newFakingTheory;
}
[Command]
public void CmdAddScore(int value)
{
score += value;
}
public bool IsFaking()
{
return (fakingTheory != null);
}
void OnGUI()
{
if (!isLocalPlayer)
{
return;
}
GUI.BeginGroup(new Rect(Screen.width / 2 - 100, Screen.height - 100, 200, 200));
GUILayout.Label("Score: " + score);
if (IsFaking())
{
GUILayout.Label("Faking using " + fakingTheory);
}
GUI.EndGroup();
}
}
|
mit
|
C#
|
f9592ea939ed0e04eec9b66aabaeb388010a36af
|
cover events edgecase
|
Pondidum/Ledger,Pondidum/Ledger
|
Ledger.Stores.Postgres.Tests/EventSaveLoadTests.cs
|
Ledger.Stores.Postgres.Tests/EventSaveLoadTests.cs
|
using System;
using System.Linq;
using Shouldly;
using TestsDomain.Events;
using Xunit;
namespace Ledger.Stores.Postgres.Tests
{
public class EventSaveLoadTests : PostgresTestBase
{
public EventSaveLoadTests()
{
CleanupTables();
var create = new CreateGuidKeyedTablesCommand(ConnectionString);
create.Execute();
}
[Fact]
public void Events_should_keep_types_and_be_ordered()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll {SequenceID = 0, NewName = "Deed"},
new FixNameSpelling {SequenceID = 1, NewName = "Fix"},
};
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(id, toSave);
var loaded = store.LoadEvents(id);
loaded.First().ShouldBeOfType<NameChangedByDeedPoll>();
loaded.Last().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_events_for_the_correct_aggregate_are_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(first, new[] { new FixNameSpelling { NewName = "Fix" } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { NewName = "Deed" } });
var loaded = store.LoadEvents(first);
loaded.Single().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_the_latest_sequence_is_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 4 } });
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 5 } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { SequenceID = 6 } });
store
.GetLatestSequenceFor(first)
.ShouldBe(5);
}
[Fact]
public void Loading_events_since_only_gets_events_after_the_sequence()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll { SequenceID = 3 },
new FixNameSpelling { SequenceID = 4 },
new FixNameSpelling { SequenceID = 5 },
new FixNameSpelling { SequenceID = 6 },
};
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(id, toSave);
var loaded = store.LoadEventsSince(id, 4);
loaded.Select(x => x.SequenceID).ShouldBe(new[] { 5, 6 });
}
[Fact]
public void When_there_are_no_events_and_load_is_called()
{
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
var loaded = store.LoadEventsSince(id, 4);
loaded.ShouldBeEmpty();
}
}
}
|
using System;
using System.Linq;
using Shouldly;
using TestsDomain.Events;
using Xunit;
namespace Ledger.Stores.Postgres.Tests
{
public class EventSaveLoadTests : PostgresTestBase
{
public EventSaveLoadTests()
{
CleanupTables();
var create = new CreateGuidKeyedTablesCommand(ConnectionString);
create.Execute();
}
[Fact]
public void Events_should_keep_types_and_be_ordered()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll {SequenceID = 0, NewName = "Deed"},
new FixNameSpelling {SequenceID = 1, NewName = "Fix"},
};
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(id, toSave);
var loaded = store.LoadEvents(id);
loaded.First().ShouldBeOfType<NameChangedByDeedPoll>();
loaded.Last().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_events_for_the_correct_aggregate_are_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(first, new[] { new FixNameSpelling { NewName = "Fix" } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { NewName = "Deed" } });
var loaded = store.LoadEvents(first);
loaded.Single().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_the_latest_sequence_is_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 4 } });
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 5 } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { SequenceID = 6 } });
store
.GetLatestSequenceFor(first)
.ShouldBe(5);
}
[Fact]
public void Loading_events_since_only_gets_events_after_the_sequence()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll { SequenceID = 3 },
new FixNameSpelling { SequenceID = 4 },
new FixNameSpelling { SequenceID = 5 },
new FixNameSpelling { SequenceID = 6 },
};
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(id, toSave);
var loaded = store.LoadEventsSince(id, 4);
loaded.Select(x => x.SequenceID).ShouldBe(new[] { 5, 6 });
}
}
}
|
lgpl-2.1
|
C#
|
f5e918707e4b12ac6ca1838d0d8e6e60801abc42
|
Add conditions to background tasks
|
Odonno/Modern-Gitter
|
Gitter/Gitter/Gitter.Shared/Services/Concrete/BackgroundTaskService.cs
|
Gitter/Gitter/Gitter.Shared/Services/Concrete/BackgroundTaskService.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Gitter.Services.Abstract;
namespace Gitter.Services.Concrete
{
public class BackgroundTaskService : IBackgroundTaskService
{
public Dictionary<string, string> Tasks
{
get
{
return new Dictionary<string, string>
{
{"NotificationsBackgroundTask", "Gitter.Tasks"}
};
}
}
public async Task RegisterTasksAsync()
{
foreach (var kvTask in Tasks)
{
if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key))
break;
await RegisterTaskAsync(kvTask.Key, kvTask.Value);
}
}
private async Task RegisterTaskAsync(string taskName, string taskNamespace)
{
var requestAccess = await BackgroundExecutionManager.RequestAccessAsync();
if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity ||
requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
{
var taskBuilder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName)
};
// Set the condition trigger that feels right for you
taskBuilder.SetTrigger(new TimeTrigger(15, false));
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent));
taskBuilder.Register();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Gitter.Services.Abstract;
namespace Gitter.Services.Concrete
{
public class BackgroundTaskService : IBackgroundTaskService
{
public Dictionary<string, string> Tasks
{
get
{
return new Dictionary<string, string>
{
{"NotificationsBackgroundTask", "Gitter.Tasks"}
};
}
}
public async Task RegisterTasksAsync()
{
foreach (var kvTask in Tasks)
{
if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == kvTask.Key))
break;
await RegisterTaskAsync(kvTask.Key, kvTask.Value);
}
}
private async Task RegisterTaskAsync(string taskName, string taskNamespace)
{
var requestAccess = await BackgroundExecutionManager.RequestAccessAsync();
if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity ||
requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
{
var taskBuilder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName)
};
// Set the condition trigger that feels right for you
taskBuilder.SetTrigger(new TimeTrigger(15, false));
taskBuilder.Register();
}
}
}
}
|
apache-2.0
|
C#
|
1063474b0e5f6f00a217aa3b26c3536589c49c47
|
Add option to mark exceptions as observed
|
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
|
Mindscape.Raygun4Net.Xamarin.iOS/RaygunSettings.cs
|
Mindscape.Raygun4Net.Xamarin.iOS/RaygunSettings.cs
|
using System;
namespace Mindscape.Raygun4Net
{
public class RaygunSettings
{
private static RaygunSettings settings;
private const string DefaultApiEndPoint = "https://api.raygun.io/entries";
private const string DefaultPulseEndPoint = "https://api.raygun.io/events";
public static RaygunSettings Settings
{
get
{
return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) });
}
}
public Uri ApiEndpoint { get; set; }
public Uri PulseEndpoint{ get; set; }
public bool SetUnobservedTaskExceptionsAsObserved { get; set; }
}
}
|
using System;
namespace Mindscape.Raygun4Net
{
public class RaygunSettings
{
private static RaygunSettings settings;
private const string DefaultApiEndPoint = "https://api.raygun.io/entries";
private const string DefaultPulseEndPoint = "https://api.raygun.io/events";
public static RaygunSettings Settings
{
get
{
return settings ?? (settings = new RaygunSettings { ApiEndpoint = new Uri(DefaultApiEndPoint), PulseEndpoint = new Uri(DefaultPulseEndPoint) });
}
}
public Uri ApiEndpoint { get; set; }
public Uri PulseEndpoint{ get; set; }
}
}
|
mit
|
C#
|
92ef60644437cd237d12009b55772887d5e0b423
|
fix nullable warning
|
NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,campersau/NuGetPackageExplorer
|
PackageViewModel/PackageSearch/PackageListCache.cs
|
PackageViewModel/PackageSearch/PackageListCache.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using NuGet.Protocol.Core.Types;
namespace PackageExplorerViewModel.PackageSearch
{
internal class PackageListCache<T> where T : IPackageSearchMetadata
{
private readonly Dictionary<string, List<T>> _packagesDict = new Dictionary<string, List<T>>(StringComparer.OrdinalIgnoreCase);
public void SetPackages(string packageSource, List<T> packages)
{
_packagesDict[packageSource] = packages;
}
public bool TryGetPackages(string packageSource, [NotNullWhen(true)] out List<T>? packages)
{
return _packagesDict.TryGetValue(packageSource, out packages);
}
}
}
|
using System;
using System.Collections.Generic;
using NuGet.Protocol.Core.Types;
namespace PackageExplorerViewModel.PackageSearch
{
internal class PackageListCache<T> where T : IPackageSearchMetadata
{
private readonly Dictionary<string, List<T>> _packagesDict = new Dictionary<string, List<T>>(StringComparer.OrdinalIgnoreCase);
public void SetPackages(string packageSource, List<T> packages)
{
_packagesDict[packageSource] = packages;
}
public bool TryGetPackages(string packageSource, out List<T> packages)
{
return _packagesDict.TryGetValue(packageSource, out packages);
}
}
}
|
mit
|
C#
|
2e96740ac27e3e36155920eb4c0bb3aa15e46d21
|
Put in some debugging code for looking at what functions have been added to the rooted event handler.
|
MatterHackers/agg-sharp,LayoutFarm/PixelFarm,mmoening/agg-sharp,mmoening/agg-sharp,jlewin/agg-sharp,mmoening/agg-sharp,larsbrubaker/agg-sharp
|
Gui/RootedObjectEventHandler.cs
|
Gui/RootedObjectEventHandler.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatterHackers.Agg.UI
{
public class RootedObjectEventHandler
{
#if DEBUG
private event EventHandler InternalEventForDebug;
private List<EventHandler> DebugEventDelegates = new List<EventHandler>();
private event EventHandler InternalEvent
{
//Wraps the PrivateClick event delegate so that we can track which events have been added and clear them if necessary
add
{
InternalEventForDebug += value;
DebugEventDelegates.Add(value);
}
remove
{
InternalEventForDebug -= value;
DebugEventDelegates.Remove(value);
}
}
#else
EventHandler InternalEvent;
#endif
public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent += functionToCallOnEvent;
functionThatWillBeCalledToUnregisterEvent += (sender, e) =>
{
InternalEvent -= functionToCallOnEvent;
};
}
public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent -= functionToCallOnEvent;
// After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent
// But it is valid to attempt remove more than once.
}
public void CallEvents(Object sender, EventArgs e)
{
#if DEBUG
if (InternalEventForDebug != null)
{
InternalEventForDebug(this, e);
}
#else
if (InternalEvent != null)
{
InternalEvent(this, e);
}
#endif
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatterHackers.Agg.UI
{
public class RootedObjectEventHandler
{
EventHandler InternalEvent;
public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent += functionToCallOnEvent;
functionThatWillBeCalledToUnregisterEvent += (sender, e) =>
{
InternalEvent -= functionToCallOnEvent;
};
}
public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent)
{
InternalEvent -= functionToCallOnEvent;
// After we remove it it will still be removed again in the functionThatWillBeCalledToUnregisterEvent
// But it is valid to attempt remove more than once.
}
public void CallEvents(Object sender, EventArgs e)
{
if (InternalEvent != null)
{
InternalEvent(this, e);
}
}
}
}
|
bsd-2-clause
|
C#
|
8cd60c07ab7b57c89b70844036d78f7f92003796
|
Test check-in
|
lelong37/urf,lelong37/urf,lelong37/urf
|
main/Source/Repository.Pattern.Ef6/DataContext.cs
|
main/Source/Repository.Pattern.Ef6/DataContext.cs
|
#region
using System;
using System.Data.Entity;
using System.Threading;
using System.Threading.Tasks;
using Repository.Pattern.DataContext;
using Repository.Pattern.Infrastructure;
#endregion
namespace Repository.Pattern.Ef6
{
public class DataContext : DbContext, IDataContext, IDataContextAsync
{
private readonly Guid _instanceId;
public DataContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
_instanceId = Guid.NewGuid();
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
public Guid InstanceId
{
get { return _instanceId; }
}
public new DbSet<T> Set<T>() where T : class
{
return base.Set<T>();
}
public override int SaveChanges()
{
SyncObjectsStatePreCommit();
var changes = base.SaveChanges();
SyncObjectsStatePostCommit();
return changes;
}
public override async Task<int> SaveChangesAsync()
{
SyncObjectsStatePreCommit();
var changesAsync = await base.SaveChangesAsync();
SyncObjectsStatePostCommit();
return changesAsync;
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
SyncObjectsStatePreCommit();
var changesAsync = await base.SaveChangesAsync(cancellationToken);
SyncObjectsStatePostCommit();
return changesAsync;
}
public void SyncObjectState(object entity)
{
Entry(entity).State = StateHelper.ConvertState(((IObjectState)entity).ObjectState);
}
private void SyncObjectsStatePreCommit()
{
foreach (var dbEntityEntry in ChangeTracker.Entries())
dbEntityEntry.State = StateHelper.ConvertState(((IObjectState)dbEntityEntry.Entity).ObjectState);
}
public void SyncObjectsStatePostCommit()
{
foreach (var dbEntityEntry in ChangeTracker.Entries())
((IObjectState)dbEntityEntry.Entity).ObjectState = StateHelper.ConvertState(dbEntityEntry.State);
}
}
}
|
#region
using System;
using System.Data.Entity;
using System.Threading;
using System.Threading.Tasks;
using Repository.Pattern.DataContext;
using Repository.Pattern.Infrastructure;
#endregion
namespace Repository.Pattern.Ef6
{
public class DataContext : DbContext, IDataContext, IDataContextAsync
{
private readonly Guid _instanceId;
public DataContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
_instanceId = Guid.NewGuid();
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
public Guid InstanceId
{
get { return _instanceId; }
}
public new DbSet<T> Set<T>() where T : class
{
return base.Set<T>();
}
public override int SaveChanges()
{
SyncObjectsStatePreCommit();
var changes = base.SaveChanges();
SyncObjectsStatePostCommit();
return changes;
}
public override async Task<int> SaveChangesAsync()
{
SyncObjectsStatePreCommit();
var changesAsync = await base.SaveChangesAsync();
SyncObjectsStatePostCommit();
return changesAsync;
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
SyncObjectsStatePreCommit();
var changesAsync = await base.SaveChangesAsync(cancellationToken);
SyncObjectsStatePostCommit();
return changesAsync;
}
public void SyncObjectState(object entity)
{
Entry(entity).State = StateHelper.ConvertState(((IObjectState)entity).ObjectState);
}
private void SyncObjectsStatePreCommit()
{
foreach (var dbEntityEntry in ChangeTracker.Entries())
dbEntityEntry.State = StateHelper.ConvertState(((IObjectState)dbEntityEntry.Entity).ObjectState);
}
public void SyncObjectsStatePostCommit()
{
foreach (var dbEntityEntry in ChangeTracker.Entries())
((IObjectState)dbEntityEntry.Entity).ObjectState = StateHelper.ConvertState(dbEntityEntry.State);
}
}
}
|
mit
|
C#
|
e70e15da52f391783ff2458a02ab44c1d98e57e3
|
rename foo.exe to something more descriptive
|
lime45/poe_folk
|
ComPortNotify/Program.cs
|
ComPortNotify/Program.cs
|
using System;
using System.Windows.Forms;
namespace ComPortNotify
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
NAppUpdate.Framework.UpdateManager.Instance.UpdateSource = new NAppUpdate.Framework.Sources.SimpleWebSource("https://www.dropbox.com/s/4czsu1rljsj7lec/feed.xml?dl=1");
NAppUpdate.Framework.UpdateManager.Instance.Config.UpdateExecutableName = "COM Port Notifier Updater.exe";
NAppUpdate.Framework.UpdateManager.Instance.Config.UpdateProcessName = "COM Port Notifier Updater";
NAppUpdate.Framework.UpdateManager.Instance.ReinstateIfRestarted();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyApplicationContext());
}
}
}
|
using System;
using System.Windows.Forms;
namespace ComPortNotify
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
NAppUpdate.Framework.UpdateManager.Instance.UpdateSource = new NAppUpdate.Framework.Sources.SimpleWebSource("https://www.dropbox.com/s/4czsu1rljsj7lec/feed.xml?dl=1");
NAppUpdate.Framework.UpdateManager.Instance.ReinstateIfRestarted();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyApplicationContext());
}
}
}
|
mit
|
C#
|
50698c05268b5fcb0a2ab3e9118820a453198fb5
|
Use git,exe from the path
|
modulexcite/GitDiffMargin,laurentkempe/GitDiffMargin
|
GitDiffMargin/Git/GitCommands.cs
|
GitDiffMargin/Git/GitCommands.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.Shell;
namespace GitDiffMargin.Git
{
public class GitCommands : IGitCommands
{
public IEnumerable<HunkRangeInfo> GetGitDiffFor(string filename)
{
var p = GetProcess(filename);
p.StartInfo.Arguments = String.Format(@" diff --unified=0 {0}", filename);
ActivityLog.LogInformation("GitDiffMargin", "Command:" + p.StartInfo.Arguments);
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
ActivityLog.LogInformation("GitDiffMargin", "Git Diff output:" + output);
var gitDiffParser = new GitDiffParser(output);
return gitDiffParser.Parse();
}
public void StartExternalDiff(string filename)
{
var p = GetProcess(filename);
p.StartInfo.Arguments = String.Format(@" difftool -y {0}", filename);
ActivityLog.LogInformation("GitDiffMargin", "Command:" + p.StartInfo.Arguments);
p.Start();
}
private static Process GetProcess(string filename)
{
var p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.FileName = @"git.exe";
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(filename);
return p;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.Shell;
namespace GitDiffMargin.Git
{
public class GitCommands : IGitCommands
{
public IEnumerable<HunkRangeInfo> GetGitDiffFor(string filename)
{
var p = GetProcess(filename);
p.StartInfo.Arguments = String.Format(@" diff --unified=0 {0}", filename);
ActivityLog.LogInformation("GitDiffMargin", "Command:" + p.StartInfo.Arguments);
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
ActivityLog.LogInformation("GitDiffMargin", "Git Diff output:" + output);
var gitDiffParser = new GitDiffParser(output);
return gitDiffParser.Parse();
}
public void StartExternalDiff(string filename)
{
var p = GetProcess(filename);
p.StartInfo.Arguments = String.Format(@" difftool -y {0}", filename);
ActivityLog.LogInformation("GitDiffMargin", "Command:" + p.StartInfo.Arguments);
p.Start();
}
private static Process GetProcess(string filename)
{
var p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.FileName = @"C:\@Tools\Development\Git\bin\git.exe";
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(filename);
return p;
}
}
}
|
mit
|
C#
|
11bd8791bf8e60b2c8a2b942eb2b31972828643b
|
Add in check for null pointers.
|
johnmott59/PolygonClippingInCSharp
|
GrinerTest/PolygonClip/insert.cs
|
GrinerTest/PolygonClip/insert.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GrienerTest
{
public partial class PolygonClip
{
#if false
void insert(node *ins, node *first, node *last)
{
node *aux=first;
while(aux != last && aux->alpha < ins->alpha) aux = aux->next;
ins->next = aux;
ins->prev = aux->prev;
ins->prev->next = ins;
ins->next->prev = ins;
}
#endif
void insert(Node ins,Node first,Node last)
{
Node aux = first;
while (aux != last && aux.alpha < ins.alpha) aux = aux.next;
ins.next = aux;
ins.prev = aux.prev;
/*
* Feb 2017. Check against null pointer
*/
if (ins.prev != null) {
ins.prev.next = ins;
}
if (ins.next != null) {
ins.next.prev = ins;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GrienerTest
{
public partial class PolygonClip
{
#if false
void insert(node *ins, node *first, node *last)
{
node *aux=first;
while(aux != last && aux->alpha < ins->alpha) aux = aux->next;
ins->next = aux;
ins->prev = aux->prev;
ins->prev->next = ins;
ins->next->prev = ins;
}
#endif
void insert(Node ins,Node first,Node last)
{
Node aux = first;
while (aux != last && aux.alpha < ins.alpha) aux = aux.next;
ins.next = aux;
ins.prev = aux.prev;
ins.prev.next = ins;
ins.next.prev = ins;
}
}
}
|
unlicense
|
C#
|
a62402882b66135b00cafe2f58fab0f95db4ce2a
|
save settings as formatted json
|
21robin12/tfs-standalone,21robin12/tfs-standalone,21robin12/tfs-standalone
|
TfsStandalone.UI/Infrastructure/ConfigManager.cs
|
TfsStandalone.UI/Infrastructure/ConfigManager.cs
|
namespace TfsStandalone.UI.Infrastructure
{
using System;
using System.IO;
using System.Linq;
using Config;
using Newtonsoft.Json;
public static class ConfigManager
{
private static TfsStandaloneConfig _config;
public static TfsStandaloneConfig Config
{
get
{
if (_config == null)
{
var configPath = ConfigPath();
if (!File.Exists(configPath))
{
throw new FileNotFoundException($"No config file found at {configPath}");
}
var text = File.ReadAllText(configPath);
_config = JsonConvert.DeserializeObject<TfsStandaloneConfig>(text);
}
return _config;
}
}
public static TfsProject Project(string projectId)
{
return Config.ProjectCollections.SelectMany(x => x.Projects).FirstOrDefault(x => x.Id == projectId);
}
public static TfsProjectCollection ProjectCollection(int projectCollectionIndex)
{
return Config.ProjectCollections.ElementAt(projectCollectionIndex);
}
public static TfsProjectCollection ProjectCollection(TfsProject project)
{
return Config.ProjectCollections.FirstOrDefault(x => x.Projects.Any(y => y.Id == project.Id));
}
public static void SaveConfig(TfsStandaloneConfig config)
{
var text = JsonConvert.SerializeObject(config, Formatting.Indented);
File.WriteAllText(ConfigPath(), text);
}
private static string ConfigPath()
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json");
}
}
}
|
namespace TfsStandalone.UI.Infrastructure
{
using System;
using System.IO;
using System.Linq;
using Config;
using Newtonsoft.Json;
public static class ConfigManager
{
private static TfsStandaloneConfig _config;
public static TfsStandaloneConfig Config
{
get
{
if (_config == null)
{
var configPath = ConfigPath();
if (!File.Exists(configPath))
{
throw new FileNotFoundException($"No config file found at {configPath}");
}
var text = File.ReadAllText(configPath);
_config = JsonConvert.DeserializeObject<TfsStandaloneConfig>(text);
}
return _config;
}
}
public static TfsProject Project(string projectId)
{
return Config.ProjectCollections.SelectMany(x => x.Projects).FirstOrDefault(x => x.Id == projectId);
}
public static TfsProjectCollection ProjectCollection(int projectCollectionIndex)
{
return Config.ProjectCollections.ElementAt(projectCollectionIndex);
}
public static TfsProjectCollection ProjectCollection(TfsProject project)
{
return Config.ProjectCollections.FirstOrDefault(x => x.Projects.Any(y => y.Id == project.Id));
}
public static void SaveConfig(TfsStandaloneConfig config)
{
var text = JsonConvert.SerializeObject(config);
File.WriteAllText(ConfigPath(), text);
}
private static string ConfigPath()
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json");
}
}
}
|
mit
|
C#
|
dc5a1d0863b5d35cb40cf99a4a21052c5a775b0a
|
fix inlining and trigger build
|
Teleopti/Stardust
|
Node/Node/Workers/HttpSender.cs
|
Node/Node/Workers/HttpSender.cs
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Stardust.Node.Interfaces;
namespace Stardust.Node.Workers
{
public class HttpSender : IHttpSender
{
private const string Mediatype = "application/json";
private static readonly HttpClient Client = new HttpClient();
public HttpSender()
{
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Mediatype));
}
public async Task<HttpResponseMessage> PostAsync(Uri url,
object data,
CancellationToken cancellationToken)
{
var response =
await Client.PostAsync(url,
new StringContent(JsonConvert.SerializeObject(data), Encoding.Unicode, Mediatype),
cancellationToken)
.ConfigureAwait(false);
return response;
}
}
}
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Stardust.Node.Interfaces;
namespace Stardust.Node.Workers
{
public class HttpSender : IHttpSender
{
private const string Mediatype = "application/json";
private static readonly HttpClient Client = new HttpClient();
public HttpSender()
{
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Mediatype));
}
public async Task<HttpResponseMessage> PostAsync(Uri url,
object data,
CancellationToken cancellationToken)
{
var sez = JsonConvert.SerializeObject(data);
var response =
await Client.PostAsync(url,
new StringContent(sez, Encoding.Unicode, Mediatype),
cancellationToken)
.ConfigureAwait(false);
return response;
}
}
}
|
mit
|
C#
|
38b92a33730c14f855e54c2db3a74bce1de2a7b1
|
Update sample script
|
RockyTV/Duality.IronPython
|
CorePlugin/Resources/PythonScript.cs
|
CorePlugin/Resources/PythonScript.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Duality;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython.Resources
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScript)]
public class PythonScript : Resource
{
protected string _content;
public string Content { get { return _content; } }
public PythonScript()
{
var sb = new StringBuilder();
sb.AppendLine("# You can access the parent GameObject by calling `gameObject`.");
sb.AppendLine("#");
sb.AppendLine("# To use Duality classes, you must first import them:");
sb.AppendLine("# from Duality import Vector2");
sb.AppendLine("#");
sb.AppendLine("# By using `import Duality`, you must use qualified names:");
sb.AppendLine("# import Duality");
sb.AppendLine("# Duality.Log.Game.Write('Hello, world!')");
sb.AppendLine("#");
sb.AppendLine("# All code must be inside a class called `PyModule`.");
sb.AppendLine("# Code outside the class scope will be executed as well,");
sb.AppendLine("# except that you won't be able to access functions nor variables.");
sb.AppendLine();
sb.AppendLine("import Duality");
sb.AppendLine("class PyModule: ");
sb.AppendLine(" def __init__(self):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine(" # Called when a Component is initializing.");
sb.AppendLine(" # `context`: what kind of initialization is being performed on the Component.");
sb.AppendLine(" def start(self, context):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine(" # Called once per frame in order to update the Component.");
sb.AppendLine(" # `delta`: time the last frame took, in milliseconds, with time scale applied.");
sb.AppendLine(" def update(self, delta):");
sb.AppendLine(" pass");
sb.AppendLine();
_content = sb.ToString();
}
public void UpdateContent(string content)
{
_content = content;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Duality;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython.Resources
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScript)]
public class PythonScript : Resource
{
protected string _content;
public string Content { get { return _content; } }
public PythonScript()
{
var sb = new StringBuilder();
sb.AppendLine("# You can access the parent GameObject by calling `gameObject`.");
sb.AppendLine("# To use Duality objects, you must first import them.");
sb.AppendLine("# Example:");
sb.AppendLine(@"#\tfrom Duality import Vector2");
sb.AppendLine();
sb.AppendLine("class PyModule: ");
sb.AppendLine(" def __init__(self):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine("# The `start` function is called whenever a component is initializing.");
sb.AppendLine(" def start(self):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine("# The `update` function is called whenever an update happens, and includes a delta.");
sb.AppendLine(" def update(self, delta):");
sb.AppendLine(" pass");
sb.AppendLine();
_content = sb.ToString();
}
public void UpdateContent(string content)
{
_content = content;
}
}
}
|
mit
|
C#
|
38a70a97932d55c399702ad8d8faa173bec52d7d
|
build fix
|
marcwittke/Backend.Fx,marcwittke/Backend.Fx
|
src/Backend.Fx.Bootstrapping/SimpleInjectorScope.cs
|
src/Backend.Fx.Bootstrapping/SimpleInjectorScope.cs
|
namespace Backend.Fx.Bootstrapping
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Principal;
using Environment.MultiTenancy;
using Logging;
using Patterns.DependencyInjection;
using Patterns.UnitOfWork;
using SimpleInjector;
public sealed class SimpleInjectorScope : IScope
{
private static readonly ILogger Logger = LogManager.Create<SimpleInjectorScope>();
private readonly Scope scope;
public SimpleInjectorScope(Scope scope, IIdentity identity, TenantId tenantId)
{
LogManager.BeginActivity();
this.scope = scope;
Logger.Info($"Began new scope for identity [{identity.Name}] and tenant[{(tenantId.HasValue ? tenantId.Value.ToString() : "")}]");
}
public IUnitOfWork BeginUnitOfWork(bool beginAsReadonlyUnitOfWork)
{
IUnitOfWork unitOfWork = beginAsReadonlyUnitOfWork
? scope.Container.GetInstance<IReadonlyUnitOfWork>()
: scope.Container.GetInstance<IUnitOfWork>();
unitOfWork.Begin();
return unitOfWork;
}
public TService GetInstance<TService>() where TService : class
{
return scope.Container.GetInstance<TService>();
}
public object GetInstance(Type serviceType)
{
return scope.Container.GetInstance(serviceType);
}
public IEnumerable<TService> GetAllInstances<TService>() where TService : class
{
return scope.Container.GetAllInstances<TService>();
}
public IEnumerable GetAllInstance(Type serviceType)
{
return scope.Container.GetAllInstances(serviceType);
}
public void Dispose()
{
scope?.Dispose();
}
}
}
|
namespace Backend.Fx.Bootstrapping
{
using System.Collections.Generic;
using System.Security.Principal;
using Environment.MultiTenancy;
using Logging;
using Patterns.DependencyInjection;
using Patterns.UnitOfWork;
using SimpleInjector;
public sealed class SimpleInjectorScope : IScope
{
private static readonly ILogger Logger = LogManager.Create<SimpleInjectorScope>();
private readonly Scope scope;
public SimpleInjectorScope(Scope scope, IIdentity identity, TenantId tenantId)
{
LogManager.BeginActivity();
this.scope = scope;
Logger.Info($"Began new scope for identity [{identity.Name}] and tenant[{(tenantId.HasValue ? tenantId.Value.ToString() : "")}]");
}
public IUnitOfWork BeginUnitOfWork(bool beginAsReadonlyUnitOfWork)
{
IUnitOfWork unitOfWork = beginAsReadonlyUnitOfWork
? scope.Container.GetInstance<IReadonlyUnitOfWork>()
: scope.Container.GetInstance<IUnitOfWork>();
unitOfWork.Begin();
return unitOfWork;
}
public TService GetInstance<TService>() where TService : class
{
return scope.Container.GetInstance<TService>();
}
public IEnumerable<TService> GetAllInstances<TService>() where TService : class
{
return scope.Container.GetAllInstances<TService>();
}
public void Dispose()
{
scope?.Dispose();
}
}
}
|
mit
|
C#
|
163a9d74f7f75a330335b06e0b5f0246a02877a5
|
Add nick wolf contact info.
|
jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox
|
ZirMed.TrainingSandbox/Views/Home/Contact.cshtml
|
ZirMed.TrainingSandbox/Views/Home/Contact.cshtml
|
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
<strong>Nicolas:</strong> <a href="mailto:nick.wolf@zirmed.com">nick.wolf@zirmed.com</a>
</address>
|
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Pat:</strong> <a href="mailto:patrick.fulton@zirmed.com">patrick.fulton@zirmed.com</a>
<strong>Dustin:</strong> <a href="mailto:dustin.crawford@zirmed.com">dustin.crawford@zirmed.com</a>
</address>
|
mit
|
C#
|
3759931aac48ea3a8403c7fe77c699f1d376da01
|
Read data if available
|
michael-reichenauer/Dependinator
|
Dependiator/Modeling/ModelService.cs
|
Dependiator/Modeling/ModelService.cs
|
using System.Collections.Generic;
using System.Windows;
using Dependiator.ApplicationHandling;
using Dependiator.MainViews;
using Dependiator.Modeling.Analyzing;
using Dependiator.Modeling.Serializing;
using Dependiator.Utils;
namespace Dependiator.Modeling
{
[SingleInstance]
internal class ModelService : IModelService
{
private readonly WorkingFolder workingFolder;
private readonly IReflectionService reflectionService;
private readonly IElementService elementService;
private readonly INodeService nodeService;
private readonly IDataSerializer dataSerializer;
private ElementTree elementTree;
public ModelService(
WorkingFolder workingFolder,
IReflectionService reflectionService,
IElementService elementService,
INodeService nodeService,
IDataSerializer dataSerializer)
{
this.workingFolder = workingFolder;
this.reflectionService = reflectionService;
this.elementService = elementService;
this.nodeService = nodeService;
this.dataSerializer = dataSerializer;
}
public void InitModules()
{
if (!dataSerializer.TryDeserialize(out Data data))
{
data = reflectionService.Analyze(workingFolder.FilePath);
}
if (elementTree != null)
{
nodeService.ClearAll();
}
elementTree = elementService.ToElementTree(data);
//Data data2 = elementService.ToData(elementTree);
//serializer.Serialize(data2);
//elementTree = elementService.ToElementTree(data2);
//Data data3 = elementService.ToData(elementTree);
//serializer.Serialize(data3);
// elementTree = elementService.ToElementTree(data3);
Timing t = new Timing();
Node rootNode = GetNode(elementTree);
nodeService.ShowRootNode(rootNode);
t.Log("Created modules");
}
public object MoveNode(Point viewPosition, Vector viewOffset, object movingObject)
{
return nodeService.MoveNode(viewPosition, viewOffset, movingObject);
}
public void Close()
{
Data data = elementService.ToData(elementTree);
dataSerializer.Serialize(data);
}
private Node GetNode(ElementTree elementTree)
{
Size size = new Size(200000, 100000);
Rect viewBox = nodeService.CurrentViewPort;
double scale = 1 ;
nodeService.Scale = scale;
viewBox = nodeService.CurrentViewPort;
//double x = ((viewBox.Width - viewBox.X) / 2 - (size.Width / 2)) + 1000;
//double y = ((viewBox.Height - viewBox.Y) / 2 -(size.Height / 2)) + 500;
double x = 0 - (size.Width / 2);
double y = 0 - (size.Height / 2);
Point position = new Point(x, y);
Rect bounds = new Rect(position, size);
Module module = new Module(nodeService, elementTree.Root, bounds, null);
nodeService.AddRootNode(module);
return module;
}
}
}
|
using System.Collections.Generic;
using System.Windows;
using Dependiator.ApplicationHandling;
using Dependiator.MainViews;
using Dependiator.Modeling.Analyzing;
using Dependiator.Modeling.Serializing;
using Dependiator.Utils;
namespace Dependiator.Modeling
{
[SingleInstance]
internal class ModelService : IModelService
{
private readonly WorkingFolder workingFolder;
private readonly IReflectionService reflectionService;
private readonly IElementService elementService;
private readonly INodeService nodeService;
private readonly IDataSerializer dataSerializer;
private ElementTree elementTree;
public ModelService(
WorkingFolder workingFolder,
IReflectionService reflectionService,
IElementService elementService,
INodeService nodeService,
IDataSerializer dataSerializer)
{
this.workingFolder = workingFolder;
this.reflectionService = reflectionService;
this.elementService = elementService;
this.nodeService = nodeService;
this.dataSerializer = dataSerializer;
}
public void InitModules()
{
Data data;
//if (!dataSerializer.TryDeserialize(out Data data))
{
data = reflectionService.Analyze(workingFolder.FilePath);
}
if (elementTree != null)
{
nodeService.ClearAll();
}
elementTree = elementService.ToElementTree(data);
//Data data2 = elementService.ToData(elementTree);
//serializer.Serialize(data2);
//elementTree = elementService.ToElementTree(data2);
//Data data3 = elementService.ToData(elementTree);
//serializer.Serialize(data3);
// elementTree = elementService.ToElementTree(data3);
Timing t = new Timing();
Node rootNode = GetNode(elementTree);
nodeService.ShowRootNode(rootNode);
t.Log("Created modules");
}
public object MoveNode(Point viewPosition, Vector viewOffset, object movingObject)
{
return nodeService.MoveNode(viewPosition, viewOffset, movingObject);
}
public void Close()
{
Data data = elementService.ToData(elementTree);
dataSerializer.Serialize(data);
}
private Node GetNode(ElementTree elementTree)
{
Size size = new Size(200000, 100000);
Rect viewBox = nodeService.CurrentViewPort;
double scale = 1 ;
nodeService.Scale = scale;
viewBox = nodeService.CurrentViewPort;
//double x = ((viewBox.Width - viewBox.X) / 2 - (size.Width / 2)) + 1000;
//double y = ((viewBox.Height - viewBox.Y) / 2 -(size.Height / 2)) + 500;
double x = 0 - (size.Width / 2);
double y = 0 - (size.Height / 2);
Point position = new Point(x, y);
Rect bounds = new Rect(position, size);
Module module = new Module(nodeService, elementTree.Root, bounds, null);
nodeService.AddRootNode(module);
return module;
}
}
}
|
mit
|
C#
|
db75332cde309ad10a40aa1136db0b7120e2b6de
|
Fix indentation when changing inside multiline block
|
hifi/monodevelop-justenoughvi
|
JustEnoughVi/ChangeInnerBlock.cs
|
JustEnoughVi/ChangeInnerBlock.cs
|
using System;
using Mono.TextEditor;
using ICSharpCode.NRefactory.Utils;
using ICSharpCode.NRefactory;
namespace JustEnoughVi
{
public class ChangeInnerBlock : ChangeCommand
{
public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar)
: base(editor, TextObject.InnerBlock, openingChar, closingChar)
{
}
protected override void Run()
{
CommandRange range = _selector();
ChangeRange(range);
if (range != CommandRange.Empty)
{
// Move caret inside if it is on on opening character and block is empty
if (range.Length == 0 && Editor.Caret.Offset < range.Start)
Editor.Caret.Offset++;
else
{
// if block still has two newlines inside, then drop inside block and indent
int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]);
if (del1 > 0)
{
int del2Start = range.Start - 1 + del1;
int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start],
Editor.Text[del2Start + 1]);
if (del2 > 0)
IndentInsideBlock(range.Start - 2);
}
}
}
}
private void IndentInsideBlock(int openingChar)
{
string indentation = Editor.GetLineIndent(Editor.OffsetToLineNumber(openingChar));
if (indentation != null && indentation.Length > 0)
Editor.Insert(Editor.Caret.Offset, indentation);
MiscActions.InsertTab(Editor);
}
}
}
|
using System;
using Mono.TextEditor;
using ICSharpCode.NRefactory;
namespace JustEnoughVi
{
public class ChangeInnerBlock : ChangeCommand
{
public ChangeInnerBlock(TextEditorData editor, char openingChar, char closingChar)
: base(editor, TextObject.InnerBlock, openingChar, closingChar)
{
}
protected override void Run()
{
CommandRange range = _selector();
ChangeRange(range);
if (range != CommandRange.Empty)
{
// Move caret inside if it is on on opening character and block is empty
if (range.Length == 0 && Editor.Caret.Offset < range.Start)
Editor.Caret.Offset++;
else
{
// if block still has two newlines inside, then drop inside block and indent
int del1 = NewLine.GetDelimiterLength(Editor.Text[range.Start - 1], Editor.Text[range.Start]);
if (del1 > 0)
{
int del2Start = range.Start - 1 + del1;
int del2 = NewLine.GetDelimiterLength(Editor.Text[del2Start],
Editor.Text[del2Start + 1]);
if (del2 > 0)
IndentInsideBlock(range.Start);
}
}
}
}
private void IndentInsideBlock(int blockStart)
{
int end = blockStart;
while (Char.IsWhiteSpace(Editor.Text[end]))
end++;
Editor.SetSelection(blockStart, end);
Editor.DeleteSelectedText();
MiscActions.InsertNewLine(Editor);
}
}
}
|
mit
|
C#
|
f0521f4f23026d1ad6ce0fbd1b9838fe7664c5bd
|
Check the condition
|
FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,Livven/AngleSharp,zedr0n/AngleSharp.Local,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,Livven/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,Livven/AngleSharp,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,AngleSharp/AngleSharp
|
AngleSharp/Css/ValueConverters/StartsWithValueConverter.cs
|
AngleSharp/Css/ValueConverters/StartsWithValueConverter.cs
|
namespace AngleSharp.Css.ValueConverters
{
using AngleSharp.Parser.Css;
using System;
using System.Collections.Generic;
sealed class StartsWithValueConverter<T> : IValueConverter<T>
{
readonly Predicate<CssToken> _condition;
readonly IValueConverter<T> _converter;
public StartsWithValueConverter(Predicate<CssToken> condition, IValueConverter<T> converter)
{
_condition = condition;
_converter = converter;
}
public Boolean TryConvert(IEnumerable<CssToken> value, Action<T> setResult)
{
var rest = Transform(value);
return rest != null && _converter.TryConvert(rest, setResult);
}
public Boolean Validate(IEnumerable<CssToken> value)
{
var rest = Transform(value);
return rest != null && _converter.Validate(rest);
}
List<CssToken> Transform(IEnumerable<CssToken> values)
{
var enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current.Type != CssTokenType.Whitespace)
break;
}
if (_condition(enumerator.Current))
{
var list = new List<CssToken>();
while (enumerator.MoveNext())
{
if (enumerator.Current.Type == CssTokenType.Whitespace && list.Count == 0)
continue;
list.Add(enumerator.Current);
}
return list;
}
return null;
}
}
}
|
namespace AngleSharp.Css.ValueConverters
{
using AngleSharp.Parser.Css;
using System;
using System.Collections.Generic;
sealed class StartsWithValueConverter<T> : IValueConverter<T>
{
readonly Predicate<CssToken> _condition;
readonly IValueConverter<T> _converter;
public StartsWithValueConverter(Predicate<CssToken> condition, IValueConverter<T> converter)
{
_condition = condition;
_converter = converter;
}
public Boolean TryConvert(IEnumerable<CssToken> value, Action<T> setResult)
{
return _converter.TryConvert(Transform(value), setResult);
}
public Boolean Validate(IEnumerable<CssToken> value)
{
return _converter.Validate(Transform(value));
}
IEnumerable<CssToken> Transform(IEnumerable<CssToken> values)
{
var enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current.Type != CssTokenType.Whitespace)
break;
}
if (_condition(enumerator.Current))
{
while (enumerator.MoveNext())
yield return enumerator.Current;
}
}
}
}
|
mit
|
C#
|
dd033df831319768a5cc6993f7e0ad1886f7de18
|
Set AssemblyVersion number correctly to 0.3.2
|
LongNguyenP/DynaShape
|
DynaShape/Properties/AssemblyInfo.cs
|
DynaShape/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DynaShape")]
[assembly: AssemblyDescription("Open-source Dynamo plugin for constraint-based form finding, optimization and physics simulation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynaShape")]
[assembly: AssemblyCopyright("MIT License © 2017 Long Nguyen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("157ad178-ee17-46e9-b6dc-c50eb9dcca60")]
[assembly: AssemblyVersion("0.3.2.0")]
[assembly: AssemblyFileVersion("0.3.2.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DynaShape")]
[assembly: AssemblyDescription("Open-source Dynamo plugin for constraint-based form finding, optimization and physics simulation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynaShape")]
[assembly: AssemblyCopyright("MIT License © 2017 Long Nguyen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("157ad178-ee17-46e9-b6dc-c50eb9dcca60")]
[assembly: AssemblyVersion("0.3.1.2")]
[assembly: AssemblyFileVersion("0.3.1.2")]
|
mit
|
C#
|
90fb3e781983ae8d0caa14dc21bb0fb32df5755b
|
Use portable ToCharArray overload yielding equivalent result
|
cureos/Evil-DICOM,SuneBuur/Evil-DICOM
|
EvilDICOM.Core/EvilDICOM.Core/IO/Writing/DICOMBinaryWriter.cs
|
EvilDICOM.Core/EvilDICOM.Core/IO/Writing/DICOMBinaryWriter.cs
|
using System;
using System.IO;
using System.Text;
namespace EvilDICOM.Core.IO.Writing
{
public class DICOMBinaryWriter : IDisposable
{
private readonly BinaryWriter _writer;
/// <summary>
/// Constructs a new writer from a file path.
/// </summary>
/// <param name="filePath">path to the file to be written</param>
public DICOMBinaryWriter(string filePath)
{
_writer = new BinaryWriter(
File.Open(filePath, FileMode.Create),
Encoding.UTF8);
}
public DICOMBinaryWriter(Stream stream)
{
_writer = new BinaryWriter(stream, Encoding.UTF8);
}
public void Dispose()
{
_writer.Dispose();
}
public void Write(byte b)
{
_writer.Write(b);
}
public void Write(byte[] bytes)
{
_writer.Write(bytes);
}
public void Write(char[] chars)
{
_writer.Write(chars);
}
public void Write(string chars)
{
char[] asCharArray = chars.ToCharArray();
Write(asCharArray);
}
public void WriteNullBytes(int numberToWrite)
{
for (int i = 0; i < numberToWrite; i++)
{
Write(0x00);
}
}
}
}
|
using System;
using System.IO;
using System.Text;
namespace EvilDICOM.Core.IO.Writing
{
public class DICOMBinaryWriter : IDisposable
{
private readonly BinaryWriter _writer;
/// <summary>
/// Constructs a new writer from a file path.
/// </summary>
/// <param name="filePath">path to the file to be written</param>
public DICOMBinaryWriter(string filePath)
{
_writer = new BinaryWriter(
File.Open(filePath, FileMode.Create),
Encoding.UTF8);
}
public DICOMBinaryWriter(Stream stream)
{
_writer = new BinaryWriter(stream, Encoding.UTF8);
}
public void Dispose()
{
_writer.Dispose();
}
public void Write(byte b)
{
_writer.Write(b);
}
public void Write(byte[] bytes)
{
_writer.Write(bytes);
}
public void Write(char[] chars)
{
_writer.Write(chars);
}
public void Write(string chars)
{
char[] asCharArray = chars.ToCharArray(0, chars.Length);
Write(asCharArray);
}
public void WriteNullBytes(int numberToWrite)
{
for (int i = 0; i < numberToWrite; i++)
{
Write(0x00);
}
}
}
}
|
mit
|
C#
|
751c48c8049e53ada536a55f2c67e5c10cc3c3b7
|
Update Vibrancy.cs
|
ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET
|
ElectronNET.API/Entities/Vibrancy.cs
|
ElectronNET.API/Entities/Vibrancy.cs
|
using System.Runtime.Serialization;
using System;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
public enum Vibrancy
{
/// <summary>
/// The appearance based
/// </summary>
[EnumMember(Value = "appearance-based")]
[Obsolete("Removed in macOS Catalina (10.15).")]
appearanceBased,
/// <summary>
/// The light
/// </summary>
[Obsolete("Removed in macOS Catalina (10.15).")]
light,
/// <summary>
/// The dark
/// </summary>
[Obsolete("Removed in macOS Catalina (10.15).")]
dark,
/// <summary>
/// The titlebar
/// </summary>
titlebar,
/// <summary>
/// The selection
/// </summary>
selection,
/// <summary>
/// The menu
/// </summary>
menu,
/// <summary>
/// The popover
/// </summary>
popover,
/// <summary>
/// The sidebar
/// </summary>
sidebar,
/// <summary>
/// The medium light
/// </summary>
[EnumMember(Value = "medium-light")]
[Obsolete("Removed in macOS Catalina (10.15).")]
mediumLight,
/// <summary>
/// The ultra dark
/// </summary>
[EnumMember(Value = "ultra-dark")]
[Obsolete("Removed in macOS Catalina (10.15).")]
ultraDark,
header,
sheet,
window,
hud,
[EnumMember(Value = "fullscreen-ui")]
fullscreenUI,
tooltip,
content,
[EnumMember(Value = "under-window")]
underWindow,
[EnumMember(Value = "under-page")]
underPage
}
}
|
using System.Runtime.Serialization;
using System;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
public enum Vibrancy
{
/// <summary>
/// The appearance based
/// </summary>
[EnumMember(Value = "appearance-based")]
[Obsolete("Removed in macOS Catalina (10.15).")]
appearanceBased,
/// <summary>
/// The light
/// </summary>
[Obsolete("Removed in macOS Catalina (10.15).")]
light,
/// <summary>
/// The dark
/// </summary>
[Obsolete("Removed in macOS Catalina (10.15).")]
dark,
/// <summary>
/// The titlebar
/// </summary>
titlebar,
/// <summary>
/// The selection
/// </summary>
selection,
/// <summary>
/// The menu
/// </summary>
menu,
/// <summary>
/// The popover
/// </summary>
popover,
/// <summary>
/// The sidebar
/// </summary>
sidebar,
/// <summary>
/// The medium light
/// </summary>
[EnumMember(Value = "medium-light")]
[Obsolete("Removed in macOS Catalina (10.15).")]
mediumLight,
/// <summary>
/// The ultra dark
/// </summary>
[EnumMember(Value = "ultra-dark")]
[Obsolete("Removed in macOS Catalina (10.15).")]
ultraDark,
popover,
header,
sheet,
window,
hud,
[EnumMember(Value = "fullscreen-ui")]
fullscreenUI,
tooltip,
content,
[EnumMember(Value = "under-window")]
underWindow,
[EnumMember(Value = "under-page")]
underPage
}
}
|
mit
|
C#
|
d024135bc01098165d64201eee86643de5466e7a
|
change scriptinstance status to string
|
andiexer/EagleEye-ScriptLogPlatform,andiexer/EagleEye-ScriptLogPlatform,andiexer/EagleEye-ScriptLogPlatform,andiexer/EagleEye-ScriptLogPlatform,andiexer/EagleEye-ScriptLogPlatform
|
src/Frontend/Gateway.API/Entities/ScriptInstance.cs
|
src/Frontend/Gateway.API/Entities/ScriptInstance.cs
|
using EESLP.Frontend.Gateway.API.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace EESLP.Frontend.Gateway.API.Entities
{
[Table("ScriptInstance")]
public class ScriptInstance : Entity, IAuditableEntity
{
public int Id { get; set; }
public string InstanceStatus { get; set; }
public Host Host { get; set; }
public Script Script { get; set; }
public string TransactionId { get; set; }
public DateTime? EndDateTime { get; set; }
public DateTime CreatedDateTime { get; set; }
public DateTime LastModDateTime { get; set; }
}
}
|
using EESLP.Frontend.Gateway.API.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace EESLP.Frontend.Gateway.API.Entities
{
[Table("ScriptInstance")]
public class ScriptInstance : Entity, IAuditableEntity
{
public int Id { get; set; }
public ScriptInstanceStatus InstanceStatus { get; set; }
public Host Host { get; set; }
public Script Script { get; set; }
public string TransactionId { get; set; }
public DateTime? EndDateTime { get; set; }
public DateTime CreatedDateTime { get; set; }
public DateTime LastModDateTime { get; set; }
}
}
|
mit
|
C#
|
1825327f0461697c29c792a345dc165749ff8007
|
work in progress
|
KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin
|
src/Kirkin.Experimental/Diagnostics/ProcessScope.cs
|
src/Kirkin.Experimental/Diagnostics/ProcessScope.cs
|
using System;
using System.Diagnostics;
using System.Threading;
namespace Kirkin.Diagnostics
{
/// <summary>
/// Manages the lifetime of the given process, ensuring that the process is reliably
/// killed if <see cref="IDisposable.Dispose"/> is called. Also terminates the process
/// if the current <see cref="AppDomain"/> exits while the process is still running.
/// </summary>
public sealed class ProcessScope : IDisposable
{
private readonly EventHandler CurrentDomainExitHandler;
private int _disposed;
/// <summary>
/// <see cref="System.Diagnostics.Process"/> whose lifetime is managed by ths instance.
/// </summary>
public Process Process { get; }
/// <summary>
/// Returns true if the process was killed as the result of the <see cref="Dispose"/> call.
/// </summary>
public bool ForciblyTerminated { get; private set; }
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="process">Process whose lifetime will be managed by this instance.</param>
public ProcessScope(Process process)
{
Process = process;
CurrentDomainExitHandler = (s, e) => Dispose();
// Ensure that the managed process is killed when this domain exits.
AppDomain.CurrentDomain.ProcessExit += CurrentDomainExitHandler;
}
/// <summary>
/// Terminates the managed process if necessary and releases any resources held by this instance.
/// </summary>
public void Dispose()
{
bool needsDisposing = (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0);
if (needsDisposing)
{
// Even if the below Kill call fails, we don't want this
// handler left dangling as it won't do anything useful.
AppDomain.CurrentDomain.ProcessExit -= CurrentDomainExitHandler;
if (Process.HasExited)
{
// TODO: Determine if this is really necessary.
Process.Close();
}
else
{
// Setting this flag first to ensure that any clients listening for the Process.Exited
// event or waiting on the Process.WaitForExit call will be able to see this value.
ForciblyTerminated = true;
Process.Kill();
}
}
}
}
}
|
using System;
using System.Diagnostics;
using System.Threading;
namespace Kirkin.Diagnostics
{
/// <summary>
/// Manages the lifetime of the given process, ensuring that the process is reliably
/// killed if <see cref="IDisposable.Dispose"/> is called. Also terminates the process
/// if the current <see cref="AppDomain"/> exits while the process is still running.
/// </summary>
public sealed class ProcessScope : IDisposable
{
private readonly EventHandler CurrentDomainExitHandler;
private int _disposed;
/// <summary>
/// <see cref="System.Diagnostics.Process"/> whose lifetime is managed by ths instance.
/// </summary>
public Process Process { get; }
/// <summary>
/// Returns true if the process was killed as the result of the <see cref="Dispose"/> call.
/// </summary>
public bool ForciblyTerminated { get; private set; }
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="process">Process whose lifetime will be managed by this instance.</param>
public ProcessScope(Process process)
{
Process = process;
CurrentDomainExitHandler = (s, e) => Dispose();
// Ensure that the managed process is killed when this domain exits.
AppDomain.CurrentDomain.ProcessExit += CurrentDomainExitHandler;
}
/// <summary>
/// Terminates the managed process if necessary and releases any resources held by this instance.
/// </summary>
public void Dispose()
{
bool needsDisposing = (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0);
if (needsDisposing)
{
if (Process.HasExited)
{
Process.Close();
}
else
{
Process.Kill();
ForciblyTerminated = true;
}
AppDomain.CurrentDomain.ProcessExit -= CurrentDomainExitHandler;
}
}
}
}
|
mit
|
C#
|
e719e764e69c8c2f44547ca0549038b2efad2449
|
Update IntroBasic.cs
|
Ky7m/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Teknikaali/BenchmarkDotNet
|
samples/BenchmarkDotNet.Samples/Intro/IntroBasic.cs
|
samples/BenchmarkDotNet.Samples/Intro/IntroBasic.cs
|
using System.Threading;
using BenchmarkDotNet.Attributes;
namespace BenchmarkDotNet.Samples.Intro
{
// It is very easy to use BenchmarkDotNet. You should just create a class
public class IntroBasic
{
// And define a method with the Benchmark attribute
[Benchmark]
public void Sleep()
{
Thread.Sleep(10);
}
// You can write a description for your method.
[Benchmark(Description = "Thread.Sleep(10)")]
public void SleepWithDescription()
{
Thread.Sleep(10);
}
}
}
|
using System.Threading;
using BenchmarkDotNet.Attributes;
namespace BenchmarkDotNet.Samples.Intro
{
// It is very easy to use BenchmarkDotNet. You should just create a class
public class IntroBasic
{
// And define a method with the Benchmark attribute
[Benchmark]
public void Sleep()
{
Thread.Sleep(10);
}
// You can write a description for your method.
[Benchmark(Description = "Thread.Sleep(100)")]
public void SleepWithDescription()
{
Thread.Sleep(10);
}
}
}
|
mit
|
C#
|
fc7769ee522c9ac63deb95014d40bed0a6ecbf7f
|
Set Culture.Dir to ltr as it is not W3C compliant to set it to string.empty (#5122)
|
xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2
|
src/OrchardCore/OrchardCore.DisplayManagement.Liquid/CultureLiquidTemplateEventHandler.cs
|
src/OrchardCore/OrchardCore.DisplayManagement.Liquid/CultureLiquidTemplateEventHandler.cs
|
using System.Globalization;
using System.Threading.Tasks;
using Fluid;
using Fluid.Values;
using OrchardCore.Liquid;
namespace OrchardCore.DisplayManagement.Liquid
{
/// <summary>
/// Provides access to the Culture property.
/// </summary>
public class CultureLiquidTemplateEventHandler : ILiquidTemplateEventHandler
{
static CultureLiquidTemplateEventHandler()
{
TemplateContext.GlobalMemberAccessStrategy.Register<CultureInfo, FluidValue>((culture, name) =>
{
switch (name)
{
case "Name": return new StringValue(culture.Name);
case "Dir": return new StringValue(culture.TextInfo.IsRightToLeft ? "rtl" : "ltr");
default: return null;
}
});
}
public Task RenderingAsync(TemplateContext context)
{
context.SetValue("Culture", CultureInfo.CurrentUICulture);
return Task.CompletedTask;
}
}
}
|
using System.Globalization;
using System.Threading.Tasks;
using Fluid;
using Fluid.Values;
using OrchardCore.Liquid;
namespace OrchardCore.DisplayManagement.Liquid
{
/// <summary>
/// Provides access to the Culture property.
/// </summary>
public class CultureLiquidTemplateEventHandler : ILiquidTemplateEventHandler
{
static CultureLiquidTemplateEventHandler()
{
TemplateContext.GlobalMemberAccessStrategy.Register<CultureInfo, FluidValue>((culture, name) =>
{
switch (name)
{
case "Name": return new StringValue(culture.Name);
case "Dir": return new StringValue(culture.TextInfo.IsRightToLeft ? "rtl" : "");
default: return null;
}
});
}
public Task RenderingAsync(TemplateContext context)
{
context.SetValue("Culture", CultureInfo.CurrentUICulture);
return Task.CompletedTask;
}
}
}
|
bsd-3-clause
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.