doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
4e70ffc3-d0e8-4b46-9be9-f68f35bda9c5 | {
"language": "C#"
} | ```c#
// Unzip class usage example
// Written by Alexey Yakovlev <yallie@yandex.ru>
// https://github.com/yallie/unzip
using System;
using System.Linq;
namespace Internals
{
internal struct Program
{
private static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Syntax: unzip Archive.zip TargetDirectory");
return;
}
var archiveName = args.First();
var outputDirectory = args.Last();
using (var unzip = new Unzip(archiveName))
{
ListFiles(unzip);
unzip.ExtractToDirectory(outputDirectory);
}
}
private static void ListFiles(Unzip unzip)
{
var tab = unzip.Entries.Any(e => e.IsDirectory) ? "\t" : string.Empty;
foreach (var entry in unzip.Entries.OrderBy(e => e.Name))
{
if (entry.IsFile)
{
Console.WriteLine(tab + "{0}: {1} -> {2}", entry.Name, entry.CompressedSize, entry.OriginalSize);
}
else if (entry.IsDirectory)
{
Console.WriteLine(entry.Name);
}
}
}
}
}
```
Use tabs instead of spaces. | ```c#
// Unzip class usage example
// Written by Alexey Yakovlev <yallie@yandex.ru>
// https://github.com/yallie/unzip
using System;
using System.Linq;
namespace Internals
{
internal struct Program
{
private static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Syntax: unzip Archive.zip TargetDirectory");
return;
}
var archiveName = args.First();
var outputDirectory = args.Last();
using (var unzip = new Unzip(archiveName))
{
ListFiles(unzip);
unzip.ExtractToDirectory(outputDirectory);
}
}
private static void ListFiles(Unzip unzip)
{
var tab = unzip.Entries.Any(e => e.IsDirectory) ? "\t" : string.Empty;
foreach (var entry in unzip.Entries.OrderBy(e => e.Name))
{
if (entry.IsFile)
{
Console.WriteLine(tab + "{0}: {1} -> {2}", entry.Name, entry.CompressedSize, entry.OriginalSize);
}
else if (entry.IsDirectory)
{
Console.WriteLine(entry.Name);
}
}
}
}
}
``` |
40c6f2c8-0786-46ea-a05e-094b327e64ca | {
"language": "C#"
} | ```c#
using System;
namespace Totem.Tracking
{
/// <summary>
/// A timeline event tracked by an index
/// </summary>
public class TrackedEvent
{
public TrackedEvent(string eventType, long eventPosition, Id userId, DateTime eventWhen, string keyType, string keyValue)
{
EventType = eventType;
EventPosition = eventPosition;
UserId = userId;
EventWhen = eventWhen;
KeyType = keyType;
KeyValue = keyValue;
}
public string EventType;
public long EventPosition;
public Id UserId;
public DateTime EventWhen;
public string KeyType;
public string KeyValue;
}
}```
Add missing constructor for derived tracking events | ```c#
using System;
namespace Totem.Tracking
{
/// <summary>
/// A timeline event tracked by an index
/// </summary>
public class TrackedEvent
{
protected TrackedEvent()
{}
public TrackedEvent(string eventType, long eventPosition, Id userId, DateTime eventWhen, string keyType, string keyValue)
{
EventType = eventType;
EventPosition = eventPosition;
UserId = userId;
EventWhen = eventWhen;
KeyType = keyType;
KeyValue = keyValue;
}
public string EventType;
public long EventPosition;
public Id UserId;
public DateTime EventWhen;
public string KeyType;
public string KeyValue;
}
}``` |
6b1211a3-0725-4ecb-982e-c832a9d3183f | {
"language": "C#"
} | ```c#
using NLog;
using NLog.Config;
using NLog.Targets;
namespace CoCo
{
internal static class NLog
{
internal static void Initialize()
{
LoggingConfiguration config = new LoggingConfiguration();
FileTarget fileTarget = new FileTarget("File");
FileTarget fileDebugTarget = new FileTarget("File debug");
fileTarget.Layout = "${date}___${level}___${message}";
fileTarget.FileName = @"${nlogdir}\file.log";
fileDebugTarget.Layout = "${date}___${level}___${message}${newline}${stacktrace}";
fileDebugTarget.FileName = @"${nlogdir}\file_debug.log";
config.AddTarget(fileTarget);
config.AddTarget(fileDebugTarget);
config.AddRule(LogLevel.Debug, LogLevel.Debug, fileDebugTarget, "*");
config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "*");
//LogManager.ThrowConfigExceptions = true;
//LogManager.ThrowExceptions = true;
LogManager.Configuration = config;
}
}
}```
Move log files to local application data. | ```c#
using System;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace CoCo
{
internal static class NLog
{
internal static void Initialize()
{
string appDataLocal = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\\CoCo";
if (!Directory.Exists(appDataLocal))
{
Directory.CreateDirectory(appDataLocal);
}
LoggingConfiguration config = new LoggingConfiguration();
FileTarget fileTarget = new FileTarget("File");
FileTarget fileDebugTarget = new FileTarget("File debug");
fileTarget.Layout = "${date}___${level}___${message}";
fileTarget.FileName = $"{appDataLocal}\\file.log";
fileDebugTarget.Layout = "${date}___${level}___${message}${newline}${stacktrace}";
fileDebugTarget.FileName = $"{appDataLocal}\\file_debug.log";
config.AddTarget(fileTarget);
config.AddTarget(fileDebugTarget);
config.AddRule(LogLevel.Debug, LogLevel.Debug, fileDebugTarget, "*");
config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "*");
//LogManager.ThrowConfigExceptions = true;
//LogManager.ThrowExceptions = true;
LogManager.Configuration = config;
}
}
}``` |
1975162d-997f-4156-abab-1df077f1a168 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Cosmos.Build.Tasks
{
public class CreateGrubConfig: Task
{
[Required]
public string TargetDirectory { get; set; }
[Required]
public string BinName { get; set; }
private string Indentation = " ";
public override bool Execute()
{
if (!Directory.Exists(TargetDirectory))
{
Log.LogError($"Invalid target directory! Target directory: '{TargetDirectory}'");
return false;
}
var xBinName = BinName;
var xLabelName = Path.GetFileNameWithoutExtension(xBinName);
using (var xWriter = File.CreateText(Path.Combine(TargetDirectory + "/boot/grub/", "grub.cfg")))
{
xWriter.WriteLine("insmod vbe");
xWriter.WriteLine("insmod vga");
xWriter.WriteLine("insmod video_bochs");
xWriter.WriteLine("insmod video_cirrus");
xWriter.WriteLine("set root='(hd0,msdos1)'");
xWriter.WriteLine();
xWriter.WriteLine("menuentry '" + xLabelName + "' {");
WriteIndentedLine(xWriter, "multiboot /boot/" + xBinName + " vid=preset,1024,768 hdd=0");
WriteIndentedLine(xWriter, "set gfxpayload=800x600x32");
WriteIndentedLine(xWriter, "boot");
xWriter.WriteLine("}");
}
return true;
}
private void WriteIndentedLine(TextWriter aWriter, string aText)
{
aWriter.WriteLine(Indentation + aText);
}
}
}
```
Update grubconfig according to osdev.org | ```c#
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Cosmos.Build.Tasks
{
public class CreateGrubConfig: Task
{
[Required]
public string TargetDirectory { get; set; }
[Required]
public string BinName { get; set; }
private string Indentation = " ";
public override bool Execute()
{
if (!Directory.Exists(TargetDirectory))
{
Log.LogError($"Invalid target directory! Target directory: '{TargetDirectory}'");
return false;
}
var xBinName = BinName;
var xLabelName = Path.GetFileNameWithoutExtension(xBinName);
using (var xWriter = File.CreateText(Path.Combine(TargetDirectory + "/boot/grub/", "grub.cfg")))
{
xWriter.WriteLine("menuentry '" + xLabelName + "' {");
WriteIndentedLine(xWriter, "multiboot /boot/" + xBinName);
xWriter.WriteLine("}");
}
return true;
}
private void WriteIndentedLine(TextWriter aWriter, string aText)
{
aWriter.WriteLine(Indentation + aText);
}
}
}
``` |
221fe29c-06a8-44fd-ab8b-fa1fabc4867b | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Internal;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Runtime;
namespace Microsoft.AspNet.Hosting
{
public class Program
{
private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini";
private readonly IServiceProvider _serviceProvider;
public Program(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Main(string[] args)
{
var config = new Configuration();
if (File.Exists(HostingIniFile))
{
config.AddIniFile(HostingIniFile);
}
config.AddEnvironmentVariables();
config.AddCommandLine(args);
var host = new WebHostBuilder(_serviceProvider, config).Build();
var serverShutdown = host.Start();
var loggerFactory = host.ApplicationServices.GetRequiredService<ILoggerFactory>();
var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>();
var shutdownHandle = new ManualResetEvent(false);
appShutdownService.ShutdownRequested.Register(() =>
{
try
{
serverShutdown.Dispose();
}
catch (Exception ex)
{
var logger = loggerFactory.CreateLogger<Program>();
logger.LogError("Dispose threw an exception.", ex);
}
shutdownHandle.Set();
});
var ignored = Task.Run(() =>
{
Console.WriteLine("Started");
Console.ReadLine();
appShutdownService.RequestShutdown();
});
shutdownHandle.WaitOne();
}
}
}
```
Simplify Hosting's shutdown handling. Don't require a TTY on Unix. | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.AspNet.Hosting.Internal;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime;
namespace Microsoft.AspNet.Hosting
{
public class Program
{
private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini";
private readonly IServiceProvider _serviceProvider;
public Program(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Main(string[] args)
{
var config = new Configuration();
if (File.Exists(HostingIniFile))
{
config.AddIniFile(HostingIniFile);
}
config.AddEnvironmentVariables();
config.AddCommandLine(args);
var host = new WebHostBuilder(_serviceProvider, config).Build();
using (host.Start())
{
var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>();
Console.CancelKeyPress += delegate { appShutdownService.RequestShutdown(); };
appShutdownService.ShutdownRequested.WaitHandle.WaitOne();
}
}
}
}
``` |
90f56c6a-2059-4374-9a66-3e30964ad1b5 | {
"language": "C#"
} | ```c#
using System;
using Serilog.Events;
namespace Serilog
{
/// <summary>
/// Extension method 'ForContext' for ILogger.
/// </summary>
public static class ForContextExtension
{
/// <summary>
/// Create a logger that enriches log events with the specified property based on log event level.
/// </summary>
/// <typeparam name="TValue"> The type of the property value. </typeparam>
/// <param name="logger">The logger</param>
/// <param name="level">The log event level used to determine if log is enriched with property.</param>
/// <param name="propertyName">The name of the property. Must be non-empty.</param>
/// <param name="value">The property value.</param>
/// <param name="destructureObjects">If true, the value will be serialized as a structured
/// object if possible; if false, the object will be recorded as a scalar or simple array.</param>
/// <returns>A logger that will enrich log events as specified.</returns>
/// <returns></returns>
public static ILogger ForContext<TValue>(
this ILogger logger,
LogEventLevel level,
string propertyName,
TValue value,
bool destructureObjects = false)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
return !logger.IsEnabled(level)
? logger
: logger.ForContext(propertyName, value, destructureObjects);
}
}
}
```
Simplify ternary operation (not !) | ```c#
using System;
using Serilog.Events;
namespace Serilog
{
/// <summary>
/// Extension method 'ForContext' for ILogger.
/// </summary>
public static class ForContextExtension
{
/// <summary>
/// Create a logger that enriches log events with the specified property based on log event level.
/// </summary>
/// <typeparam name="TValue"> The type of the property value. </typeparam>
/// <param name="logger">The logger</param>
/// <param name="level">The log event level used to determine if log is enriched with property.</param>
/// <param name="propertyName">The name of the property. Must be non-empty.</param>
/// <param name="value">The property value.</param>
/// <param name="destructureObjects">If true, the value will be serialized as a structured
/// object if possible; if false, the object will be recorded as a scalar or simple array.</param>
/// <returns>A logger that will enrich log events as specified.</returns>
/// <returns></returns>
public static ILogger ForContext<TValue>(
this ILogger logger,
LogEventLevel level,
string propertyName,
TValue value,
bool destructureObjects = false)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
return logger.IsEnabled(level)
? logger.ForContext(propertyName, value, destructureObjects)
: logger;
}
}
}
``` |
159fb694-1d2d-42a1-957a-3d7408e3430c | {
"language": "C#"
} | ```c#
// 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.Extensions;
using osu.Framework.Platform;
namespace osu.Framework.Input
{
public class GameWindowTextInput : ITextInputSource
{
private readonly IWindow window;
private string pending = string.Empty;
public GameWindowTextInput(IWindow window)
{
this.window = window;
}
protected virtual void HandleKeyPress(object sender, osuTK.KeyPressEventArgs e) => pending += e.KeyChar;
public bool ImeActive => false;
public string GetPendingText()
{
try
{
return pending;
}
finally
{
pending = string.Empty;
}
}
public void Deactivate(object sender)
{
window.AsLegacyWindow().KeyPress -= HandleKeyPress;
}
public void Activate(object sender)
{
window.AsLegacyWindow().KeyPress += HandleKeyPress;
}
private void imeCompose()
{
//todo: implement
OnNewImeComposition?.Invoke(string.Empty);
}
private void imeResult()
{
//todo: implement
OnNewImeResult?.Invoke(string.Empty);
}
public event Action<string> OnNewImeComposition;
public event Action<string> OnNewImeResult;
}
}
```
Fix text input for SDL | ```c#
// 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.Extensions;
using osu.Framework.Platform;
namespace osu.Framework.Input
{
public class GameWindowTextInput : ITextInputSource
{
private readonly IWindow window;
private string pending = string.Empty;
public GameWindowTextInput(IWindow window)
{
this.window = window;
}
protected virtual void HandleKeyPress(object sender, osuTK.KeyPressEventArgs e) => pending += e.KeyChar;
protected virtual void HandleKeyTyped(char c) => pending += c;
public bool ImeActive => false;
public string GetPendingText()
{
try
{
return pending;
}
finally
{
pending = string.Empty;
}
}
public void Deactivate(object sender)
{
if (window is Window win)
win.KeyTyped -= HandleKeyTyped;
else
window.AsLegacyWindow().KeyPress -= HandleKeyPress;
}
public void Activate(object sender)
{
if (window is Window win)
win.KeyTyped += HandleKeyTyped;
else
window.AsLegacyWindow().KeyPress += HandleKeyPress;
}
private void imeCompose()
{
//todo: implement
OnNewImeComposition?.Invoke(string.Empty);
}
private void imeResult()
{
//todo: implement
OnNewImeResult?.Invoke(string.Empty);
}
public event Action<string> OnNewImeComposition;
public event Action<string> OnNewImeResult;
}
}
``` |
21920554-8f83-4d51-9ac2-95ef6e360be3 | {
"language": "C#"
} | ```c#
namespace Albireo.Otp.ConsoleApplication
{
using System;
public static class Program
{
public static void Main()
{
Console.Title = "One-Time Password Generator";
}
}
}
```
Fix console application window title | ```c#
namespace Albireo.Otp.ConsoleApplication
{
using System;
public static class Program
{
public static void Main()
{
Console.Title = "C# One-Time Password";
}
}
}
``` |
c246b70b-db2c-4d8c-b69f-20144102fa30 | {
"language": "C#"
} | ```c#
using System;
using System.Security.Cryptography;
using Algorithms.Utils;
namespace Algorithms.Search
{
public class BinarySearch
{
public static int IndexOf<T>(T[] a, T v) where T: IComparable<T>
{
var lo = 0;
var hi = a.Length - 1;
int comparison(T a1, T a2) => a1.CompareTo(a2);
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (SortUtil.IsLessThan(a[mid], v, comparison)) lo = mid;
else if (SortUtil.IsGreaterThan(a[mid], v, comparison)) hi = mid;
}
return -1;
}
}
}```
Fix the bug in the binary search | ```c#
using System;
using System.Security.Cryptography;
using Algorithms.Utils;
namespace Algorithms.Search
{
public class BinarySearch
{
public static int IndexOf<T>(T[] a, T v) where T: IComparable<T>
{
var lo = 0;
var hi = a.Length - 1;
int comparison(T a1, T a2) => a1.CompareTo(a2);
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (SortUtil.IsLessThan(a[mid], v, comparison)) lo = mid+1;
else if (SortUtil.IsGreaterThan(a[mid], v, comparison)) hi = mid - 1;
else return mid;
}
return -1;
}
}
}``` |
54d8489c-018b-4493-87cb-000361891b8f | {
"language": "C#"
} | ```c#
// -----------------------------------------------------------------------
// <copyright file="ReviewController.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview.Controllers
{
using System.Web.Http;
using GitReview.Models;
/// <summary>
/// Provides an API for working with reviews.
/// </summary>
public class ReviewController : ApiController
{
/// <summary>
/// Gets the specified review.
/// </summary>
/// <param name="id">The ID of the review to find.</param>
/// <returns>The specified review.</returns>
[Route("reviews/{id}")]
public object Get(string id)
{
return new
{
Reviews = new[]
{
new Review { Id = id },
}
};
}
}
}
```
Read reviews from the database. | ```c#
// -----------------------------------------------------------------------
// <copyright file="ReviewController.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview.Controllers
{
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
/// <summary>
/// Provides an API for working with reviews.
/// </summary>
public class ReviewController : ApiController
{
/// <summary>
/// Gets the specified review.
/// </summary>
/// <param name="id">The ID of the review to find.</param>
/// <returns>The specified review.</returns>
[Route("reviews/{id}")]
public async Task<object> Get(string id)
{
using (var ctx = new ReviewContext())
{
var review = await ctx.Reviews.FindAsync(id);
if (review == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new
{
Reviews = new[] { review },
};
}
}
}
}
``` |
24a33d9a-a98c-4c76-9005-aa9d2ea9c158 | {
"language": "C#"
} | ```c#
using System;
using System.Windows.Forms;
namespace CSharpEx.Forms
{
/// <summary>
/// Control extensions
/// </summary>
public static class ControlEx
{
/// <summary>
/// Invoke action if Invoke is requiered.
/// </summary>
public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
}
}
```
Set DoubleBuffered property via reflection | ```c#
using System;
using System.Windows.Forms;
namespace CSharpEx.Forms
{
/// <summary>
/// Control extensions
/// </summary>
public static class ControlEx
{
/// <summary>
/// Invoke action if Invoke is requiered.
/// </summary>
public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
/// <summary>
/// Set DoubleBuffered property using reflection.
/// Call this in the constructor just after InitializeComponent().
/// </summary>
public static void SetDoubleBuffered(this Control control, bool enabled)
{
typeof (Control).InvokeMember("DoubleBuffered",
System.Reflection.BindingFlags.SetProperty |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic,
null,
control,
new object[] {enabled});
}
}
}
``` |
61da026f-8d84-4d5d-9440-de9085914b4d | {
"language": "C#"
} | ```c#
using System;
using DAQ.Environment;
namespace DAQ.HAL
{
/// <summary>
/// This class represents a GPIB controlled Gigatronics 7100 arbitrary waveform generator. It conforms to the Synth
/// interface.
/// </summary>
class Gigatronics7100Synth : Synth
{
public Gigatronics7100Synth(String visaAddress)
: base(visaAddress)
{ }
override public double Frequency
{
set
{
if (!Environs.Debug) Write("CW" + value + "MZ"); // the value is entered in MHz
}
}
public override double Amplitude
{
set
{
if (!Environs.Debug) Write("PL" + value + "DM"); // the value is entered in MHz
} // do nothing
}
public override double DCFM
{
set { } // do nothing
}
public override bool DCFMEnabled
{
set { } // do nothing
}
public override bool Enabled
{
set { } // do nothing
}
public double PulseDuration
{
set
{
if (!Environs.Debug)
{
Write("PM4");
Write("PW" + value + "US");
}
}
}
}
}
```
Add remote rf enable function | ```c#
using System;
using DAQ.Environment;
namespace DAQ.HAL
{
/// <summary>
/// This class represents a GPIB controlled Gigatronics 7100 arbitrary waveform generator. It conforms to the Synth
/// interface.
/// </summary>
public class Gigatronics7100Synth : Synth
{
public Gigatronics7100Synth(String visaAddress)
: base(visaAddress)
{ }
override public double Frequency
{
set
{
if (!Environs.Debug) Write("CW" + value + "MZ"); // the value is entered in MHz
}
}
public override double Amplitude
{
set
{
if (!Environs.Debug) Write("PL" + value + "DM"); // the value is entered in dBm
} // do nothing
}
public override double DCFM
{
set { } // do nothing
}
public override bool DCFMEnabled
{
set { } // do nothing
}
public override bool Enabled
{
set
{
if (value)
{
if (!Environs.Debug) Write("RF1");
}
else
{
if (!Environs.Debug) Write("RF0");
}
}
}
public double PulseDuration
{
set
{
if (!Environs.Debug)
{
Write("PM4");
Write("PW" + value + "US");
}
}
}
}
}
``` |
8b8ecb7d-fecc-44b7-91dd-9a3754c9726d | {
"language": "C#"
} | ```c#
using System;
using System.Windows.Forms;
namespace ProtoScript.Dialogs
{
class SelectBundleDialog : IDisposable
{
private const string kResourceBundleExtension = ".bun";
private readonly OpenFileDialog m_fileDialog;
public SelectBundleDialog()
{
m_fileDialog = new OpenFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Filter = "Bundle files|*" + kResourceBundleExtension
};
}
public void ShowDialog()
{
if (m_fileDialog.ShowDialog() == DialogResult.OK)
FileName = m_fileDialog.FileName;
}
public string FileName { get; private set; }
public void Dispose()
{
m_fileDialog.Dispose();
}
}
}
```
Select Bundle dialog looks for zip files | ```c#
using System;
using System.Windows.Forms;
namespace ProtoScript.Dialogs
{
class SelectBundleDialog : IDisposable
{
private const string kResourceBundleExtension = ".zip";
private readonly OpenFileDialog m_fileDialog;
public SelectBundleDialog()
{
m_fileDialog = new OpenFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Filter = "Zip files|*" + kResourceBundleExtension
};
}
public void ShowDialog()
{
if (m_fileDialog.ShowDialog() == DialogResult.OK)
FileName = m_fileDialog.FileName;
}
public string FileName { get; private set; }
public void Dispose()
{
m_fileDialog.Dispose();
}
}
}
``` |
7874b54a-0de7-4d54-a91f-3653bbd38dbc | {
"language": "C#"
} | ```c#
namespace ExampleGenerator
{
using OxyPlot;
public static class BindingExamples
{
[Export(@"BindingExamples\Example1")]
public static PlotModel Example1()
{
return null;
}
}
}```
Fix example that caused exception | ```c#
namespace ExampleGenerator
{
using OxyPlot;
public static class BindingExamples
{
[Export(@"BindingExamples\Example1")]
public static PlotModel Example1()
{
return new PlotModel { Title = "TODO" };
}
}
}``` |
51b01828-5c1b-4092-93db-0ab7c2558fc4 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace GoldenAnvil.Utility
{
public static class EnumerableUtility
{
public static IEnumerable<T> Append<T>(this IEnumerable<T> items, T value)
{
foreach (T item in items)
yield return item;
yield return value;
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items)
{
return items ?? Enumerable.Empty<T>();
}
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items)
{
return items.Where(x => x != null);
}
public static IEnumerable<T> Enumerate<T>(params T[] items)
{
return items;
}
}
}
```
Add AsReadOnlyList; Remove obsolete method | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace GoldenAnvil.Utility
{
public static class EnumerableUtility
{
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items)
{
return items ?? Enumerable.Empty<T>();
}
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items)
{
return items.Where(x => x != null);
}
public static IEnumerable<T> Enumerate<T>(params T[] items)
{
return items;
}
public static IReadOnlyList<T> AsReadOnlyList<T>(this IEnumerable<T> items)
{
return items as IReadOnlyList<T> ??
(items is IList<T> list ? (IReadOnlyList<T>) new ReadOnlyListAdapter<T>(list) : items.ToList().AsReadOnly());
}
private sealed class ReadOnlyListAdapter<T> : IReadOnlyList<T>
{
public ReadOnlyListAdapter(IList<T> list) => m_list = list ?? throw new ArgumentNullException(nameof(list));
public int Count => m_list.Count;
public T this[int index] => m_list[index];
public IEnumerator<T> GetEnumerator() => m_list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) m_list).GetEnumerator();
readonly IList<T> m_list;
}
}
}
``` |
b96b152e-e6c1-4923-b50b-13ecfd897cc6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EvoNet.Controls;
using Graph;
using EvoNet.Map;
namespace EvoNet.Forms
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
foodValueList.Color = Color.Green;
FoodGraph.Add("Food", foodValueList);
evoSimControl1.OnUpdate += EvoSimControl1_OnUpdate;
}
private void EvoSimControl1_OnUpdate(Microsoft.Xna.Framework.GameTime obj)
{
}
GraphValueList foodValueList = new GraphValueList();
int lastFoodIndex = 0;
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Close();
}
private TileMap TileMap
{
get
{
return evoSimControl1.sim.TileMap;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
float Value = TileMap.FoodRecord.Skip(lastFoodIndex).Average();
lastFoodIndex = TileMap.FoodRecord.Count;
foodValueList.Add(new GraphTimeDoubleValue(DateTime.Now, Value));
FoodGraph.Refresh();
}
}
}
```
Check for empty array on food record | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EvoNet.Controls;
using Graph;
using EvoNet.Map;
namespace EvoNet.Forms
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
foodValueList.Color = Color.Green;
FoodGraph.Add("Food", foodValueList);
evoSimControl1.OnUpdate += EvoSimControl1_OnUpdate;
}
private void EvoSimControl1_OnUpdate(Microsoft.Xna.Framework.GameTime obj)
{
}
GraphValueList foodValueList = new GraphValueList();
int lastFoodIndex = 0;
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Close();
}
private TileMap TileMap
{
get
{
return evoSimControl1.sim.TileMap;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (TileMap.FoodRecord.Count > lastFoodIndex)
{
float Value = TileMap.FoodRecord.Skip(lastFoodIndex).Average();
lastFoodIndex = TileMap.FoodRecord.Count;
foodValueList.Add(new GraphTimeDoubleValue(DateTime.Now, Value));
FoodGraph.Refresh();
}
}
}
}
``` |
8584dea3-af99-497c-8cc7-02961a080c08 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Threading;
namespace RedGate.AppHost.Client
{
internal class ParentProcessMonitor
{
private readonly Action m_OnParentMissing;
private readonly int m_PollingIntervalInSeconds;
private Thread m_PollingThread;
public ParentProcessMonitor(Action onParentMissing, int pollingIntervalInSeconds = 10)
{
if (onParentMissing == null)
{
throw new ArgumentNullException("onParentMissing");
}
m_OnParentMissing = onParentMissing;
m_PollingIntervalInSeconds = pollingIntervalInSeconds;
}
public void Start()
{
m_PollingThread = new Thread(PollForParentProcess);
m_PollingThread.Start();
}
private void PollForParentProcess()
{
var currentProcess = Process.GetCurrentProcess();
var parentProcessId = currentProcess.GetParentProcessId();
try
{
while (true)
{
Process.GetProcessById(parentProcessId);
Thread.Sleep(m_PollingIntervalInSeconds * 1000);
}
}
catch
{
m_OnParentMissing();
}
}
}
}
```
Replace the polling with an event handler | ```c#
using System;
using System.Diagnostics;
using System.Runtime.Remoting.Channels;
using System.Threading;
namespace RedGate.AppHost.Client
{
internal class ParentProcessMonitor
{
private readonly Action m_OnParentMissing;
public ParentProcessMonitor(Action onParentMissing)
{
if (onParentMissing == null)
{
throw new ArgumentNullException("onParentMissing");
}
m_OnParentMissing = onParentMissing;
}
public void Start()
{
var currentProcess = Process.GetCurrentProcess();
var parentProcessId = currentProcess.GetParentProcessId();
var parentProcess = Process.GetProcessById(parentProcessId);
parentProcess.EnableRaisingEvents = true;
parentProcess.Exited += (sender, e) => { m_OnParentMissing(); };
}
}
}
``` |
c92da4e2-8582-4715-ac39-8b41c701cc9b | {
"language": "C#"
} | ```c#
@model IEnumerable<alert_roster.web.Models.Message>
@{
ViewBag.Title = "Messages";
}
<div class="jumbotron">
<h1>@ViewBag.Title</h1>
</div>
@foreach (var message in Model)
{
<div class="row">
<div class="col-md-4">
<fieldset>
<legend>
<script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script>
</legend>
@message.Content
</fieldset>
</div>
</div>
}```
Tweak some of the list page formatting | ```c#
@model IEnumerable<alert_roster.web.Models.Message>
@{
ViewBag.Title = "Notices";
}
<h2>@ViewBag.Title</h2>
@foreach (var message in Model)
{
<div class="row">
<div class="col-md-5">
<fieldset>
<legend>
Posted <script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script>
</legend>
@message.Content
</fieldset>
</div>
</div>
}``` |
1f5a876a-561a-4cb0-904a-4560c0aad190 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Game.Configuration;
using osu.Game.Updater;
namespace osu.Game.Overlays.Settings.Sections.General
{
public class UpdateSettings : SettingsSubsection
{
[Resolved(CanBeNull = true)]
private UpdateManager updateManager { get; set; }
protected override string Header => "Updates";
[BackgroundDependencyLoader]
private void load(Storage storage, OsuConfigManager config, OsuGameBase game)
{
Add(new SettingsEnumDropdown<ReleaseStream>
{
LabelText = "Release stream",
Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream),
});
// We should only display the button for UpdateManagers that do update the client
if (updateManager != null && updateManager.CanPerformUpdate)
{
Add(new SettingsButton
{
Text = "Check for updates",
Action = updateManager.CheckForUpdate,
Enabled = { Value = game.IsDeployedBuild }
});
}
if (RuntimeInfo.IsDesktop)
{
Add(new SettingsButton
{
Text = "Open osu! folder",
Action = storage.OpenInNativeExplorer,
});
}
}
}
}
```
Use null-conditional operator when checking against UpdateManager | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Game.Configuration;
using osu.Game.Updater;
namespace osu.Game.Overlays.Settings.Sections.General
{
public class UpdateSettings : SettingsSubsection
{
[Resolved(CanBeNull = true)]
private UpdateManager updateManager { get; set; }
protected override string Header => "Updates";
[BackgroundDependencyLoader]
private void load(Storage storage, OsuConfigManager config, OsuGameBase game)
{
Add(new SettingsEnumDropdown<ReleaseStream>
{
LabelText = "Release stream",
Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream),
});
// We should only display the button for UpdateManagers that do update the client
if (updateManager?.CanPerformUpdate == true)
{
Add(new SettingsButton
{
Text = "Check for updates",
Action = updateManager.CheckForUpdate,
Enabled = { Value = game.IsDeployedBuild }
});
}
if (RuntimeInfo.IsDesktop)
{
Add(new SettingsButton
{
Text = "Open osu! folder",
Action = storage.OpenInNativeExplorer,
});
}
}
}
}
``` |
170baf7c-3071-48b4-a80c-5ac1cbde7b24 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ZWCloud.DWriteCairo;
namespace DWriteCairoTest
{
[TestClass]
public class UnitTestTextFromat
{
[TestMethod]
public void TestTextFormat()
{
const string fontFamilyName = "SimSun";
const FontWeight fontWeight = FontWeight.Bold;
const FontStyle fontStyle = FontStyle.Normal;
const FontStretch fontStretch = FontStretch.Normal;
const float fontSize = 32f;
var textFormat = DWriteCairo.CreateTextFormat(fontFamilyName, fontWeight, fontStyle, fontStretch, fontSize);
Assert.IsNotNull(textFormat, "TextFormat creating failed.");
Assert.AreEqual(fontFamilyName, textFormat.FontFamilyName);
Assert.AreEqual(fontWeight, textFormat.FontWeight);
Assert.AreEqual(fontStyle, textFormat.FontStyle);
Assert.AreEqual(fontStretch, textFormat.FontStretch);
Assert.AreEqual(fontSize, textFormat.FontSize);
textFormat.TextAlignment = TextAlignment.Center;
Assert.AreEqual(textFormat.TextAlignment, TextAlignment.Center);
}
}
}
```
Add a test for text alignment. | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ZWCloud.DWriteCairo;
namespace DWriteCairoTest
{
[TestClass]
public class UnitTestTextFromat
{
[TestMethod]
public void TestTextFormat()
{
const string fontFamilyName = "SimSun";
const FontWeight fontWeight = FontWeight.Bold;
const FontStyle fontStyle = FontStyle.Normal;
const FontStretch fontStretch = FontStretch.Normal;
const float fontSize = 32f;
var textFormat = DWriteCairo.CreateTextFormat(fontFamilyName, fontWeight, fontStyle, fontStretch, fontSize);
Assert.IsNotNull(textFormat, "TextFormat creating failed.");
Assert.AreEqual(fontFamilyName, textFormat.FontFamilyName);
Assert.AreEqual(fontWeight, textFormat.FontWeight);
Assert.AreEqual(fontStyle, textFormat.FontStyle);
Assert.AreEqual(fontStretch, textFormat.FontStretch);
Assert.AreEqual(fontSize, textFormat.FontSize);
textFormat.TextAlignment = TextAlignment.Center;
Assert.AreEqual(textFormat.TextAlignment, TextAlignment.Center);
textFormat.TextAlignment = TextAlignment.Leading;
Assert.AreEqual(textFormat.TextAlignment, TextAlignment.Leading);
}
}
}
``` |
cb0664c0-8db8-4f01-bd9a-49431411d946 | {
"language": "C#"
} | ```c#
@model dynamic
@{
ViewBag.Title = "login";
}
<h2>Log in!</h2>
<form method="POST">
@Html.AntiForgeryToken()
Username: @Html.TextBox("Username")<br/>
Password: @Html.Password("Password")<br/>
Remember me @Html.CheckBox("RememberMe")<br />
<input type="submit" value="Log in"/>
</form>```
Tidy of the login page | ```c#
@model dynamic
@{
ViewBag.Title = "login";
}
<h2>Log in!</h2>
<form method="POST" role="form" id="loginForm" name="loginForm">
@Html.AntiForgeryToken()
<div class="form-group" ng-class="{'has-error': addForm.name.$invalid && addForm.name.$pristine && submitted}">
<label class="col-sm-2 control-label" for="Username">Username</label>
@Html.TextBox("Username", "", new { required = "required", @class = "form-control" })
<span class="help-block" ng-show="loginForm.Username.$error.required && loginform.Username.$pristine">Required</span>
</div>
<div class="form-group" ng-class="{'has-error': addForm.name.$invalid && addForm.name.$pristine && submitted}">
<label class="col-sm-2 control-label" for="Password">Password</label>
@Html.Password("Password", "", new { required = "required", @class = "form-control" })
<span class="help-block" ng-show="loginForm.Password.$error.required && loginform.Password.$pristine">Required</span>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
@Html.CheckBox("RememberMe") Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" type="submit">Log in</button>
</div>
</div>
</form>``` |
08f17aff-10b1-4323-aafe-aae12d77fed8 | {
"language": "C#"
} | ```c#
using System;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Scripting.TagScript;
using Premotion.Mansion.Web.Portal.Service;
namespace Premotion.Mansion.Web.Portal.ScriptTags
{
/// <summary>
/// Renders the specified block.
/// </summary>
[ScriptTag(Constants.TagNamespaceUri, "renderBlock")]
public class RenderBlockTag : ScriptTag
{
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="context"></param>
protected override void DoExecute(IMansionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var blockProperties = GetAttributes(context);
string targetField;
if (!blockProperties.TryGetAndRemove(context, "targetField", out targetField) || string.IsNullOrEmpty(targetField))
throw new InvalidOperationException("The target attribute is manditory");
var portalService = context.Nucleus.ResolveSingle<IPortalService>();
portalService.RenderBlockToOutput(context, blockProperties, targetField);
}
#endregion
}
}```
Use AttributeNullException instead of an InvalidOperationException. | ```c#
using System;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Scripting.TagScript;
using Premotion.Mansion.Web.Portal.Service;
namespace Premotion.Mansion.Web.Portal.ScriptTags
{
/// <summary>
/// Renders the specified block.
/// </summary>
[ScriptTag(Constants.TagNamespaceUri, "renderBlock")]
public class RenderBlockTag : ScriptTag
{
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="context"></param>
protected override void DoExecute(IMansionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var blockProperties = GetAttributes(context);
string targetField;
if (!blockProperties.TryGetAndRemove(context, "targetField", out targetField) || string.IsNullOrEmpty(targetField))
throw new AttributeNullException("targetField", this);
var portalService = context.Nucleus.ResolveSingle<IPortalService>();
portalService.RenderBlockToOutput(context, blockProperties, targetField);
}
#endregion
}
}``` |
96729444-3049-4da3-9a95-70e9e44f7fd8 | {
"language": "C#"
} | ```c#
namespace Tools.Test.Database.Model.Tasks
{
public class DropDatabaseTask : DatabaseTask
{
private readonly string _connectionString;
public DropDatabaseTask(string connectionString)
: base(connectionString)
{
_connectionString = connectionString;
}
public override bool Execute()
{
System.Data.Entity.Database.Delete(_connectionString);
return true;
}
}
}
```
Change back to use EF initializer to drop db | ```c#
using System.Data.Entity;
using Infrastructure.DataAccess;
namespace Tools.Test.Database.Model.Tasks
{
public class DropDatabaseTask : DatabaseTask
{
private readonly string _connectionString;
public DropDatabaseTask(string connectionString)
: base(connectionString)
{
_connectionString = connectionString;
}
public override bool Execute()
{
System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseAlways<KitosContext>());
using (var context = CreateKitosContext())
{
context.Database.Initialize(true);
}
return true;
}
}
}
``` |
fb181c55-31ae-498d-a85d-2d05a8db1e7a | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="ViewModelBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Base class used to create ViewModel objects that contain the Model object and related elements.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csla.Web.Mvc
{
/// <summary>
/// Base class used to create ViewModel objects that
/// contain the Model object and related elements.
/// </summary>
/// <typeparam name="T">Type of the Model object.</typeparam>
public abstract class ViewModelBase<T> : IViewModel where T : class
{
object IViewModel.ModelObject
{
get { return ModelObject; }
set { ModelObject = (T)value; }
}
/// <summary>
/// Gets or sets the Model object.
/// </summary>
public T ModelObject { get; set; }
}
}
```
Add Save method. bugid: 928 | ```c#
//-----------------------------------------------------------------------
// <copyright file="ViewModelBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Base class used to create ViewModel objects that contain the Model object and related elements.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace Csla.Web.Mvc
{
/// <summary>
/// Base class used to create ViewModel objects that
/// contain the Model object and related elements.
/// </summary>
/// <typeparam name="T">Type of the Model object.</typeparam>
public abstract class ViewModelBase<T> : IViewModel where T : class
{
object IViewModel.ModelObject
{
get { return ModelObject; }
set { ModelObject = (T)value; }
}
/// <summary>
/// Gets or sets the Model object.
/// </summary>
public T ModelObject { get; set; }
/// <summary>
/// Saves the current Model object if the object
/// implements Csla.Core.ISavable.
/// </summary>
/// <param name="modelState">Controller's ModelState object.</param>
/// <returns>true if the save succeeds.</returns>
public virtual bool Save(ModelStateDictionary modelState, bool forceUpdate)
{
try
{
var savable = ModelObject as Csla.Core.ISavable;
if (savable == null)
throw new InvalidOperationException("Save");
ModelObject = (T)savable.Save(forceUpdate);
return true;
}
catch (Csla.DataPortalException ex)
{
if (ex.BusinessException != null)
modelState.AddModelError("", ex.BusinessException.Message);
else
modelState.AddModelError("", ex.Message);
return false;
}
catch (Exception ex)
{
modelState.AddModelError("", ex.Message);
return false;
}
}
}
}
``` |
969f76e3-31ea-4cc6-9d72-c4b4aa10fe46 | {
"language": "C#"
} | ```c#
using System;
using XPNet;
namespace XPNet.CLR.Template
{
[XPlanePlugin(
name: "My Plugin",
signature: "you.plugins.name",
description: "Describe your plugin here."
)]
public class Plugin : IXPlanePlugin
{
private readonly IXPlaneApi m_api;
public Plugin(IXPlaneApi api)
{
m_api = api ?? throw new ArgumentNullException("api");
}
public void Dispose()
{
// Clean up whatever we attached / registered for / etc.
}
public void Enable()
{
// Called when the plugin is enabled in X-Plane.
}
public void Disable()
{
// Called when the plugin is disabled in X-Plane.
}
}
}
```
Use nameof on argument check in the template project. | ```c#
using System;
using XPNet;
namespace XPNet.CLR.Template
{
[XPlanePlugin(
name: "My Plugin",
signature: "you.plugins.name",
description: "Describe your plugin here."
)]
public class Plugin : IXPlanePlugin
{
private readonly IXPlaneApi m_api;
public Plugin(IXPlaneApi api)
{
m_api = api ?? throw new ArgumentNullException(nameof(api));
}
public void Dispose()
{
// Clean up whatever we attached / registered for / etc.
}
public void Enable()
{
// Called when the plugin is enabled in X-Plane.
}
public void Disable()
{
// Called when the plugin is disabled in X-Plane.
}
}
}
``` |
06349dd4-aafa-45eb-8c23-2a796dd76451 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class PlainTextOutputSpeech : IOutputSpeech
{
/// <summary>
/// A string containing the type of output speech to render. Valid types are:
/// - "PlainText" - Indicates that the output speech is defined as plain text.
/// - "SSML" - Indicates that the output speech is text marked up with SSML.
/// </summary>
[JsonProperty("type")]
[JsonRequired]
public string Type
{
get { return "PlainText"; }
}
/// <summary>
/// A string containing the speech to render to the user. Use this when type is "PlainText"
/// </summary>
[JsonRequired]
[JsonProperty("text")]
public string Text { get; set; }
}
}```
Comment removal in prep for newer commenting | ```c#
using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class PlainTextOutputSpeech : IOutputSpeech
{
[JsonProperty("type")]
[JsonRequired]
public string Type
{
get { return "PlainText"; }
}
[JsonRequired]
[JsonProperty("text")]
public string Text { get; set; }
}
}``` |
d6014ea7-5571-4078-b111-6b72167fa98c | {
"language": "C#"
} | ```c#
using System.IO;
namespace Nustache.Core
{
public class FileSystemTemplateLocator
{
private readonly string _extension;
private readonly string _directory;
public FileSystemTemplateLocator(string extension, string directory)
{
_extension = extension;
_directory = directory;
}
public Template GetTemplate(string name)
{
string path = Path.Combine(_directory, name + _extension);
if (File.Exists(path))
{
string text = File.ReadAllText(path);
var reader = new StringReader(text);
var template = new Template();
template.Load(reader);
return template;
}
return null;
}
}
}```
Use an array of directories instead of just one. | ```c#
using System.IO;
namespace Nustache.Core
{
public class FileSystemTemplateLocator
{
private readonly string _extension;
private readonly string[] _directories;
public FileSystemTemplateLocator(string extension, params string[] directories)
{
_extension = extension;
_directories = directories;
}
public Template GetTemplate(string name)
{
foreach (var directory in _directories)
{
var path = Path.Combine(directory, name + _extension);
if (File.Exists(path))
{
var text = File.ReadAllText(path);
var reader = new StringReader(text);
var template = new Template();
template.Load(reader);
return template;
}
}
return null;
}
}
}``` |
310960ad-7116-4c4c-95c5-c047974b758e | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Filter;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Rulesets.Mania
{
public class ManiaFilterCriteria : IRulesetFilterCriteria
{
private FilterCriteria.OptionalRange<float> keys;
public bool Matches(BeatmapInfo beatmapInfo)
{
return !keys.HasFilter || (beatmapInfo.Ruleset.OnlineID == new ManiaRuleset().LegacyID && keys.IsInRange(ManiaBeatmapConverter.GetColumnCountForNonConvert(beatmapInfo)));
}
public bool TryParseCustomKeywordCriteria(string key, Operator op, string value)
{
switch (key)
{
case "key":
case "keys":
return FilterQueryParser.TryUpdateCriteriaRange(ref keys, op, value);
}
return false;
}
}
}
```
Remove the nullable disable annotation in the mania ruleset. | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Filter;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Rulesets.Mania
{
public class ManiaFilterCriteria : IRulesetFilterCriteria
{
private FilterCriteria.OptionalRange<float> keys;
public bool Matches(BeatmapInfo beatmapInfo)
{
return !keys.HasFilter || (beatmapInfo.Ruleset.OnlineID == new ManiaRuleset().LegacyID && keys.IsInRange(ManiaBeatmapConverter.GetColumnCountForNonConvert(beatmapInfo)));
}
public bool TryParseCustomKeywordCriteria(string key, Operator op, string value)
{
switch (key)
{
case "key":
case "keys":
return FilterQueryParser.TryUpdateCriteriaRange(ref keys, op, value);
}
return false;
}
}
}
``` |
fb0fbe8b-ac60-4e57-8693-2d1e8727fb70 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class SchedulerAutoremove : SchedulerTestLayer
{
public virtual void onEnter()
{
base.OnEnter();
Schedule(autoremove, 0.5f);
Schedule(tick, 0.5f);
accum = 0;
}
public override string title()
{
return "Self-remove an scheduler";
}
public override string subtitle()
{
return "1 scheduler will be autoremoved in 3 seconds. See console";
}
public void autoremove(float dt)
{
accum += dt;
CCLog.Log("Time: %f", accum);
if (accum > 3)
{
Unschedule(autoremove);
CCLog.Log("scheduler removed");
}
}
public void tick(float dt)
{
CCLog.Log("This scheduler should not be removed");
}
private float accum;
}
}
```
Fix SchedulerAutorRemove to work correctly. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class SchedulerAutoremove : SchedulerTestLayer
{
private float accum;
public override void OnEnter ()
{
base.OnEnter();
Schedule(autoremove, 0.5f);
Schedule(tick, 0.5f);
accum = 0;
}
public override string title()
{
return "Self-remove an scheduler";
}
public override string subtitle()
{
return "1 scheduler will be autoremoved in 3 seconds. See console";
}
public void autoremove(float dt)
{
accum += dt;
CCLog.Log("Time: {0}", accum);
if (accum > 3)
{
Unschedule(autoremove);
CCLog.Log("scheduler removed");
}
}
public void tick(float dt)
{
CCLog.Log("This scheduler should not be removed");
}
}
}
``` |
e89f04b4-4360-45c0-8ff6-756b56fe1625 | {
"language": "C#"
} | ```c#
/*
Copyright (C) 2018 de4dot@gmail.com
This file is part of Iced.
Iced is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Iced is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Iced. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
namespace Iced.Intel {
sealed class InstructionListDebugView {
readonly InstructionList list;
public InstructionListDebugView(InstructionList list) =>
this.list = list ?? throw new ArgumentNullException(nameof(list));
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Instruction[] Items {
get {
var instructions = new Instruction[list.Count];
list.CopyTo(instructions, 0);
return instructions;
}
}
}
}
```
Simplify debug view prop body | ```c#
/*
Copyright (C) 2018 de4dot@gmail.com
This file is part of Iced.
Iced is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Iced is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Iced. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
namespace Iced.Intel {
sealed class InstructionListDebugView {
readonly InstructionList list;
public InstructionListDebugView(InstructionList list) =>
this.list = list ?? throw new ArgumentNullException(nameof(list));
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Instruction[] Items => list.ToArray();
}
}
``` |
5904c2e4-51b1-4864-9719-361aa8354780 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.InteropServices;
using System.Windows;
using CoCo.UI;
using CoCo.UI.ViewModels;
using Microsoft.VisualStudio.Shell;
namespace CoCo
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading =true)]
[ProvideOptionPage(typeof(DialogOption), "CoCo", "CoCo", 0, 0, true)]
[Guid("b933474d-306e-434f-952d-a820c849ed07")]
public sealed class VsPackage : Package
{
}
public class DialogOption : UIElementDialogPage
{
private OptionViewModel _view;
private OptionControl _child;
protected override UIElement Child
{
get
{
if (_child != null) return _child;
_view = new OptionViewModel(new OptionProvider());
_child = new OptionControl
{
DataContext = _view
};
return _child;
}
}
protected override void OnClosed(EventArgs e)
{
_view.SaveOption();
base.OnClosed(e);
}
}
}```
Apply a saving option only at it needed. | ```c#
using System;
using System.Runtime.InteropServices;
using System.Windows;
using CoCo.UI;
using CoCo.UI.ViewModels;
using Microsoft.VisualStudio.Shell;
namespace CoCo
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideOptionPage(typeof(DialogOption), "CoCo", "CoCo", 0, 0, true)]
[Guid("b933474d-306e-434f-952d-a820c849ed07")]
public sealed class VsPackage : Package
{
}
public class DialogOption : UIElementDialogPage
{
private OptionViewModel _view;
private OptionControl _child;
protected override UIElement Child
{
get
{
if (_child != null) return _child;
_view = new OptionViewModel(new OptionProvider());
_child = new OptionControl
{
DataContext = _view
};
return _child;
}
}
protected override void OnApply(PageApplyEventArgs e)
{
if (e.ApplyBehavior == ApplyKind.Apply)
{
_view.SaveOption();
}
base.OnApply(e);
}
}
}``` |
5980b07d-7242-4f10-abaf-132e6cc87d59 | {
"language": "C#"
} | ```c#
using System;
using System.Runtime.CompilerServices;
#if NETFX_CORE
namespace HelixToolkit.UWP.Model
#else
namespace HelixToolkit.Wpf.SharpDX.Model
#endif
{
/// <summary>
/// Render order key
/// </summary>
public struct OrderKey : IComparable<OrderKey>
{
public uint Key;
public OrderKey(uint key)
{
Key = key;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OrderKey Create(ushort order, ushort materialID)
{
return new OrderKey(((uint)order << 32) | materialID);
}
public int CompareTo(OrderKey other)
{
return Key.CompareTo(other.Key);
}
}
}
```
Fix wrong render order key bit shift | ```c#
using System;
using System.Runtime.CompilerServices;
#if NETFX_CORE
namespace HelixToolkit.UWP.Model
#else
namespace HelixToolkit.Wpf.SharpDX.Model
#endif
{
/// <summary>
/// Render order key
/// </summary>
public struct OrderKey : IComparable<OrderKey>
{
public uint Key;
public OrderKey(uint key)
{
Key = key;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OrderKey Create(ushort order, ushort materialID)
{
return new OrderKey(((uint)order << 16) | materialID);
}
public int CompareTo(OrderKey other)
{
return Key.CompareTo(other.Key);
}
}
}
``` |
108cb021-b523-4563-a1e2-2e9a765224e3 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Lib.Adpcm;
using DspAdpcm.Lib.Adpcm.Formats;
using DspAdpcm.Lib.Pcm;
using DspAdpcm.Lib.Pcm.Formats;
namespace DspAdpcm.Cli
{
public static class DspAdpcmCli
{
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: dspadpcm <wavIn> <brstmOut>\n");
return 0;
}
PcmStream wave;
try
{
using (var file = new FileStream(args[0], FileMode.Open))
{
wave = new Wave(file).AudioStream;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return -1;
}
Stopwatch watch = new Stopwatch();
watch.Start();
AdpcmStream adpcm = Lib.Adpcm.Encode.PcmToAdpcmParallel(wave);
watch.Stop();
Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per millisecond.");
var brstm = new Brstm(adpcm);
using (var stream = File.Open(args[1], FileMode.Create))
foreach (var b in brstm.GetFile())
stream.WriteByte(b);
return 0;
}
}
}
```
Write directly to a FileStream when writing the output file | ```c#
using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Lib.Adpcm;
using DspAdpcm.Lib.Adpcm.Formats;
using DspAdpcm.Lib.Pcm;
using DspAdpcm.Lib.Pcm.Formats;
namespace DspAdpcm.Cli
{
public static class DspAdpcmCli
{
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: dspadpcm <wavIn> <brstmOut>\n");
return 0;
}
PcmStream wave;
try
{
using (var file = new FileStream(args[0], FileMode.Open))
{
wave = new Wave(file).AudioStream;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return -1;
}
Stopwatch watch = new Stopwatch();
watch.Start();
AdpcmStream adpcm = Lib.Adpcm.Encode.PcmToAdpcmParallel(wave);
watch.Stop();
Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per millisecond.");
var brstm = new Brstm(adpcm);
using (FileStream stream = File.Open(args[1], FileMode.Create))
{
brstm.WriteFile(stream);
}
return 0;
}
}
}
``` |
c0f117ee-53b3-4fd2-b44d-7eb7e1793cc7 | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
using Xunit;
namespace BatteryCommander.Tests
{
public class AirTableServiceTests
{
private const String AppKey = "";
private const String BaseId = "";
[Fact]
public async Task Try_Get_Records()
{
if (String.IsNullOrWhiteSpace(AppKey)) return;
// Arrange
var options = Options.Create(new AirTableSettings { AppKey = AppKey, BaseId = BaseId });
var service = new AirTableService(options);
// Act
var records = await service.GetRecords();
// Assert
Assert.NotEmpty(records);
}
}
}```
Add placeholder for testing retrieving POs | ```c#
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
using Xunit;
namespace BatteryCommander.Tests
{
public class AirTableServiceTests
{
private const String AppKey = "";
private const String BaseId = "";
[Fact]
public async Task Try_Get_Records()
{
if (String.IsNullOrWhiteSpace(AppKey)) return;
// Arrange
var options = Options.Create(new AirTableSettings { AppKey = AppKey, BaseId = BaseId });
var service = new AirTableService(options);
// Act
var records = await service.GetRecords();
// Assert
Assert.NotEmpty(records);
}
[Fact]
public async Task Get_Purchase_Order()
{
if (String.IsNullOrWhiteSpace(AppKey)) return;
// Arrange
var options = Options.Create(new AirTableSettings { AppKey = AppKey, BaseId = BaseId });
var service = new AirTableService(options);
// Act
var order = await service.GetPurchaseOrder(id: "reclJK6G3IFjFlXE1");
// Assert
// TODO
}
}
}``` |
9c8f15b8-8f5d-408c-833c-f3b219caeb61 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Test.Extensions
{
public static class SemanticModelExtensions
{
public static IOperation GetOperationInternal(this SemanticModel model, SyntaxNode node)
{
return model.GetOperationInternal(node);
}
}
}
```
Address PR feedback and add comment | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Test.Extensions
{
public static class SemanticModelExtensions
{
public static IOperation GetOperationInternal(this SemanticModel model, SyntaxNode node)
{
// Invoke the GetOperationInternal API to by-pass the IOperation feature flag check.
return model.GetOperationInternal(node);
}
}
}
``` |
59a1ccda-6c78-45ba-8287-a2bfbd608ecb | {
"language": "C#"
} | ```c#
<?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Report</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
```
Fix category of revision log RSS feeds. | ```c#
<?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Log</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
``` |
fc9250e0-e53a-47e1-a489-ebf5e85d7082 | {
"language": "C#"
} | ```c#
using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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: AssemblyInformationalVersion("1.0.0-beta01")]```
Update nuget package version to beta02 | ```c#
using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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: AssemblyInformationalVersion("1.0.0-beta02")]``` |
f0f73ffb-a6ed-4775-96e0-36b877a01003 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class NoteMask : HitObjectMask
{
public NoteMask(DrawableNote note)
: base(note)
{
Scale = note.Scale;
AddInternal(new NotePiece());
note.HitObject.ColumnChanged += _ => Position = note.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Colour = colours.Yellow;
}
protected override void Update()
{
base.Update();
Size = HitObject.DrawSize;
Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft);
}
}
}
```
Update visual style to match new notes | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class NoteMask : HitObjectMask
{
public NoteMask(DrawableNote note)
: base(note)
{
Scale = note.Scale;
CornerRadius = 5;
Masking = true;
AddInternal(new NotePiece());
note.HitObject.ColumnChanged += _ => Position = note.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Colour = colours.Yellow;
}
protected override void Update()
{
base.Update();
Size = HitObject.DrawSize;
Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft);
}
}
}
``` |
6b838471-c93e-43f0-b45e-823ef68a04be | {
"language": "C#"
} | ```c#
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
namespace Glimpse
{
public static class GlimpseServerServiceCollectionExtensions
{
public static IServiceCollection RunningServer(this IServiceCollection services)
{
UseSignalR(services, null);
return services.Add(GlimpseServerServices.GetDefaultServices());
}
public static IServiceCollection RunningServer(this IServiceCollection services, IConfiguration configuration)
{
UseSignalR(services, configuration);
return services.Add(GlimpseServerServices.GetDefaultServices(configuration));
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services)
{
return services.Add(GlimpseServerServices.GetPublisherServices());
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services, IConfiguration configuration)
{
return services.Add(GlimpseServerServices.GetPublisherServices(configuration));
}
// TODO: Confirm that this is where this should be registered
private static void UseSignalR(IServiceCollection services, IConfiguration configuration)
{
// TODO: Config isn't currently being handled - https://github.com/aspnet/SignalR-Server/issues/51
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
}
}
}```
Switch around registration order for signalr | ```c#
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
namespace Glimpse
{
public static class GlimpseServerServiceCollectionExtensions
{
public static IServiceCollection RunningServer(this IServiceCollection services)
{
services.Add(GlimpseServerServices.GetDefaultServices());
UseSignalR(services, null);
return services;
}
public static IServiceCollection RunningServer(this IServiceCollection services, IConfiguration configuration)
{
services.Add(GlimpseServerServices.GetDefaultServices(configuration));
UseSignalR(services, configuration);
return services;
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services)
{
return services.Add(GlimpseServerServices.GetPublisherServices());
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services, IConfiguration configuration)
{
return services.Add(GlimpseServerServices.GetPublisherServices(configuration));
}
// TODO: Confirm that this is where this should be registered
private static void UseSignalR(IServiceCollection services, IConfiguration configuration)
{
// TODO: Config isn't currently being handled - https://github.com/aspnet/SignalR-Server/issues/51
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
}
}
}``` |
3abec1f9-7da2-4c21-b8b0-78af15594191 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using DG.Tweening;
public class GameInit : MonoBehaviour
{
void Awake()
{
// seed Random with current seconds;
Random.seed = (int)System.DateTime.Now.Ticks;
// initialize DOTween before first use.
DOTween.Init(true, true, LogBehaviour.Verbose).SetCapacity(200, 10);
DOTween.SetTweensCapacity(2000, 100);
// ignore collisions between
Physics2D.IgnoreLayerCollision(LayerID("BodyCollider"), LayerID("One-Way Platform"), true);
Physics2D.IgnoreLayerCollision(LayerID("WeaponCollider"), LayerID("Enemies"), true);
Physics2D.IgnoreLayerCollision(LayerID("WeaponCollider"), LayerID("Collectables"), true);
}
int LayerID(string layerName)
{
return LayerMask.NameToLayer(layerName);
}
}
```
Swap out IgnoreLayerCollisions for new custom version. | ```c#
using UnityEngine;
using System.Collections;
using DG.Tweening;
using Matcha.Lib;
public class GameInit : MonoBehaviour
{
void Awake()
{
// seed Random with current seconds;
Random.seed = (int)System.DateTime.Now.Ticks;
// initialize DOTween before first use.
DOTween.Init(true, true, LogBehaviour.Verbose).SetCapacity(200, 10);
DOTween.SetTweensCapacity(2000, 100);
// ignore collisions between
MLib.IgnoreLayerCollision2D("BodyCollider", "One-Way Platform", true);
MLib.IgnoreLayerCollision2D("WeaponCollider", "Enemies", true);
MLib.IgnoreLayerCollision2D("WeaponCollider", "Collectables", true);
}
}
``` |
71ad55b6-709f-4e5d-9b6d-2732484f9bd4 | {
"language": "C#"
} | ```c#
namespace SearchingBinaryTree
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class BinarySearchTree
{
public Node Root { get; private set; }
public void Add(Node node) {
if(Root!=null) {
Node current = Root;
while(current != null) {
if (current.Value > node.Value)
{
if (current.Right != null) {
current = current.Right;
continue;
}
Root.Right = node;
current = null;
}
else
{
if (current.Left != null) {
current = current.Left;
continue;
}
Root.Left = node;
current = null;
}
}
} else {
Root = node;
}
}
}
}
```
Fix operation on wrong node | ```c#
namespace SearchingBinaryTree
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class BinarySearchTree
{
public Node Root { get; private set; }
public void Add(Node node) {
if(Root!=null) {
Node current = Root;
while(current != null) {
if (current.Value > node.Value)
{
if (current.Right != null) {
current = current.Right;
continue;
}
current.Right = node;
current = null;
}
else
{
if (current.Left != null) {
current = current.Left;
continue;
}
current.Left = node;
current = null;
}
}
} else {
Root = node;
}
}
}
}
``` |
96db0ae1-4e1c-4524-a04d-71c37bc2a12a | {
"language": "C#"
} | ```c#
using System;
using IonFar.SharePoint.Migration;
using Microsoft.SharePoint.Client;
namespace TestApplication.Migrations
{
[Migration(10001)]
public class ShowTitle : IMigration
{
public void Up(ClientContext clientContext, ILogger logger)
{
clientContext.Load(clientContext.Web, w => w.Title);
clientContext.ExecuteQuery();
Console.WriteLine("Your site title is: " + clientContext.Web.Title);
}
}
}
```
Add override to test migration, so it happens every time | ```c#
using System;
using IonFar.SharePoint.Migration;
using Microsoft.SharePoint.Client;
namespace TestApplication.Migrations
{
[Migration(10001, true)]
public class ShowTitle : IMigration
{
public void Up(ClientContext clientContext, ILogger logger)
{
clientContext.Load(clientContext.Web, w => w.Title);
clientContext.ExecuteQuery();
Console.WriteLine("Your site title is: " + clientContext.Web.Title);
}
}
}
``` |
c927fae6-670a-49c7-9372-35544cd68886 | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Attribute used to indicate the name to use for a job function.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class FunctionNameAttribute : Attribute
{
private string _name;
/// <summary>
/// Initializes a new instance of the <see cref="FunctionNameAttribute"/> class with a given name.
/// </summary>
/// <param name="name">Name of the function.</param>
public FunctionNameAttribute(string name)
{
this._name = name;
}
/// <summary>
/// Gets the function name.
/// </summary>
public string Name => _name;
/// <summary>
/// Validation for name.
/// </summary>
public static readonly Regex FunctionNameValidationRegex = new Regex(@"^[a-z][a-z0-9_\-]{0,127}$(?<!^host$)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
}
```
Remove RegexOptions.Compiled for code paths executed during cold start | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Attribute used to indicate the name to use for a job function.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class FunctionNameAttribute : Attribute
{
private string _name;
/// <summary>
/// Initializes a new instance of the <see cref="FunctionNameAttribute"/> class with a given name.
/// </summary>
/// <param name="name">Name of the function.</param>
public FunctionNameAttribute(string name)
{
this._name = name;
}
/// <summary>
/// Gets the function name.
/// </summary>
public string Name => _name;
/// <summary>
/// Validation for name.
/// RegexOptions.Compiled is specifically removed as it impacts the cold start.
/// </summary>
public static readonly Regex FunctionNameValidationRegex = new Regex(@"^[a-z][a-z0-9_\-]{0,127}$(?<!^host$)", RegexOptions.IgnoreCase);
}
}
``` |
cc4bda30-517d-4cd9-8565-014d84001ef9 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AustinSite
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
```
Add Articles rep into DI scope | ```c#
using AustinSite.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AustinSite
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddScoped<ArticlesRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
``` |
cf01843b-f8d2-4dda-8dc9-5db531b8b7af | {
"language": "C#"
} | ```c#
using System;
namespace TestUtility
{
public partial class TestAssets
{
private class TestProject : ITestProject
{
private bool _disposed;
public string Name { get; }
public string BaseDirectory { get; }
public string Directory { get; }
public bool ShadowCopied { get; }
public TestProject(string name, string baseDirectory, string directory, bool shadowCopied)
{
this.Name = name;
this.BaseDirectory = baseDirectory;
this.Directory = directory;
this.ShadowCopied = shadowCopied;
}
~TestProject()
{
throw new InvalidOperationException($"{nameof(ITestProject)}.{nameof(Dispose)}() not called for {this.Name}");
}
public virtual void Dispose()
{
if (_disposed)
{
throw new InvalidOperationException($"{nameof(ITestProject)} for {this.Name} already disposed.");
}
if (this.ShadowCopied)
{
System.IO.Directory.Delete(this.BaseDirectory, recursive: true);
if (System.IO.Directory.Exists(this.BaseDirectory))
{
throw new InvalidOperationException($"{nameof(ITestProject)} directory still exists: '{this.BaseDirectory}'");
}
}
this._disposed = true;
GC.SuppressFinalize(this);
}
}
}
}
```
Add retry logic for test clean up | ```c#
using System;
using System.Threading;
namespace TestUtility
{
public partial class TestAssets
{
private class TestProject : ITestProject
{
private bool _disposed;
public string Name { get; }
public string BaseDirectory { get; }
public string Directory { get; }
public bool ShadowCopied { get; }
public TestProject(string name, string baseDirectory, string directory, bool shadowCopied)
{
this.Name = name;
this.BaseDirectory = baseDirectory;
this.Directory = directory;
this.ShadowCopied = shadowCopied;
}
~TestProject()
{
throw new InvalidOperationException($"{nameof(ITestProject)}.{nameof(Dispose)}() not called for {this.Name}");
}
public virtual void Dispose()
{
if (_disposed)
{
throw new InvalidOperationException($"{nameof(ITestProject)} for {this.Name} already disposed.");
}
if (this.ShadowCopied)
{
var retries = 0;
while (retries <= 5)
{
try
{
System.IO.Directory.Delete(this.BaseDirectory, recursive: true);
break;
}
catch
{
Thread.Sleep(1000);
retries++;
}
}
if (System.IO.Directory.Exists(this.BaseDirectory))
{
throw new InvalidOperationException($"{nameof(ITestProject)} directory still exists: '{this.BaseDirectory}'");
}
}
this._disposed = true;
GC.SuppressFinalize(this);
}
}
}
}
``` |
2ce91086-83f7-42ae-9bad-e96030e98dd8 | {
"language": "C#"
} | ```c#
/*
JustMock Lite
Copyright © 2019 Progress Software Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
public static MethodBase GetContext()
{
return resolver.GetContext();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
```
Move EditorBrowsable to class level | ```c#
/*
JustMock Lite
Copyright © 2019 Progress Software Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return resolver.GetContext();
}
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
``` |
5ccf340f-5f5d-48f7-987a-db06b2f9c2d0 | {
"language": "C#"
} | ```c#
using System;
using Faithlife.Build;
internal static class Build
{
public static int Main(string[] args) => BuildRunner.Execute(args, build =>
{
build.AddDotNetTargets(
new DotNetBuildSettings
{
DocsSettings = new DotNetDocsSettings
{
GitLogin = new GitLoginInfo("ejball", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""),
GitAuthor = new GitAuthorInfo("ejball", "ejball@gmail.com"),
SourceCodeUrl = "https://github.com/ejball/ArgsReading/tree/master/src",
},
});
build.Target("default")
.DependsOn("build");
});
}
```
Use latest xmldocmd to fix publish. | ```c#
using System;
using Faithlife.Build;
internal static class Build
{
public static int Main(string[] args) => BuildRunner.Execute(args, build =>
{
build.AddDotNetTargets(
new DotNetBuildSettings
{
DocsSettings = new DotNetDocsSettings
{
GitLogin = new GitLoginInfo("ejball", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""),
GitAuthor = new GitAuthorInfo("ejball", "ejball@gmail.com"),
SourceCodeUrl = "https://github.com/ejball/ArgsReading/tree/master/src",
ToolVersion = "1.5.1",
},
});
build.Target("default")
.DependsOn("build");
});
}
``` |
9329eec7-e53f-4b7b-aba6-89b7a79ab1a7 | {
"language": "C#"
} | ```c#
using System.Linq;
using Raven.Client.Indexes;
namespace Raven.TimeZones
{
public class ZoneShapesIndex : AbstractIndexCreationTask<ZoneShape>
{
public ZoneShapesIndex()
{
Map = shapes => from shape in shapes
select new
{
shape.Zone,
_ = SpatialGenerate("location", shape.Shape)
};
}
}
}
```
Use a lower maxTreeLevel precision | ```c#
using System.Linq;
using Raven.Abstractions.Indexing;
using Raven.Client.Indexes;
namespace Raven.TimeZones
{
public class ZoneShapesIndex : AbstractIndexCreationTask<ZoneShape>
{
public ZoneShapesIndex()
{
Map = shapes => from shape in shapes
select new
{
shape.Zone,
_ = SpatialGenerate("location", shape.Shape, SpatialSearchStrategy.GeohashPrefixTree, 3)
};
}
}
}
``` |
0219bff1-2cbc-4040-a7ce-c1dcb5123a3e | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using EnumsNET;
using Microsoft.Extensions.FileProviders;
namespace SJP.Schematic.Reporting.Html
{
internal class TemplateProvider : ITemplateProvider
{
public string GetTemplate(ReportTemplate template)
{
if (!template.IsValid())
throw new ArgumentException($"The { nameof(ReportTemplate) } provided must be a valid enum.", nameof(template));
var resource = GetResource(template);
return GetResourceAsString(resource);
}
private static IFileInfo GetResource(ReportTemplate template)
{
var templateKey = template.ToString();
var templateFileName = templateKey + TemplateExtension;
var resourceFiles = _fileProvider.GetDirectoryContents("/");
var templateResource = resourceFiles.FirstOrDefault(r => r.Name.EndsWith(templateFileName));
if (templateResource == null)
throw new NotSupportedException($"The given template: { templateKey } is not a supported template.");
return templateResource;
}
private static string GetResourceAsString(IFileInfo fileInfo)
{
if (fileInfo == null)
throw new ArgumentNullException(nameof(fileInfo));
using (var stream = new MemoryStream())
using (var reader = fileInfo.CreateReadStream())
{
reader.CopyTo(stream);
return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length);
}
}
private static readonly IFileProvider _fileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly(), Assembly.GetExecutingAssembly().GetName().Name + ".Html.Templates");
private const string TemplateExtension = ".cshtml";
}
}
```
Clean up reading templates from embedded resources. | ```c#
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using EnumsNET;
using Microsoft.Extensions.FileProviders;
namespace SJP.Schematic.Reporting.Html
{
internal class TemplateProvider : ITemplateProvider
{
public string GetTemplate(ReportTemplate template)
{
if (!template.IsValid())
throw new ArgumentException($"The { nameof(ReportTemplate) } provided must be a valid enum.", nameof(template));
var resource = GetResource(template);
return GetResourceAsString(resource);
}
private static IFileInfo GetResource(ReportTemplate template)
{
var templateKey = template.ToString();
var templateFileName = templateKey + TemplateExtension;
var resourceFiles = _fileProvider.GetDirectoryContents("/");
var templateResource = resourceFiles.FirstOrDefault(r => r.Name.EndsWith(templateFileName));
if (templateResource == null)
throw new NotSupportedException($"The given template: { templateKey } is not a supported template.");
return templateResource;
}
private static string GetResourceAsString(IFileInfo fileInfo)
{
if (fileInfo == null)
throw new ArgumentNullException(nameof(fileInfo));
using (var stream = fileInfo.CreateReadStream())
using (var reader = new StreamReader(stream))
return reader.ReadToEnd();
}
private static readonly IFileProvider _fileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly(), Assembly.GetExecutingAssembly().GetName().Name + ".Html.Templates");
private const string TemplateExtension = ".cshtml";
}
}
``` |
70a5bc5b-8b61-488e-b288-a813dd4070b6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace Alexa.NET.Management.Package
{
public enum ImportStatus
{
FAILED,
IN_PROGRESS,
SUCCEEEDED
}
}
```
Fix import status succeeded spelling error | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace Alexa.NET.Management.Package
{
public enum ImportStatus
{
FAILED,
IN_PROGRESS,
SUCCEEDED
}
}
``` |
4eba8c84-ed92-48d6-bf3d-0b41764005e5 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnlockCursorOnStart : MonoBehaviour
{
void Start()
{
Invoke("unlockCursor", .1f);
}
void unlockCursor()
{
Cursor.lockState = GameController.DefaultCursorMode;
}
}
```
Make cursor redundancy more redundant | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnlockCursorOnStart : MonoBehaviour
{
[SerializeField]
bool forceOnUpdate = true;
void Start()
{
Invoke("unlockCursor", .1f);
}
void unlockCursor()
{
Cursor.lockState = GameController.DefaultCursorMode;
}
private void Update()
{
if (Cursor.lockState != GameController.DefaultCursorMode)
Cursor.lockState = GameController.DefaultCursorMode;
}
}
``` |
2311b718-d029-4432-9fee-20f0237773f9 | {
"language": "C#"
} | ```c#
@if (Model.DiscountedPrice != Model.Price)
{
<b class="inactive-price" style="text-decoration:line-through" title="@T("Was {0}", Model.Price.ToString("c"))">@Model.Price.ToString("c")</b>
<b class="discounted-price" title="@T("Now {0}", Model.DiscountedPrice.ToString("c"))">@Model.DiscountedPrice.ToString("c")</b>
<span class="discount-comment">@Model.DiscountComment</span>
}
else
{
<b>@Model.Price.ToString("c")</b>
}
```
Use {0:c} rather than ToString("c") where possible. | ```c#
@if (Model.DiscountedPrice != Model.Price)
{
<b class="inactive-price" style="text-decoration:line-through" title="@T("Was {0:c}", Model.Price)">@Model.Price.ToString("c")</b>
<b class="discounted-price" title="@T("Now {0:c}", Model.DiscountedPrice)">@Model.DiscountedPrice.ToString("c")</b>
<span class="discount-comment">@Model.DiscountComment</span>
}
else
{
<b>@Model.Price.ToString("c")</b>
}
``` |
f15e50d4-ff2b-42b4-abba-af462771238a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
namespace RawRabbit.Common
{
public interface IBasicPropertiesProvider
{
IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null);
}
public class BasicPropertiesProvider : IBasicPropertiesProvider
{
public IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null)
{
var properties = new BasicProperties
{
MessageId = Guid.NewGuid().ToString(),
Persistent = true,
Headers = new Dictionary<string, object>
{
{ PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") },
{ PropertyHeaders.MessageType, typeof(TMessage).FullName }
}
};
custom?.Invoke(properties);
return properties;
}
}
}
```
Use Persist value from config. | ```c#
using System;
using System.Collections.Generic;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
using RawRabbit.Configuration;
namespace RawRabbit.Common
{
public interface IBasicPropertiesProvider
{
IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null);
}
public class BasicPropertiesProvider : IBasicPropertiesProvider
{
private readonly RawRabbitConfiguration _config;
public BasicPropertiesProvider(RawRabbitConfiguration config)
{
_config = config;
}
public IBasicProperties GetProperties<TMessage>(Action<IBasicProperties> custom = null)
{
var properties = new BasicProperties
{
MessageId = Guid.NewGuid().ToString(),
Persistent = _config.PersistentDeliveryMode,
Headers = new Dictionary<string, object>
{
{ PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") },
{ PropertyHeaders.MessageType, typeof(TMessage).FullName }
}
};
custom?.Invoke(properties);
return properties;
}
}
}
``` |
d8cc177d-cfbd-4ebd-8139-8c2ed8866fe0 | {
"language": "C#"
} | ```c#
#region Using
using System;
using System.Numerics;
using Emotion.Graphics.Objects;
using Emotion.Primitives;
#endregion
namespace Emotion.Plugins.ImGuiNet
{
public static class ImGuiExtensions
{
public static Tuple<Vector2, Vector2> GetImGuiUV(this Texture t, Rectangle? uv = null)
{
Rectangle reqUv;
if (uv == null)
reqUv = new Rectangle(0, 0, t.Size);
else
reqUv = (Rectangle) uv;
Vector2 uvOne = new Vector2(
reqUv.X / t.Size.X,
reqUv.Y / t.Size.Y * -1
);
Vector2 uvTwo = new Vector2(
(reqUv.X + reqUv.Size.X) / t.Size.X,
(reqUv.Y + reqUv.Size.Y) / t.Size.Y * -1
);
return new Tuple<Vector2, Vector2>(uvOne, uvTwo);
}
}
}```
Add util extention for rendering GUI. | ```c#
#region Using
using System;
using System.Numerics;
using Emotion.Graphics;
using Emotion.Graphics.Objects;
using Emotion.Primitives;
using ImGuiNET;
#endregion
namespace Emotion.Plugins.ImGuiNet
{
public static class ImGuiExtensions
{
public static Tuple<Vector2, Vector2> GetImGuiUV(this Texture t, Rectangle? uv = null)
{
Rectangle reqUv;
if (uv == null)
reqUv = new Rectangle(0, 0, t.Size);
else
reqUv = (Rectangle) uv;
Vector2 uvOne = new Vector2(
reqUv.X / t.Size.X,
reqUv.Y / t.Size.Y * -1
);
Vector2 uvTwo = new Vector2(
(reqUv.X + reqUv.Size.X) / t.Size.X,
(reqUv.Y + reqUv.Size.Y) / t.Size.Y * -1
);
return new Tuple<Vector2, Vector2>(uvOne, uvTwo);
}
public static void RenderUI(this RenderComposer composer)
{
ImGuiNetPlugin.RenderUI(composer);
}
}
}``` |
ee3815e3-1c87-43fe-9782-a9ea63a864a2 | {
"language": "C#"
} | ```c#
namespace AngleSharp.Core.Tests.Library
{
using AngleSharp.Core.Tests.Mocks;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
[TestFixture]
public class PageImportTests
{
[Test]
public async Task ImportPageFromVirtualRequest()
{
var requester = new MockRequester();
var receivedRequest = new TaskCompletionSource<String>();
requester.OnRequest = request => receivedRequest.SetResult(request.Address.Href);
var config = Configuration.Default.WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true, new[] { requester });
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href=http://example.com/test.html>"));
var link = document.QuerySelector<IHtmlLinkElement>("link");
var result = await receivedRequest.Task;
Assert.AreEqual("import", link.Relation);
Assert.IsNotNull(link.Import);
Assert.AreEqual("http://example.com/test.html", result);
}
}
}
```
Test for loading import from data url | ```c#
namespace AngleSharp.Core.Tests.Library
{
using AngleSharp.Core.Tests.Mocks;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
[TestFixture]
public class PageImportTests
{
[Test]
public async Task ImportPageFromVirtualRequest()
{
var requester = new MockRequester();
var receivedRequest = new TaskCompletionSource<String>();
requester.OnRequest = request => receivedRequest.SetResult(request.Address.Href);
var config = Configuration.Default.WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true, new[] { requester });
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href=http://example.com/test.html>"));
var link = document.QuerySelector<IHtmlLinkElement>("link");
var result = await receivedRequest.Task;
Assert.AreEqual("import", link.Relation);
Assert.IsNotNull(link.Import);
Assert.AreEqual("http://example.com/test.html", result);
}
[Test]
public async Task ImportPageFromDataRequest()
{
var receivedRequest = new TaskCompletionSource<Boolean>();
var config = Configuration.Default.WithDefaultLoader(setup =>
{
setup.IsResourceLoadingEnabled = true;
setup.Filter = request =>
{
receivedRequest.SetResult(true);
return true;
};
});
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("<!doctype html><link rel=import href='data:text/html,<div>foo</div>'>"));
var link = document.QuerySelector<IHtmlLinkElement>("link");
var finished = await receivedRequest.Task;
Assert.AreEqual("import", link.Relation);
Assert.IsNotNull(link.Import);
Assert.AreEqual("foo", link.Import.QuerySelector("div").TextContent);
}
}
}
``` |
25473fea-d345-428b-a99c-845589bde2cf | {
"language": "C#"
} | ```c#
@model PagedList.IPagedList<DynThings.Data.Models.Endpoint>
<table class="table striped hovered border bordered">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>GUID</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.EndPointType.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.GUID)
</td>
<td>
@Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
<div id="EndPointsListPager">
<input id="EndPointCurrentPage" value="@Model.PageNumber.ToString()" hidden />
@Html.PagedListPager(Model, page => Url.Action("ListPV", new { page }))
</div>
```
Add Device & Thing Titles to Endpoint GridList | ```c#
@model PagedList.IPagedList<DynThings.Data.Models.Endpoint>
<table class="table striped hovered border bordered">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Device</th>
<th>Thing</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.EndPointType.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Device.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Thing.Title)
</td>
<td>
@Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
<div id="EndPointsListPager">
<input id="EndPointCurrentPage" value="@Model.PageNumber.ToString()" hidden />
@Html.PagedListPager(Model, page => Url.Action("ListPV", new { page }))
</div>
``` |
bee1e696-968f-4f66-aaef-547125ae2000 | {
"language": "C#"
} | ```c#
using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace TIKSN.Data.LiteDB
{
/// <summary>
/// Create LiteDB database
/// </summary>
public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
{
private readonly IConfigurationRoot _configuration;
private readonly string _connectionStringKey;
private readonly IFileProvider _fileProvider;
public LiteDbDatabaseProvider(IConfigurationRoot configuration, string connectionStringKey,
IFileProvider fileProvider = null)
{
this._configuration = configuration;
this._connectionStringKey = connectionStringKey;
this._fileProvider = fileProvider;
}
/// <summary>
/// Creates LiteDB database with mapper
/// </summary>
/// <param name="mapper">Mapper</param>
/// <returns></returns>
public LiteDatabase GetDatabase(BsonMapper mapper)
{
var connectionString =
new ConnectionString(this._configuration.GetConnectionString(this._connectionStringKey));
if (this._fileProvider != null)
{
connectionString.Filename = this._fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
}
return new LiteDatabase(connectionString);
}
/// <summary>
/// Creates LiteDB database
/// </summary>
/// <returns></returns>
public LiteDatabase GetDatabase() => this.GetDatabase(null);
}
}
```
Use IConfiguration instead of IConfigurationRoot | ```c#
using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace TIKSN.Data.LiteDB
{
/// <summary>
/// Create LiteDB database
/// </summary>
public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
{
private readonly IConfiguration _configuration;
private readonly string _connectionStringKey;
private readonly IFileProvider _fileProvider;
public LiteDbDatabaseProvider(IConfiguration configuration, string connectionStringKey,
IFileProvider fileProvider = null)
{
this._configuration = configuration;
this._connectionStringKey = connectionStringKey;
this._fileProvider = fileProvider;
}
/// <summary>
/// Creates LiteDB database with mapper
/// </summary>
/// <param name="mapper">Mapper</param>
/// <returns></returns>
public LiteDatabase GetDatabase(BsonMapper mapper)
{
var connectionString =
new ConnectionString(this._configuration.GetConnectionString(this._connectionStringKey));
if (this._fileProvider != null)
{
connectionString.Filename = this._fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
}
return new LiteDatabase(connectionString);
}
/// <summary>
/// Creates LiteDB database
/// </summary>
/// <returns></returns>
public LiteDatabase GetDatabase() => this.GetDatabase(null);
}
}
``` |
fa3988cc-a6a9-4c4d-999f-1d39700d034a | {
"language": "C#"
} | ```c#
/*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace Mono.Debugger.Client.Commands
{
sealed class KillCommand : Command
{
public override string[] Names
{
get { return new[] { "kill", "stop" }; }
}
public override string Summary
{
get { return "Kill the inferior process."; }
}
public override string Syntax
{
get { return "kill|stop"; }
}
public override void Process(string args)
{
if (Debugger.State == State.Exited)
Log.Error("No inferior process");
else
Debugger.Kill();
}
}
}
```
Remove the silly `stop` alias for `kill`. | ```c#
/*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace Mono.Debugger.Client.Commands
{
sealed class KillCommand : Command
{
public override string[] Names
{
get { return new[] { "kill" }; }
}
public override string Summary
{
get { return "Kill the inferior process."; }
}
public override string Syntax
{
get { return "kill|stop"; }
}
public override void Process(string args)
{
if (Debugger.State == State.Exited)
Log.Error("No inferior process");
else
Debugger.Kill();
}
}
}
``` |
11bc27ea-8bf1-449f-a8a1-a4a95986ec07 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
namespace Cams
{
public static class VideoConverter
{
public static bool CodecCopy(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -codec copy {outputFile}");
}
public static bool Concat(string listFilePath, string outputFile)
{
return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
}
public static bool FastForward(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -filter:v \"setpts = 0.01 * PTS\" {outputFile}");
}
public static bool CheckValidVideoFile(string inputFile)
{
return Run($"-v error -i {inputFile} -f null -");
}
static bool Run(string args)
{
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "ffmpeg",
Arguments = args
}
})
{
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
}
}
}
```
Drop audio in summary videos | ```c#
using System.Diagnostics;
namespace Cams
{
public static class VideoConverter
{
public static bool CodecCopy(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -codec copy {outputFile}");
}
public static bool Concat(string listFilePath, string outputFile)
{
return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
}
public static bool FastForward(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -filter:v \"setpts = 0.01 * PTS\" -an {outputFile}");
}
public static bool CheckValidVideoFile(string inputFile)
{
return Run($"-v error -i {inputFile} -f null -");
}
static bool Run(string args)
{
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "ffmpeg",
Arguments = args
}
})
{
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
}
}
}
``` |
95e17268-0152-4878-bdec-bbaf5fe2e659 | {
"language": "C#"
} | ```c#
using System;
namespace $safeprojectname$
{
public class Program
{
public static void Main()
{
}
}
}
```
Update application template with working code to prevent the main thread from exiting | ```c#
using System;
namespace $safeprojectname$
{
public class Program
{
public static void Main()
{
// Insert your code below this line
// The main() method has to end with this infinite loop.
// Do not use the NETMF style : Thread.Sleep(Timeout.Infinite)
while (true)
{
Thread.Sleep(200);
}
}
}
}
``` |
2d2b113f-2ef8-4e08-a4c2-3243a670579e | {
"language": "C#"
} | ```c#
namespace PcscDotNet
{
public class PcscConnection
{
public PcscContext Context { get; private set; }
public IPcscProvider Provider { get; private set; }
public string ReaderName { get; private set; }
public PcscConnection(PcscContext context, string readerName)
{
Provider = (Context = context).Provider;
ReaderName = readerName;
}
}
}
```
Add properties and methods about connection. Implement `IDisposable` interface. | ```c#
using System;
namespace PcscDotNet
{
public class PcscConnection : IDisposable
{
public PcscContext Context { get; private set; }
public SCardHandle Handle { get; private set; }
public bool IsConnect => Handle.HasValue;
public bool IsDisposed { get; private set; } = false;
public SCardProtocols Protocols { get; private set; } = SCardProtocols.Undefined;
public IPcscProvider Provider { get; private set; }
public string ReaderName { get; private set; }
public PcscConnection(PcscContext context, string readerName)
{
Provider = (Context = context).Provider;
ReaderName = readerName;
}
~PcscConnection()
{
Dispose();
}
public unsafe PcscConnection Connect(SCardShare shareMode, SCardProtocols protocols, PcscExceptionHandler onException = null)
{
SCardHandle handle;
Provider.SCardConnect(Context.Handle, ReaderName, shareMode, protocols, &handle, &protocols).ThrowIfNotSuccess(onException);
Handle = handle;
Protocols = protocols;
return this;
}
public PcscConnection Disconnect(SCardDisposition disposition = SCardDisposition.Leave, PcscExceptionHandler onException = null)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PcscConnection), nameof(Disconnect));
DisconnectInternal(disposition, onException);
return this;
}
public void Dispose()
{
if (IsDisposed) return;
DisconnectInternal();
IsDisposed = true;
GC.SuppressFinalize(this);
}
private void DisconnectInternal(SCardDisposition disposition = SCardDisposition.Leave, PcscExceptionHandler onException = null)
{
if (!IsConnect) return;
Provider.SCardDisconnect(Handle, disposition).ThrowIfNotSuccess(onException);
Handle = SCardHandle.Default;
Protocols = SCardProtocols.Undefined;
}
}
}
``` |
7b36d4e6-d352-4a8b-96e7-59f4f39321f4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Castle.Core;
namespace Orchard.Caching {
public class DefaultCacheHolder : ICacheHolder {
private readonly IDictionary<CacheKey, object> _caches = new Dictionary<CacheKey, object>();
class CacheKey : Pair<Type, Pair<Type, Type>> {
public CacheKey(Type component, Type key, Type result)
: base(component, new Pair<Type, Type>(key, result)) {
}
}
public ICache<TKey, TResult> GetCache<TKey, TResult>(Type component) {
var cacheKey = new CacheKey(component, typeof(TKey), typeof(TResult));
lock (_caches) {
object value;
if (!_caches.TryGetValue(cacheKey, out value)) {
value = new Cache<TKey, TResult>();
_caches[cacheKey] = value;
}
return (ICache<TKey, TResult>)value;
}
}
}
}```
Use ConcurrentDictionary to simplify code | ```c#
using System;
using System.Collections.Concurrent;
namespace Orchard.Caching {
public class DefaultCacheHolder : ICacheHolder {
private readonly ConcurrentDictionary<CacheKey, object> _caches = new ConcurrentDictionary<CacheKey, object>();
class CacheKey : Tuple<Type, Type, Type> {
public CacheKey(Type component, Type key, Type result)
: base(component, key, result) {
}
}
public ICache<TKey, TResult> GetCache<TKey, TResult>(Type component) {
var cacheKey = new CacheKey(component, typeof(TKey), typeof(TResult));
var result = _caches.GetOrAdd(cacheKey, k => new Cache<TKey, TResult>());
return (Cache<TKey, TResult>)result;
}
}
}``` |
3ed825f4-a4b0-4ad6-82e7-c738938daa4f | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
namespace Gherkin.AstGenerator
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
return 100;
}
var startTime = Environment.TickCount;
foreach (var featureFilePath in args)
{
try
{
var astText = AstGenerator.GenerateAst(featureFilePath);
Console.WriteLine(astText);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
}
var endTime = Environment.TickCount;
if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
{
Console.Error.WriteLine(endTime - startTime);
}
return 0;
}
}
}
```
Print to STDOUT - 2> is broken on Mono/OS X | ```c#
using System;
using System.Linq;
namespace Gherkin.AstGenerator
{
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Gherkin.AstGenerator.exe test-feature-file.feature");
return 100;
}
var startTime = Environment.TickCount;
foreach (var featureFilePath in args)
{
try
{
var astText = AstGenerator.GenerateAst(featureFilePath);
Console.WriteLine(astText);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return 1;
}
}
var endTime = Environment.TickCount;
if (Environment.GetEnvironmentVariable("GHERKIN_PERF") != null)
{
Console.Error.WriteLine(endTime - startTime);
}
return 0;
}
}
}
``` |
c3a01de1-272b-45bb-b552-8de06e4473e0 | {
"language": "C#"
} | ```c#
using Content.Client.Utility;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.IoC;
namespace Content.Client.UserInterface
{
/// <summary>
/// The status effects display on the right side of the screen.
/// </summary>
public sealed class StatusEffectsUI : Control
{
private readonly VBoxContainer _vBox;
private TextureRect _healthStatusRect;
public StatusEffectsUI()
{
_vBox = new VBoxContainer {GrowHorizontal = GrowDirection.Begin};
AddChild(_vBox);
_vBox.AddChild(_healthStatusRect = new TextureRect
{
Texture = IoCManager.Resolve<IResourceCache>().GetTexture("/Textures/Mob/UI/Human/human0.png")
});
SetAnchorAndMarginPreset(LayoutPreset.TopRight);
MarginTop = 200;
}
public void SetHealthIcon(Texture texture)
{
_healthStatusRect.Texture = texture;
}
}
}
```
Make Status Effects UI better positioned. | ```c#
using Content.Client.Utility;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.IoC;
namespace Content.Client.UserInterface
{
/// <summary>
/// The status effects display on the right side of the screen.
/// </summary>
public sealed class StatusEffectsUI : Control
{
private readonly VBoxContainer _vBox;
private TextureRect _healthStatusRect;
public StatusEffectsUI()
{
_vBox = new VBoxContainer {GrowHorizontal = GrowDirection.Begin};
AddChild(_vBox);
_vBox.AddChild(_healthStatusRect = new TextureRect
{
TextureScale = (2, 2),
Texture = IoCManager.Resolve<IResourceCache>().GetTexture("/Textures/Mob/UI/Human/human0.png")
});
SetAnchorAndMarginPreset(LayoutPreset.TopRight);
MarginTop = 200;
MarginRight = 10;
}
public void SetHealthIcon(Texture texture)
{
_healthStatusRect.Texture = texture;
}
}
}
``` |
097bedaa-40c6-463d-85cc-115e2bc00346 | {
"language": "C#"
} | ```c#
using System;
namespace RapidCore.Locking
{
/// <summary>
/// When implemented in a downstream locker provider, this instance contains a handle to the underlying lock instance
/// </summary>
public interface IDistributedAppLock : IDisposable
{
/// <summary>
/// The name of the lock acquired
/// </summary>
string Name { get; set; }
}
}```
Add IsActive and ThrowIfNotActiveWithGivenName to AppLock interface | ```c#
using System;
namespace RapidCore.Locking
{
/// <summary>
/// When implemented in a downstream locker provider, this instance contains a handle to the underlying lock instance
/// </summary>
public interface IDistributedAppLock : IDisposable
{
/// <summary>
/// The name of the lock acquired
/// </summary>
string Name { get; set; }
/// <summary>
/// Determines whether the lock has been taken in the underlying source and is still active
/// </summary>
bool IsActive { get; set; }
/// <summary>
/// When implemented in a downstream provider it will verify that the current instance of the lock is in an
/// active (locked) state and has the name given to the method
/// </summary>
/// <param name="name"></param>
/// <exception cref="InvalidOperationException">
/// When the lock is either not active, or has a different name than provided in <paramref name="name"/>
/// </exception>
void ThrowIfNotActiveWithGivenName(string name);
}
}``` |
5fccb709-f2c0-4842-8862-39616f3961ee | {
"language": "C#"
} | ```c#
/* Empiria Extensions ****************************************************************************************
* *
* Module : Cognitive Services Component : Service provider *
* Assembly : Empiria.Cognition.dll Pattern : Data Transfer Objects *
* Type : TranslatorDataTypes License : Please read LICENSE.txt file *
* *
* Summary : Define data types for Microsoft Azure Cognition Translator Services. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
namespace Empiria.Cognition.Providers {
/// <summary>Summary : Define data types for Microsoft Azure Cognition Translator Services.</summary>
internal class Alignment {
internal string Proj {
get; set;
}
}
internal class SentenceLength {
internal int[] SrcSentLen {
get; set;
}
internal int[] TransSentLen {
get; set;
}
}
internal class Translation {
internal string Text {
get; set;
}
internal TextResult Transliteration {
get; set;
}
internal string To {
get; set;
}
internal Alignment Alignment {
get; set;
}
internal SentenceLength SentLen {
get; set;
}
}
internal class DetectedLanguage {
internal string Language {
get; set;
}
internal float Score {
get; set;
}
}
internal class TextResult {
internal string Text {
get; set;
}
internal string Script {
get; set;
}
}
internal class TranslatorDataTypes {
internal DetectedLanguage DetectedLanguage {
get; set;
}
internal TextResult SourceText {
get; set;
}
internal Translation[] Translations {
get; set;
}
}
}
```
Use JsonProperty attribute and remove unused types | ```c#
/* Empiria Extensions ****************************************************************************************
* *
* Module : Cognitive Services Component : Service provider *
* Assembly : Empiria.Cognition.dll Pattern : Data Transfer Objects *
* Type : TranslatorDataTypes License : Please read LICENSE.txt file *
* *
* Summary : Define data types for Microsoft Azure Cognition Translator Services. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using Newtonsoft.Json;
namespace Empiria.Cognition.Providers {
internal class Translation {
[JsonProperty]
internal string Text {
get; set;
}
[JsonProperty]
internal string To {
get; set;
}
}
internal class TranslatorResult {
[JsonProperty]
internal Translation[] Translations {
get; set;
}
}
}
``` |
1f3f0b35-85ff-446a-90e0-c5ff334bbf83 | {
"language": "C#"
} | ```c#
// Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START vision_quickstart]
using Google.Cloud.Vision.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
var client = ImageAnnotatorClient.Create();
var image = Image.FromFile("wakeupcat.jpg");
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
}
}
}
// [END vision_quickstart]```
Add comments to vision quickstart. | ```c#
// Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START vision_quickstart]
using Google.Cloud.Vision.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Instantiates a client
var client = ImageAnnotatorClient.Create();
// Load the image file into memory
var image = Image.FromFile("wakeupcat.jpg");
// Performs label detection on the image file
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
}
}
}
// [END vision_quickstart]
``` |
b1a5d08d-3e40-4861-a519-1ca286864e81 | {
"language": "C#"
} | ```c#
using TAP;
using System;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start("Device name");
Console.WriteLine("Got device name: {0}", dev.DeviceName);
dev.MTU = 1280;
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
while (true) {
EthernetFrame frame = dev.Read();
if (frame == null)
break;
if (frame.EtherType == EtherType.IPv6) {
IPv6Packet packet = new IPv6Packet(frame.Payload);
if (packet.NextHeader == ProtocolType.ICMPv6) {
ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
Console.WriteLine("Got ICMPv6 packet type {0}", type);
Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
}
}
Console.WriteLine("Read Ethernet frame of type {0}",
frame.EtherType);
Console.WriteLine("Source address: {0}",
BitConverter.ToString(frame.SourceAddress));
Console.WriteLine("Destination address: {0}",
BitConverter.ToString(frame.DestinationAddress));
}
}
}
```
Print source and destination addresses on ICMPv6 packets | ```c#
using TAP;
using System;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start("Device name");
Console.WriteLine("Got device name: {0}", dev.DeviceName);
dev.MTU = 1280;
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
while (true) {
EthernetFrame frame = dev.Read();
if (frame == null)
break;
if (frame.EtherType == EtherType.IPv6) {
IPv6Packet packet = new IPv6Packet(frame.Payload);
if (packet.NextHeader == ProtocolType.ICMPv6) {
ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
Console.WriteLine("Got ICMPv6 packet type {0}", type);
Console.WriteLine("Src: {0}", packet.Source);
Console.WriteLine("Dst: {0}", packet.Destination);
Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
}
}
Console.WriteLine("Read Ethernet frame of type {0}",
frame.EtherType);
Console.WriteLine("Source address: {0}",
BitConverter.ToString(frame.SourceAddress));
Console.WriteLine("Destination address: {0}",
BitConverter.ToString(frame.DestinationAddress));
}
}
}
``` |
ee69b63f-d7d0-4495-b3fa-9bf2e1f22b13 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace apod_api
{
public sealed class APOD_API
{
public APOD_API()
{
date = DateTime.Today;
}
public void sendRequest()
{
generateURL();
WebRequest request = WebRequest.Create(api_url);
api_response = request.GetResponse();
Stream responseStream = api_response.GetResponseStream();
sr = new StreamReader(responseStream);
myAPOD = JsonConvert.DeserializeObject<APOD>(sr.ReadToEnd());
sr.Close();
responseStream.Close();
api_response.Close();
}
public APOD_API setDate(DateTime newDate)
{
date = newDate;
return this;
}
private void generateURL()
{
api_url = api + "?api_key=" + api_key + "&date=" + date.ToString("yyyy-MM-dd");
}
private string api_key = "DEMO_KEY";
private string api = "https://api.nasa.gov/planetary/apod";
private string api_url;
private DateTime date;
private WebResponse api_response;
private StreamReader sr;
private APOD myAPOD;
public APOD apod { get { return myAPOD; } }
}
}```
Switch to .Dispose() from .Close(). | ```c#
using System;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace apod_api
{
public sealed class APOD_API
{
public APOD_API()
{
date = DateTime.Today;
}
public void sendRequest()
{
generateURL();
WebRequest request = WebRequest.Create(api_url);
api_response = request.GetResponse();
Stream responseStream = api_response.GetResponseStream();
sr = new StreamReader(responseStream);
myAPOD = JsonConvert.DeserializeObject<APOD>(sr.ReadToEnd());
sr.Dispose();
responseStream.Dispose();
api_response.Dispose();
}
public APOD_API setDate(DateTime newDate)
{
date = newDate;
return this;
}
private void generateURL()
{
api_url = api + "?api_key=" + api_key + "&date=" + date.ToString("yyyy-MM-dd");
}
private string api_key = "DEMO_KEY";
private string api = "https://api.nasa.gov/planetary/apod";
private string api_url;
private DateTime date;
private WebResponse api_response;
private StreamReader sr;
private APOD myAPOD;
public APOD apod { get { return myAPOD; } }
}
}``` |
57bee3d2-379d-4733-8d92-8dc11abb17a1 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundSpawn : MonoBehaviour
{
public AudioSource audioSource;
//We need to handle this manually to prevent multiple requests grabbing sound pool items in the same frame
public bool isPlaying = false;
private float waitLead = 0;
public void PlayOneShot()
{
audioSource.PlayOneShot(audioSource.clip);
WaitForPlayToFinish();
}
public void PlayNormally()
{
audioSource.Play();
WaitForPlayToFinish();
}
void WaitForPlayToFinish()
{
waitLead = 0f;
UpdateManager.Add(CallbackType.UPDATE, UpdateMe);
}
void UpdateMe()
{
waitLead += Time.deltaTime;
if (waitLead > 0.2f)
{
if (!audioSource.isPlaying)
{
UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
isPlaying = false;
waitLead = 0f;
}
}
}
}
```
Fix UpdateManager NRE for soundspawn | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundSpawn : MonoBehaviour
{
public AudioSource audioSource;
//We need to handle this manually to prevent multiple requests grabbing sound pool items in the same frame
public bool isPlaying = false;
private float waitLead = 0;
public void PlayOneShot()
{
audioSource.PlayOneShot(audioSource.clip);
WaitForPlayToFinish();
}
public void PlayNormally()
{
audioSource.Play();
WaitForPlayToFinish();
}
void WaitForPlayToFinish()
{
waitLead = 0f;
UpdateManager.Add(CallbackType.UPDATE, UpdateMe);
}
private void OnDisable()
{
if(isPlaying)
{
UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
isPlaying = false;
}
}
void UpdateMe()
{
waitLead += Time.deltaTime;
if (waitLead > 0.2f)
{
if (!audioSource.isPlaying)
{
UpdateManager.Remove(CallbackType.UPDATE, UpdateMe);
isPlaying = false;
waitLead = 0f;
}
}
}
}
``` |
47dc86b7-b813-4878-bc10-e105dfd7b720 | {
"language": "C#"
} | ```c#
// Copyright 2014 Ron Griffin, ...
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
using Topshelf;
namespace MassTransit.Host.RabbitMQ
{
/// <summary>
/// Entry point of the host process used to construct the Topshelf service.
/// </summary>
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<ServiceHost>(s =>
{
s.ConstructUsing(name => new ServiceHost());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("MassTransit RabbitMQ Service Bus Host");
x.SetDisplayName("MassTransitServiceBusHost");
x.SetServiceName("MassTransitServiceBusHost");
});
//TODO: extra parameter stuff
}
}
}
```
Add exit code to console app; return HostFactory.Run result | ```c#
// Copyright 2014 Ron Griffin, ...
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
using System;
using Magnum.Extensions;
using Topshelf;
namespace MassTransit.Host.RabbitMQ
{
/// <summary>
/// Entry point of the host process used to construct the Topshelf service.
/// </summary>
class Program
{
static void Main(string[] args)
{
var exitCode = HostFactory.Run(x =>
{
x.Service<ServiceHost>(s =>
{
s.ConstructUsing(name => new ServiceHost());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("MassTransit RabbitMQ Service Bus Host");
x.SetDisplayName("MassTransitServiceBusHost");
x.SetServiceName("MassTransitServiceBusHost");
});
//TODO: extra parameter stuff
Environment.Exit((int)exitCode);
}
}
}
``` |
2fcaf52b-e7cd-4aea-aa28-9cc56d105b08 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game.Configuration;
namespace osu.Desktop.Windows
{
public class GameplayWinKeyBlocker : Component
{
private Bindable<bool> allowScreenSuspension;
private Bindable<bool> disableWinKey;
private GameHost host;
[BackgroundDependencyLoader]
private void load(GameHost host, OsuConfigManager config)
{
this.host = host;
allowScreenSuspension = host.AllowScreenSuspension.GetBoundCopy();
allowScreenSuspension.BindValueChanged(_ => updateBlocking());
disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey);
disableWinKey.BindValueChanged(_ => updateBlocking(), true);
}
private void updateBlocking()
{
bool shouldDisable = disableWinKey.Value && !allowScreenSuspension.Value;
if (shouldDisable)
host.InputThread.Scheduler.Add(WindowsKey.Disable);
else
host.InputThread.Scheduler.Add(WindowsKey.Enable);
}
}
}
```
Fix windows key blocking applying when window is inactive / when watching a replay | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game;
using osu.Game.Configuration;
namespace osu.Desktop.Windows
{
public class GameplayWinKeyBlocker : Component
{
private Bindable<bool> disableWinKey;
private Bindable<bool> localUserPlaying;
[Resolved]
private GameHost host { get; set; }
[BackgroundDependencyLoader(true)]
private void load(OsuGame game, OsuConfigManager config)
{
localUserPlaying = game.LocalUserPlaying.GetBoundCopy();
localUserPlaying.BindValueChanged(_ => updateBlocking());
disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey);
disableWinKey.BindValueChanged(_ => updateBlocking(), true);
}
private void updateBlocking()
{
bool shouldDisable = disableWinKey.Value && localUserPlaying.Value;
if (shouldDisable)
host.InputThread.Scheduler.Add(WindowsKey.Disable);
else
host.InputThread.Scheduler.Add(WindowsKey.Enable);
}
}
}
``` |
30e1c097-c21c-4cac-a7c6-ac892d542a20 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
string _lastIp;
DateTime _lastUpdate;
public Dictionary<string, Func<string>> GetVariables()
{
var now = DateTime.Now;
if (now - _lastUpdate > TimeSpan.FromMinutes(1))
{
_lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
_lastUpdate = now;
}
return new Dictionary<string, Func<string>>()
{
{ "publicIp", () => _lastIp }
};
}
}
}
```
Make PublicIp variable lazy again. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
string _lastIp;
DateTime _lastUpdate;
public Dictionary<string, Func<string>> GetVariables()
{
Func<string> getIp = () =>
{
var now = DateTime.Now;
if (now - _lastUpdate > TimeSpan.FromMinutes(1))
{
_lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
_lastUpdate = now;
}
return _lastIp;
};
return new Dictionary<string, Func<string>>()
{
{ "publicIp", getIp }
};
}
}
}
``` |
1639cf56-cfa3-44e0-a2d2-bdc5f7ee4c04 | {
"language": "C#"
} | ```c#
using System.IO;
using Xunit;
namespace TfsHipChat.Tests
{
public class TfsIdentityTests
{
[Fact]
public void Url_ShouldReturnTheServerUrl_WhenDeserializedByValidXml()
{
const string serverUrl = "http://some-tfs-server.com";
const string tfsIdentityXml = "<TeamFoundationServer url=\"" + serverUrl + "\" />";
var serializer = new System.Xml.Serialization.XmlSerializer(typeof (TfsIdentity));
string url = null;
using (var reader = new StringReader(tfsIdentityXml))
{
var tfsIdentity = serializer.Deserialize(reader) as TfsIdentity;
if (tfsIdentity != null) url = tfsIdentity.Url;
}
Assert.Equal(url, serverUrl);
}
}
}
```
Fix grammar in test name | ```c#
using System.IO;
using Xunit;
namespace TfsHipChat.Tests
{
public class TfsIdentityTests
{
[Fact]
public void Url_ShouldReturnTheServerUrl_WhenDeserializedUsingValidXml()
{
const string serverUrl = "http://some-tfs-server.com";
const string tfsIdentityXml = "<TeamFoundationServer url=\"" + serverUrl + "\" />";
var serializer = new System.Xml.Serialization.XmlSerializer(typeof (TfsIdentity));
string url = null;
using (var reader = new StringReader(tfsIdentityXml))
{
var tfsIdentity = serializer.Deserialize(reader) as TfsIdentity;
if (tfsIdentity != null) url = tfsIdentity.Url;
}
Assert.Equal(url, serverUrl);
}
}
}
``` |
12a617cd-f2a4-4304-8267-91b628253d24 | {
"language": "C#"
} | ```c#
namespace LoadTests
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using EasyConsole;
using SqlStreamStore.Streams;
public class ReadAll : LoadTest
{
protected override async Task RunAsync(CancellationToken ct)
{
Output.WriteLine("");
Output.WriteLine(ConsoleColor.Green, "Appends events to streams and reads them all back in a single task.");
Output.WriteLine("");
var streamStore = GetStore();
await new AppendExpectedVersionAnyParallel()
.Append(streamStore, ct);
int readPageSize = Input.ReadInt("Read page size: ", 1, 10000);
var stopwatch = Stopwatch.StartNew();
int count = 0;
var position = Position.Start;
ReadAllPage page;
do
{
page = await streamStore.ReadAllForwards(position, readPageSize, cancellationToken: ct);
count += page.Messages.Length;
Console.Write($"\r> Read {count}");
position = page.NextPosition;
} while (!page.IsEnd);
stopwatch.Stop();
var rate = Math.Round((decimal)count / stopwatch.ElapsedMilliseconds * 1000, 0);
Output.WriteLine("");
Output.WriteLine($"> {count} messages read in {stopwatch.Elapsed} ({rate} m/s)");
}
}
}```
Add option to enable prefetch or not. | ```c#
namespace LoadTests
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using EasyConsole;
using SqlStreamStore.Streams;
public class ReadAll : LoadTest
{
protected override async Task RunAsync(CancellationToken ct)
{
Output.WriteLine("");
Output.WriteLine(ConsoleColor.Green, "Appends events to streams and reads them all back in a single task.");
Output.WriteLine("");
var streamStore = GetStore();
await new AppendExpectedVersionAnyParallel()
.Append(streamStore, ct);
int readPageSize = Input.ReadInt("Read page size: ", 1, 10000);
var prefectch = Input.ReadEnum<YesNo>("Prefetch: ");
var stopwatch = Stopwatch.StartNew();
int count = 0;
var position = Position.Start;
ReadAllPage page;
do
{
page = await streamStore.ReadAllForwards(position, readPageSize, prefetchJsonData: prefectch == YesNo.Yes, cancellationToken: ct);
count += page.Messages.Length;
Console.Write($"\r> Read {count}");
position = page.NextPosition;
} while (!page.IsEnd);
stopwatch.Stop();
var rate = Math.Round((decimal)count / stopwatch.ElapsedMilliseconds * 1000, 0);
Output.WriteLine("");
Output.WriteLine($"> {count} messages read in {stopwatch.Elapsed} ({rate} m/s)");
}
private enum YesNo
{
Yes,
No
}
}
}``` |
e20e0a03-51c3-483d-9f22-19fa71d51c0b | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
using static System.Console;
namespace AsyncLambda
{
class Program
{
static async Task Main()
{
WriteLine("Started");
try
{
Process(async () =>
{
await Task.Delay(500);
throw new Exception();
});
}
catch (Exception)
{
WriteLine("Catch");
}
await Task.Delay(2000);
WriteLine("Finished");
}
private static void Process(Action action)
{
action();
}
private static void Process(Func<Task> action)
{
action();
}
}
}```
Comment code according to presentation's flow | ```c#
using System;
using System.Threading.Tasks;
using static System.Console;
namespace AsyncLambda
{
class Program
{
static async Task Main()
{
WriteLine("Started");
try
{
Process(async () =>
{
await Task.Delay(500);
throw new Exception();
});
}
catch (Exception)
{
WriteLine("Catch");
}
await Task.Delay(2000);
WriteLine("Finished");
}
private static void Process(Action action)
{
action();
}
// private static void Process(Func<Task> action)
// {
// action();
// }
}
}``` |
098e65d3-13ed-46f5-8c5a-38840bce1eba | {
"language": "C#"
} | ```c#
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Visuals.Media.Imaging;
namespace Avalonia.Media
{
public class RenderOptions
{
/// <summary>
/// Defines the <see cref="BitmapInterpolationMode"/> property.
/// </summary>
public static readonly StyledProperty<BitmapInterpolationMode> BitmapInterpolationModeProperty =
AvaloniaProperty.RegisterAttached<RenderOptions, AvaloniaObject, BitmapInterpolationMode>(
"BitmapInterpolationMode",
BitmapInterpolationMode.HighQuality,
inherits: true);
/// <summary>
/// Gets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's left coordinate.</returns>
public static BitmapInterpolationMode GetBitmapInterpolationMode(AvaloniaObject element)
{
return element.GetValue(BitmapInterpolationModeProperty);
}
/// <summary>
/// Sets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The left value.</param>
public static void SetBitmapInterpolationMode(AvaloniaObject element, BitmapInterpolationMode value)
{
element.SetValue(BitmapInterpolationModeProperty, value);
}
}
}
```
Set default render quality to medium | ```c#
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Visuals.Media.Imaging;
namespace Avalonia.Media
{
public class RenderOptions
{
/// <summary>
/// Defines the <see cref="BitmapInterpolationMode"/> property.
/// </summary>
public static readonly StyledProperty<BitmapInterpolationMode> BitmapInterpolationModeProperty =
AvaloniaProperty.RegisterAttached<RenderOptions, AvaloniaObject, BitmapInterpolationMode>(
"BitmapInterpolationMode",
BitmapInterpolationMode.MediumQuality,
inherits: true);
/// <summary>
/// Gets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's left coordinate.</returns>
public static BitmapInterpolationMode GetBitmapInterpolationMode(AvaloniaObject element)
{
return element.GetValue(BitmapInterpolationModeProperty);
}
/// <summary>
/// Sets the value of the BitmapInterpolationMode attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The left value.</param>
public static void SetBitmapInterpolationMode(AvaloniaObject element, BitmapInterpolationMode value)
{
element.SetValue(BitmapInterpolationModeProperty, value);
}
}
}
``` |
32b0f9c7-3200-4099-8c61-f65811a89e9e | {
"language": "C#"
} | ```c#
using System.Drawing;
using System.Windows;
namespace NetSparkle.TestAppWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Sparkle _sparkle;
public MainWindow()
{
InitializeComponent();
// remove the netsparkle key from registry
try
{
Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree("Software\\Microsoft\\NetSparkle.TestAppWPF");
}
catch { }
_sparkle = new Sparkle("https://deadpikle.github.io/NetSparkle/files/sample-app/appcast.xml", SystemIcons.Application); //, "NetSparkleTestApp.exe");
_sparkle.RunningFromWPF = true;
_sparkle.CloseWPFWindow += _sparkle_CloseWPFWindow;
_sparkle.StartLoop(true, true);
}
private void _sparkle_CloseWPFWindow()
{
Dispatcher.Invoke(() => {
Application.Current.Shutdown();
});
}
private void button1_Click(object sender, RoutedEventArgs e)
{
_sparkle.CheckForUpdatesAtUserRequest();
// _sparkle.StopLoop();
// Close();
}
}
}
```
Remove unnecessary event callback in WPF demo | ```c#
using System.Drawing;
using System.Windows;
namespace NetSparkle.TestAppWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Sparkle _sparkle;
public MainWindow()
{
InitializeComponent();
// remove the netsparkle key from registry
try
{
Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree("Software\\Microsoft\\NetSparkle.TestAppWPF");
}
catch { }
_sparkle = new Sparkle("https://deadpikle.github.io/NetSparkle/files/sample-app/appcast.xml", SystemIcons.Application); //, "NetSparkleTestApp.exe");
_sparkle.RunningFromWPF = true;
_sparkle.StartLoop(true, true);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
_sparkle.CheckForUpdatesAtUserRequest();
// _sparkle.StopLoop();
// Close();
}
}
}
``` |
6cb30cd6-0c82-4e90-a1c0-2db95538f0aa | {
"language": "C#"
} | ```c#
using System;
namespace AutoQueryable.Models.Enums
{
[Flags]
public enum ClauseType : short
{
Select = 1 << 1,
Top = 1 << 2,
Take = 1 << 3,
Skip = 1 << 4,
OrderBy = 1 << 5,
OrderByDesc = 1 << 6,
Include = 1 << 7,
GroupBy = 1 << 8,
First = 1 << 9,
Last = 1 << 10,
WrapWith = 1 << 11
}
}```
Remove Include from clause types. | ```c#
using System;
namespace AutoQueryable.Models.Enums
{
[Flags]
public enum ClauseType : short
{
Select = 1 << 1,
Top = 1 << 2,
Take = 1 << 3,
Skip = 1 << 4,
OrderBy = 1 << 5,
OrderByDesc = 1 << 6,
GroupBy = 1 << 8,
First = 1 << 9,
Last = 1 << 10,
WrapWith = 1 << 11
}
}``` |
bd0ac1dd-73ae-47a9-abc2-ccded4b03368 | {
"language": "C#"
} | ```c#
using System.Windows.Input;
namespace DesktopWidgets.Events
{
internal class WidgetMouseDownEvent : WidgetEventBase
{
public MouseButton MouseButton { get; set; }
}
}```
Fix "Widget Mouse Down" event property friendly names | ```c#
using System.ComponentModel;
using System.Windows.Input;
namespace DesktopWidgets.Events
{
internal class WidgetMouseDownEvent : WidgetEventBase
{
[DisplayName("Mouse Button")]
public MouseButton MouseButton { get; set; }
}
}``` |
964ed5cd-4e0d-47f4-956d-956fea6b2166 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin, Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012 Xamarin, Inc.")]
[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.*")]
// 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("")]
```
Fix version and update copyright | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2013 Xamarin Inc.")]
[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.2.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("")]
``` |
81abf3ac-ebac-42ed-8e66-3a4c98e3c184 | {
"language": "C#"
} | ```c#
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace Example_Drawing
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
#region -= declarations and properties =-
protected UIWindow window;
protected UINavigationController mainNavController;
protected Example_Drawing.Screens.iPad.Home.HomeScreen iPadHome;
#endregion
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create our window
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.MakeKeyAndVisible ();
// instantiate our main navigatin controller and add it's view to the window
mainNavController = new UINavigationController ();
iPadHome = new Example_Drawing.Screens.iPad.Home.HomeScreen ();
mainNavController.PushViewController (iPadHome, false);
window.RootViewController = mainNavController;
//
return true;
}
}
}
```
Set navigation bar translucent to false to fix views overlapping. Fix bug | ```c#
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace Example_Drawing
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
#region -= declarations and properties =-
protected UIWindow window;
protected UINavigationController mainNavController;
protected Example_Drawing.Screens.iPad.Home.HomeScreen iPadHome;
#endregion
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create our window
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.MakeKeyAndVisible ();
// instantiate our main navigatin controller and add it's view to the window
mainNavController = new UINavigationController ();
mainNavController.NavigationBar.Translucent = false;
iPadHome = new Example_Drawing.Screens.iPad.Home.HomeScreen ();
mainNavController.PushViewController (iPadHome, false);
window.RootViewController = mainNavController;
//
return true;
}
}
}
``` |
794eaf4a-f121-4783-9201-55a9833c87e1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SGEnviro;
namespace SGEnviroTest
{
[TestClass]
public class ApiTest
{
private string apiKey;
[TestInitialize]
public void TestInitialize()
{
apiKey = ConfigurationManager.AppSettings["ApiKey"];
}
[TestMethod]
public void TestApiCanRetrieve()
{
var api = new SGEnviroApi(apiKey);
var result = api.GetPsiUpdateAsync().Result;
Assert.IsNotNull(result);
}
}
}
```
Fix incorrectly implemented async test. | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SGEnviro;
namespace SGEnviroTest
{
[TestClass]
public class ApiTest
{
private string apiKey;
[TestInitialize]
public void TestInitialize()
{
apiKey = ConfigurationManager.AppSettings["ApiKey"];
}
[TestMethod]
public async Task TestApiCanRetrieve()
{
var api = new SGEnviroApi(apiKey);
var result = await api.GetPsiUpdateAsync();
Assert.IsNotNull(result);
}
}
}
``` |
37eeb6f3-3db3-4cd4-905a-bc7649fdfd01 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RestKit")]
[assembly: AssemblyDescription("SIMPLE http client wrapper that eliminates the boilerplate code you don't want to write.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("de3a6223-af0a-4583-bdfb-63957829e7ba")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
[assembly: CLSCompliant(true)]
```
Increment minor version - breaking changes. | ```c#
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("RestKit")]
[assembly: AssemblyDescription("SIMPLE http client wrapper that eliminates the boilerplate code you don't want to write.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("de3a6223-af0a-4583-bdfb-63957829e7ba")]
[assembly: AssemblyVersion("1.1.0.1")]
[assembly: AssemblyFileVersion("1.1.0.1")]
[assembly: CLSCompliant(true)]
``` |
bcb580d2-ef48-4ce1-a81a-88e955d1f9b7 | {
"language": "C#"
} | ```c#
using CommandLine;
namespace ProcessGremlinApp
{
public class ArgumentParser
{
public bool TryParse(string[] args, out Arguments arguments)
{
string invokedVerb = null;
object invokedVerbInstance = null;
var options = new Options();
if (Parser.Default.ParseArguments(
args,
options,
(verb, subOptions) =>
{
invokedVerb = verb;
invokedVerbInstance = subOptions;
}) && invokedVerbInstance is CommonOptions)
{
arguments = new Arguments(invokedVerb, invokedVerbInstance);
return true;
}
arguments = null;
return false;
}
}
}```
Fix crashing in the case of empty args | ```c#
using CommandLine;
namespace ProcessGremlinApp
{
public class ArgumentParser
{
public bool TryParse(string[] args, out Arguments arguments)
{
if (args != null && args.Length != 0)
{
string invokedVerb = null;
object invokedVerbInstance = null;
var options = new Options();
if (Parser.Default.ParseArguments(
args,
options,
(verb, subOptions) =>
{
invokedVerb = verb;
invokedVerbInstance = subOptions;
}) && invokedVerbInstance is CommonOptions)
{
arguments = new Arguments(invokedVerb, invokedVerbInstance);
return true;
}
}
arguments = null;
return false;
}
}
}``` |
529feb93-9c8e-4550-8326-aec134537bee | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
if (args.Any())
{
commandDispatcher.Dispatch(args);
}
}
}
}
```
Write usage information if no parameters are specified | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
var commandDispatcher = container.Resolve<CommandDispatcher>();
if (args.Any())
{
commandDispatcher.Dispatch(args);
}
Console.WriteLine("Usage: appharbor COMMAND [command-options]");
Console.WriteLine("");
}
}
}
``` |
7831cbcb-ab40-401d-80af-09cb62b19750 | {
"language": "C#"
} | ```c#
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("Lurking Window Detector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lurking Window Detector")]
[assembly: AssemblyCopyright("Copyright (c) 2016 KAMADA Ken'ichi")]
[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("700adee8-5d49-40f3-a3ae-05dc23501663")]
// 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")]
```
Increment the version to 1.1. | ```c#
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("Lurking Window Detector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lurking Window Detector")]
[assembly: AssemblyCopyright("Copyright (c) 2016 KAMADA Ken'ichi")]
[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("700adee8-5d49-40f3-a3ae-05dc23501663")]
// 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")]
``` |
e115faf3-9bf9-4408-bb17-0187ed822f1e | {
"language": "C#"
} | ```c#
namespace Parsley;
partial class Grammar
{
public static Parser<string> Keyword(string word)
{
if (word.Any(ch => !char.IsLetter(ch)))
throw new ArgumentException("Keywords may only contain letters.", nameof(word));
return input =>
{
var peek = input.Peek(word.Length + 1);
if (peek.StartsWith(word, StringComparison.Ordinal))
{
if (peek.Length == word.Length || !char.IsLetter(peek[^1]))
{
input.Advance(word.Length);
return new Parsed<string>(word, input.Position);
}
}
return new Error<string>(input.Position, ErrorMessage.Expected(word));
};
}
}
```
Remove superfluous StringComparison.Ordinal argument from ReadOnlySpan<char>.StarstWith(...) call, since the overload without a StringComparison in fact performs ordinal comparison semantics and the original call ultimately calls into the overload with no StringComparison argument anyway. In other words, you only have to specify StringComparison for span StartsWith calls when you are NOT using ordinal comparisons. | ```c#
namespace Parsley;
partial class Grammar
{
public static Parser<string> Keyword(string word)
{
if (word.Any(ch => !char.IsLetter(ch)))
throw new ArgumentException("Keywords may only contain letters.", nameof(word));
return input =>
{
var peek = input.Peek(word.Length + 1);
if (peek.StartsWith(word))
{
if (peek.Length == word.Length || !char.IsLetter(peek[^1]))
{
input.Advance(word.Length);
return new Parsed<string>(word, input.Position);
}
}
return new Error<string>(input.Position, ErrorMessage.Expected(word));
};
}
}
``` |
160e4114-256c-472d-8c77-78a0b784c7ab | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Windows.ApplicationModel;
namespace EarTrumpet.Extensions
{
public static class AppExtensions
{
public static Version GetVersion(this Application app)
{
if (HasIdentity(app))
{
var packageVer = Package.Current.Id.Version;
return new Version(packageVer.Major, packageVer.Minor, packageVer.Build, packageVer.Revision);
}
else
{
#if DEBUG
var versionStr = new StreamReader(Application.GetResourceStream(new Uri("pack://application:,,,/EarTrumpet;component/Assets/DevVersion.txt")).Stream).ReadToEnd();
return Version.Parse(versionStr);
#else
return new Version(0, 0, 0, 0);
#endif
}
}
static bool? _hasIdentity = null;
public static bool HasIdentity(this Application app)
{
#if VSDEBUG
if (Debugger.IsAttached)
{
return false;
}
#endif
if (_hasIdentity == null)
{
try
{
_hasIdentity = (Package.Current.Id != null);
}
catch (InvalidOperationException ex)
{
#if !DEBUG
// We do not expect this to occur in production when the app is packaged.
AppTrace.LogWarning(ex);
#else
Trace.WriteLine($"AppExtensions HasIdentity: False {ex.Message}");
#endif
_hasIdentity = false;
}
}
return (bool)_hasIdentity;
}
}
}
```
Clean up lingering AppTrace reference | ```c#
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Windows.ApplicationModel;
using EarTrumpet.Diagnosis;
namespace EarTrumpet.Extensions
{
public static class AppExtensions
{
public static Version GetVersion(this Application app)
{
if (HasIdentity(app))
{
var packageVer = Package.Current.Id.Version;
return new Version(packageVer.Major, packageVer.Minor, packageVer.Build, packageVer.Revision);
}
else
{
#if DEBUG
var versionStr = new StreamReader(Application.GetResourceStream(new Uri("pack://application:,,,/EarTrumpet;component/Assets/DevVersion.txt")).Stream).ReadToEnd();
return Version.Parse(versionStr);
#else
return new Version(0, 0, 0, 0);
#endif
}
}
static bool? _hasIdentity = null;
public static bool HasIdentity(this Application app)
{
#if VSDEBUG
if (Debugger.IsAttached)
{
return false;
}
#endif
if (_hasIdentity == null)
{
try
{
_hasIdentity = (Package.Current.Id != null);
}
catch (InvalidOperationException ex)
{
#if !DEBUG
// We do not expect this to occur in production when the app is packaged.
ErrorReporter.LogWarning(ex);
#else
Trace.WriteLine($"AppExtensions HasIdentity: False {ex.Message}");
#endif
_hasIdentity = false;
}
}
return (bool)_hasIdentity;
}
}
}
``` |
7d8b5e53-8731-433c-9dc2-041d8c193049 | {
"language": "C#"
} | ```c#
using System;
using UnityEditor;
using UnityEngine;
namespace Alensia.Core.UI
{
public static class ComponentFactory
{
[MenuItem("GameObject/UI/Alensia/Button", false, 10)]
public static Button CreateButton(MenuCommand command) => CreateComponent(command, Button.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Dropdown", false, 10)]
public static Dropdown CreateDropdown(MenuCommand command) => CreateComponent(command, Dropdown.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Label", false, 10)]
public static Label CreateLabel(MenuCommand command) => CreateComponent(command, Label.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Panel", false, 10)]
public static Panel CreatePanel(MenuCommand command) => CreateComponent(command, Panel.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Slider", false, 10)]
public static Slider CreateSlider(MenuCommand command) => CreateComponent(command, Slider.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Scroll Panel", false, 10)]
public static ScrollPanel CreateScrollPanel(MenuCommand command) => CreateComponent(command, ScrollPanel.CreateInstance);
private static T CreateComponent<T>(
MenuCommand command, Func<T> factory) where T : UIComponent
{
var component = factory.Invoke();
GameObjectUtility.SetParentAndAlign(
component.gameObject, command.context as GameObject);
Undo.RegisterCreatedObjectUndo(component, "Create " + component.name);
Selection.activeObject = component;
return component;
}
}
}```
Rearrange UI menu according to component types | ```c#
using System;
using UnityEditor;
using UnityEngine;
namespace Alensia.Core.UI
{
public static class ComponentFactory
{
[MenuItem("GameObject/UI/Alensia/Label", false, 10)]
public static Label CreateLabel(MenuCommand command) => CreateComponent(command, Label.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Button", false, 10)]
public static Button CreateButton(MenuCommand command) => CreateComponent(command, Button.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Dropdown", false, 10)]
public static Dropdown CreateDropdown(MenuCommand command) => CreateComponent(command, Dropdown.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Slider", false, 10)]
public static Slider CreateSlider(MenuCommand command) => CreateComponent(command, Slider.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Panel", false, 10)]
public static Panel CreatePanel(MenuCommand command) => CreateComponent(command, Panel.CreateInstance);
[MenuItem("GameObject/UI/Alensia/Scroll Panel", false, 10)]
public static ScrollPanel CreateScrollPanel(MenuCommand command) => CreateComponent(command, ScrollPanel.CreateInstance);
private static T CreateComponent<T>(
MenuCommand command, Func<T> factory) where T : UIComponent
{
var component = factory.Invoke();
GameObjectUtility.SetParentAndAlign(
component.gameObject, command.context as GameObject);
Undo.RegisterCreatedObjectUndo(component, "Create " + component.name);
Selection.activeObject = component;
return component;
}
}
}``` |
e8b3c79d-cfba-4cfe-ab58-24dad873ce3b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
public Dictionary<string, Func<string>> GetVariables()
{
return new Dictionary<string, Func<string>>()
{
{ "publicIp", () => new WebClient().DownloadString("http://icanhazip.com").Trim() }
};
}
}
}
```
Refresh IP address not often than 1 time per minute. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Eco.Variables
{
public class PublicIpVariable : IVariableProvider
{
string _lastIp;
DateTime _lastUpdate;
public Dictionary<string, Func<string>> GetVariables()
{
var now = DateTime.Now;
if (now - _lastUpdate > TimeSpan.FromMinutes(1))
{
_lastIp = new WebClient().DownloadString("http://icanhazip.com").Trim();
_lastUpdate = now;
}
return new Dictionary<string, Func<string>>()
{
{ "publicIp", () => _lastIp }
};
}
}
}
``` |
d768d980-41f5-43f8-a978-e28683705e60 | {
"language": "C#"
} | ```c#
using Andromeda2D.Entities;
using Andromeda2D.Entities.Components;
using Andromeda2D.Entities.Components.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Andromeda.Entities.Components
{
/// <summary>
/// A controller for a model
/// </summary>
/// <typeparam name="TModel">The model type</typeparam>
public abstract class Controller<TModel> : Component
where TModel : IModel
{
Entity _entity;
/// <summary>
/// Sets the model of the controller
/// </summary>
/// <param name="model">The model to set to this controller</param>
protected void SetControllerModel(TModel model)
{
this._model = model;
}
private TModel _model;
/// <summary>
/// The model of this controller
/// </summary>
public TModel Model
{
get => _model;
}
public abstract void InitModel();
public override void OnComponentInit(Entity entity)
{
InitModel();
}
}
}
```
Change InitModel from public to protected | ```c#
using Andromeda2D.Entities;
using Andromeda2D.Entities.Components;
using Andromeda2D.Entities.Components.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Andromeda.Entities.Components
{
/// <summary>
/// A controller for a model
/// </summary>
/// <typeparam name="TModel">The model type</typeparam>
public abstract class Controller<TModel> : Component
where TModel : IModel
{
Entity _entity;
/// <summary>
/// Sets the model of the controller
/// </summary>
/// <param name="model">The model to set to this controller</param>
protected void SetControllerModel(TModel model)
{
this._model = model;
}
private TModel _model;
/// <summary>
/// The model of this controller
/// </summary>
public TModel Model
{
get => _model;
}
protected abstract void InitModel();
public override void OnComponentInit(Entity entity)
{
InitModel();
}
}
}
``` |
2809e207-b873-4caa-85fd-e5465eace348 | {
"language": "C#"
} | ```c#
using System;
using System.ServiceModel;
namespace MultiMiner.Remoting.Server
{
public class RemotingServer
{
private bool serviceStarted = false;
private ServiceHost myServiceHost = null;
public void Startup()
{
Uri baseAddress = new Uri("net.tcp://localhost:" + Config.RemotingPort + "/RemotingService");
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
myServiceHost = new ServiceHost(typeof(RemotingService), baseAddress);
myServiceHost.AddServiceEndpoint(typeof(IRemotingService), binding, baseAddress);
myServiceHost.Open();
serviceStarted = true;
}
public void Shutdown()
{
myServiceHost.Close();
myServiceHost = null;
serviceStarted = false;
}
}
}
```
Fix a null ref error | ```c#
using System;
using System.ServiceModel;
namespace MultiMiner.Remoting.Server
{
public class RemotingServer
{
private bool serviceStarted = false;
private ServiceHost myServiceHost = null;
public void Startup()
{
Uri baseAddress = new Uri("net.tcp://localhost:" + Config.RemotingPort + "/RemotingService");
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
myServiceHost = new ServiceHost(typeof(RemotingService), baseAddress);
myServiceHost.AddServiceEndpoint(typeof(IRemotingService), binding, baseAddress);
myServiceHost.Open();
serviceStarted = true;
}
public void Shutdown()
{
if (!serviceStarted)
return;
myServiceHost.Close();
myServiceHost = null;
serviceStarted = false;
}
}
}
``` |
70c62b58-2738-4bb4-aac7-9f36edd11eab | {
"language": "C#"
} | ```c#
using System;
using Gtk;
namespace VideoAggregator
{
class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
MainWindow win = new MainWindow ();
win.Show ();
Application.Run ();
}
}
}
```
Make program maximized on start | ```c#
using System;
using Gtk;
namespace VideoAggregator
{
class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
MainWindow win = new MainWindow ();
win.Maximize ();
win.Show ();
Application.Run ();
}
}
}
``` |
8fb92069-b0a8-4d38-aab0-b0ddf8b72046 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CuberLib
{
public class ImageTile
{
private Image image;
private Size size;
public ImageTile(string inputFile, int xSize, int ySize)
{
if (!File.Exists(inputFile)) throw new FileNotFoundException();
image = Image.FromFile(inputFile);
size = new Size(xSize, ySize);
}
public void GenerateTiles(string outputPath)
{
int xMax = image.Width;
int yMax = image.Height;
int tileWidth = xMax / size.Width;
int tileHeight = yMax / size.Height;
for (int x = 0; x < size.Width; x++)
{
for (int y = 0; y < size.Height; y++)
{
string outputFileName = Path.Combine(outputPath, string.Format("{0}_{1}.jpg", x, y));
Rectangle tileBounds = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
Bitmap target = new Bitmap(tileWidth, tileHeight);
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.DrawImage(
image,
new Rectangle(0, 0, tileWidth, tileHeight),
tileBounds,
GraphicsUnit.Pixel);
}
target.Save(outputFileName, ImageFormat.Jpeg);
}
}
}
}
}
```
Create output directory if needed for jpg slicing. | ```c#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CuberLib
{
public class ImageTile
{
private Image image;
private Size size;
public ImageTile(string inputFile, int xSize, int ySize)
{
if (!File.Exists(inputFile)) throw new FileNotFoundException();
image = Image.FromFile(inputFile);
size = new Size(xSize, ySize);
}
public void GenerateTiles(string outputPath)
{
int xMax = image.Width;
int yMax = image.Height;
int tileWidth = xMax / size.Width;
int tileHeight = yMax / size.Height;
if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); }
for (int x = 0; x < size.Width; x++)
{
for (int y = 0; y < size.Height; y++)
{
string outputFileName = Path.Combine(outputPath, string.Format("{0}_{1}.jpg", x, y));
Rectangle tileBounds = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
Bitmap target = new Bitmap(tileWidth, tileHeight);
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.DrawImage(
image,
new Rectangle(0, 0, tileWidth, tileHeight),
tileBounds,
GraphicsUnit.Pixel);
}
target.Save(outputFileName, ImageFormat.Jpeg);
}
}
}
}
}
``` |
068e8178-7346-484d-b57d-6da38ab69c6c | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BatteryCommander.Web.Models
{
public class Vehicle
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int UnitId { get; set; }
public virtual Unit Unit { get; set; }
// Notes, What's broken about it?
[Required]
public VehicleStatus Status { get; set; } = VehicleStatus.FMC;
[Required, StringLength(10)]
public String Bumper { get; set; }
[Required]
public VehicleType Type { get; set; } = VehicleType.HMMWV;
// public String Registration { get; set; }
// public String Serial { get; set; }
[Required]
public int Seats { get; set; } = 2;
// TroopCapacity?
// Chalk Order?
// LIN?
// Fuel Card? Towbar? Water Buffalo?
// Fuel Level?
// Driver, A-Driver, Passengers, Assigned Section?
public enum VehicleType : byte
{
HMMWV = 0,
MTV = 1
}
public enum VehicleStatus : byte
{
Unknown = 0,
FMC = 1,
NMC = byte.MaxValue
}
}
}```
Add note about things to add for vehicles | ```c#
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BatteryCommander.Web.Models
{
public class Vehicle
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int UnitId { get; set; }
public virtual Unit Unit { get; set; }
// Notes, What's broken about it?
[Required]
public VehicleStatus Status { get; set; } = VehicleStatus.FMC;
[Required, StringLength(10)]
public String Bumper { get; set; }
[Required]
public VehicleType Type { get; set; } = VehicleType.HMMWV;
// public String Registration { get; set; }
// public String Serial { get; set; }
[Required]
public int Seats { get; set; } = 2;
// TroopCapacity?
// Chalk Order?
// LIN?
// Fuel Card? Towbar? Water Buffalo?
// Fuel Level?
// Driver, A-Driver, Passengers, Assigned Section?
// Has JBC-P?
public enum VehicleType : byte
{
HMMWV = 0,
MTV = 1
}
public enum VehicleStatus : byte
{
Unknown = 0,
FMC = 1,
NMC = byte.MaxValue
}
}
}``` |
3b5ebbbc-5c3e-4af3-8394-cf01a92f0625 | {
"language": "C#"
} | ```c#
using System;
using SocialToolBox.Core.Database;
using SocialToolBox.Core.Database.Serialization;
using SocialToolBox.Crm.Contact.Event;
namespace SocialToolBox.Sample.Web
{
/// <summary>
/// Data initially available in the system.
/// </summary>
public static class InitialData
{
public static readonly Id UserVictorNicollet = Id.Parse("aaaaaaaaaaa");
public static readonly Id ContactBenjaminFranklin = Id.Parse("aaaaaaaaaab");
/// <summary>
/// Generates sample data.
/// </summary>
public static void AddTo(SocialModules modules)
{
var t = modules.Database.OpenReadWriteCursor();
AddContactsTo(modules, t);
}
/// <summary>
/// Generates sample contacts.
/// </summary>
private static void AddContactsTo(SocialModules modules, ICursor t)
{
foreach (var ev in new IContactEvent[]
{
new ContactCreated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet),
new ContactNameUpdated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet,"Benjamin","Franklin"),
}) modules.Contacts.Stream.AddEvent(ev, t);
}
}
}```
Add a second contact to initial sample data | ```c#
using System;
using SocialToolBox.Core.Database;
using SocialToolBox.Crm.Contact.Event;
namespace SocialToolBox.Sample.Web
{
/// <summary>
/// Data initially available in the system.
/// </summary>
public static class InitialData
{
public static readonly Id UserVictorNicollet = Id.Parse("aaaaaaaaaaa");
public static readonly Id ContactBenjaminFranklin = Id.Parse("aaaaaaaaaab");
public static readonly Id ContactJuliusCaesar = Id.Parse("aaaaaaaaaac");
/// <summary>
/// Generates sample data.
/// </summary>
public static void AddTo(SocialModules modules)
{
var t = modules.Database.OpenReadWriteCursor();
AddContactsTo(modules, t);
}
/// <summary>
/// Generates sample contacts.
/// </summary>
private static void AddContactsTo(SocialModules modules, ICursor t)
{
foreach (var ev in new IContactEvent[]
{
new ContactCreated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet),
new ContactNameUpdated(ContactBenjaminFranklin, DateTime.Parse("2013/09/26"),UserVictorNicollet,"Benjamin","Franklin"),
new ContactCreated(ContactJuliusCaesar, DateTime.Parse("2013/09/27"),UserVictorNicollet),
new ContactNameUpdated(ContactJuliusCaesar, DateTime.Parse("2013/09/27"),UserVictorNicollet,"Julius","Caesar")
}) modules.Contacts.Stream.AddEvent(ev, t);
}
}
}``` |
586c8f5b-0d5f-4ad6-80c6-212f9f366327 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System.Collections.Generic;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Gameplay
{
/// <summary>
/// Static class providing a <see cref="Create"/> convenience method to retrieve a correctly-initialised <see cref="GameplayState"/> instance in testing scenarios.
/// </summary>
public static class TestGameplayState
{
/// <summary>
/// Creates a correctly-initialised <see cref="GameplayState"/> instance for use in testing.
/// </summary>
public static GameplayState Create(Ruleset ruleset, IReadOnlyList<Mod>? mods = null, Score? score = null)
{
var beatmap = new TestBeatmap(ruleset.RulesetInfo);
var workingBeatmap = new TestWorkingBeatmap(beatmap);
var playableBeatmap = workingBeatmap.GetPlayableBeatmap(ruleset.RulesetInfo, mods);
return new GameplayState(playableBeatmap, ruleset, mods, score);
}
}
}
```
Fix tests by creating a score processor | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System.Collections.Generic;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Gameplay
{
/// <summary>
/// Static class providing a <see cref="Create"/> convenience method to retrieve a correctly-initialised <see cref="GameplayState"/> instance in testing scenarios.
/// </summary>
public static class TestGameplayState
{
/// <summary>
/// Creates a correctly-initialised <see cref="GameplayState"/> instance for use in testing.
/// </summary>
public static GameplayState Create(Ruleset ruleset, IReadOnlyList<Mod>? mods = null, Score? score = null)
{
var beatmap = new TestBeatmap(ruleset.RulesetInfo);
var workingBeatmap = new TestWorkingBeatmap(beatmap);
var playableBeatmap = workingBeatmap.GetPlayableBeatmap(ruleset.RulesetInfo, mods);
var scoreProcessor = ruleset.CreateScoreProcessor();
scoreProcessor.ApplyBeatmap(playableBeatmap);
return new GameplayState(playableBeatmap, ruleset, mods, score, scoreProcessor);
}
}
}
``` |
81ab114d-1b8d-46c9-aecc-7708df829f10 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeBreaker.Core;
using CodeBreaker.Core.Storage;
using Microsoft.EntityFrameworkCore;
namespace CodeBreaker.WebApp.Storage
{
public class ScoreStore : IScoreStore
{
private readonly CodeBreakerDbContext _dbContext;
public ScoreStore(CodeBreakerDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<Score[]> GetScores(int page, int size)
{
return (await _dbContext.Scores.ToListAsync())
.OrderBy(s => s.Attempts)
.ThenBy(s => s.Duration)
.Skip(page * size).Take(size)
.ToArray();
}
public async Task SaveScore(Score score)
{
await _dbContext.Scores.AddAsync(score);
await _dbContext.SaveChangesAsync();
}
public Task<bool> ScoreExists(Guid gameId)
{
return _dbContext.Scores.AnyAsync(s => s.GameId == gameId);
}
}
}```
Fix for slow high score loading | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeBreaker.Core;
using CodeBreaker.Core.Storage;
using Microsoft.EntityFrameworkCore;
namespace CodeBreaker.WebApp.Storage
{
public class ScoreStore : IScoreStore
{
private readonly CodeBreakerDbContext _dbContext;
public ScoreStore(CodeBreakerDbContext dbContext)
{
_dbContext = dbContext;
}
public Task<Score[]> GetScores(int page, int size)
{
return _dbContext.Scores
.OrderBy(s => s.Attempts)
.ThenBy(s => s.Duration)
.Skip(page * size).Take(size)
.ToArrayAsync();
}
public async Task SaveScore(Score score)
{
await _dbContext.Scores.AddAsync(score);
await _dbContext.SaveChangesAsync();
}
public Task<bool> ScoreExists(Guid gameId)
{
return _dbContext.Scores.AnyAsync(s => s.GameId == gameId);
}
}
}``` |
ed4ae521-c32f-4192-902c-d7a02588d43f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Glimpse.Web;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse
{
public class GlimpseWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
services.AddTransient<IRequestAuthorizerProvider, DefaultRequestAuthorizerProvider>();
services.AddTransient<IRequestHandlerProvider, DefaultRequestHandlerProvider>();
return services;
}
}
}```
Add default RequestRuntime to service registration | ```c#
using System;
using System.Collections.Generic;
using Glimpse.Web;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse
{
public class GlimpseWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
services.AddTransient<IRequestAuthorizerProvider, DefaultRequestAuthorizerProvider>();
services.AddTransient<IRequestHandlerProvider, DefaultRequestHandlerProvider>();
services.AddTransient<IRequestRuntimeProvider, DefaultRequestRuntimeProvider>();
return services;
}
}
}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.