doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
a16afcd2-2101-4ac6-8cd3-4501270ea245 | {
"language": "C#"
} | ```c#
using System.IO;
using BenchmarkDotNet.Attributes;
using FreeImageAPI;
using ImageMagick;
using DS = DevILSharp;
namespace Pfim.Benchmarks
{
public class TargaBenchmark
{
[Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga")]
public string Payload { get; set; }
private byte[] data;
[GlobalSetup]
public void SetupData()
{
data = File.ReadAllBytes(Payload);
DS.Bootstrap.Init();
}
[Benchmark]
public IImage Pfim() => Targa.Create(new MemoryStream(data));
[Benchmark]
public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));
[Benchmark]
public int ImageMagick()
{
var settings = new MagickReadSettings {Format = MagickFormat.Tga};
using (var image = new MagickImage(new MemoryStream(data), settings))
{
return image.Width;
}
}
[Benchmark]
public int DevILSharp()
{
using (var image = DS.Image.Load(data, DS.ImageType.Tga))
{
return image.Width;
}
}
[Benchmark]
public int TargaImage()
{
using (var image = new Paloma.TargaImage(new MemoryStream(data)))
{
return image.Stride;
}
}
}
}```
Include top left encoded targa in benchmark | ```c#
using System.IO;
using BenchmarkDotNet.Attributes;
using FreeImageAPI;
using ImageMagick;
using DS = DevILSharp;
namespace Pfim.Benchmarks
{
public class TargaBenchmark
{
[Params("true-32-rle-large.tga", "true-24-large.tga", "true-24.tga", "true-32-rle.tga", "rgb24_top_left")]
public string Payload { get; set; }
private byte[] data;
[GlobalSetup]
public void SetupData()
{
data = File.ReadAllBytes(Payload);
DS.Bootstrap.Init();
}
[Benchmark]
public IImage Pfim() => Targa.Create(new MemoryStream(data));
[Benchmark]
public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));
[Benchmark]
public int ImageMagick()
{
var settings = new MagickReadSettings {Format = MagickFormat.Tga};
using (var image = new MagickImage(new MemoryStream(data), settings))
{
return image.Width;
}
}
[Benchmark]
public int DevILSharp()
{
using (var image = DS.Image.Load(data, DS.ImageType.Tga))
{
return image.Width;
}
}
[Benchmark]
public int TargaImage()
{
using (var image = new Paloma.TargaImage(new MemoryStream(data)))
{
return image.Stride;
}
}
}
}``` |
8ab895c9-fbf4-42da-8749-496fd708ea1b | {
"language": "C#"
} | ```c#
using MetroOverhaul.Detours;
using MetroOverhaul.OptionsFramework.Attibutes;
namespace MetroOverhaul
{
[Options("MetroOverhaul")]
public class Options
{
private const string UNSUBPREP = "Unsubscribe Prep";
private const string STYLES = "Additional styles";
private const string GENERAL = "General settings";
public Options()
{
improvedPassengerTrainAi = true;
improvedMetroTrainAi = true;
metroUi = true;
ghostMode = false;
}
[Checkbox("Metro track customization UI (requires reloading from main menu)", GENERAL)]
public bool metroUi { set; get; }
[Checkbox("No depot mode (Trains will spawn at stations. Please bulldoze existing depots after enabling)", GENERAL)]
public bool depotsNotRequiredMode { set; get; }
[Checkbox("Improved PassengerTrainAI (Allows trains to return to depots)", GENERAL, typeof(PassengerTrainAIDetour), nameof(PassengerTrainAIDetour.ChangeDeployState))]
public bool improvedPassengerTrainAi { set; get; }
[Checkbox("Improved MetroTrainAI (Allows trains to properly spawn at surface)", GENERAL, typeof(MetroTrainAIDetour), nameof(MetroTrainAIDetour.ChangeDeployState))]
public bool improvedMetroTrainAi { set; get; }
[Checkbox("GHOST MODE (Load your MOM city with this ON and save before unsubscribing)", UNSUBPREP)]
public bool ghostMode { set; get; }
}
}```
Set default value for no depot mode. | ```c#
using MetroOverhaul.Detours;
using MetroOverhaul.OptionsFramework.Attibutes;
namespace MetroOverhaul
{
[Options("MetroOverhaul")]
public class Options
{
private const string UNSUBPREP = "Unsubscribe Prep";
private const string GENERAL = "General settings";
public Options()
{
improvedPassengerTrainAi = true;
improvedMetroTrainAi = true;
metroUi = true;
ghostMode = false;
depotsNotRequiredMode = false;
}
[Checkbox("Metro track customization UI (requires reloading from main menu)", GENERAL)]
public bool metroUi { set; get; }
[Checkbox("No depot mode (Trains will spawn at stations. Please bulldoze existing depots after enabling)", GENERAL)]
public bool depotsNotRequiredMode { set; get; }
[Checkbox("Improved PassengerTrainAI (Allows trains to return to depots)", GENERAL, typeof(PassengerTrainAIDetour), nameof(PassengerTrainAIDetour.ChangeDeployState))]
public bool improvedPassengerTrainAi { set; get; }
[Checkbox("Improved MetroTrainAI (Allows trains to properly spawn at surface)", GENERAL, typeof(MetroTrainAIDetour), nameof(MetroTrainAIDetour.ChangeDeployState))]
public bool improvedMetroTrainAi { set; get; }
[Checkbox("GHOST MODE (Load your MOM city with this ON and save before unsubscribing)", UNSUBPREP)]
public bool ghostMode { set; get; }
}
}``` |
b86886d7-4d34-44f6-aab9-85e400a031c4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PS.Mothership.Core.Common.Dto.Merchant
{
public class AddProspectDto
{
public string CompanyName { get; set; }
public string LocatorId
{
get
{
var id = Convert.ToString(((CompanyName.GetHashCode() ^ DateTime.UtcNow.Ticks.GetHashCode())
& 0xffffff) | 0x1000000, 16).Substring(1);
return id;
}
}
public long MainPhoneCountryKey { get; set; }
public string MainPhoneNumber { get; set; }
public Guid ContactGuid { get; set; }
public Guid AddressGuid { get; set; }
public Guid MainPhoneGuid { get; set; }
}
}
```
Remove LocatorId generation code from DTO since the locator id will be generated by a SQL CLR function | ```c#
using System;
namespace PS.Mothership.Core.Common.Dto.Merchant
{
public class AddProspectDto
{
public string CompanyName { get; set; }
public string LocatorId { get; set; }
public long MainPhoneCountryKey { get; set; }
public string MainPhoneNumber { get; set; }
public Guid ContactGuid { get; set; }
public Guid AddressGuid { get; set; }
public Guid MainPhoneGuid { get; set; }
}
}
``` |
1840309c-8b9d-46e6-8f7b-c83abcadf6e0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using NDesk.Options;
namespace make
{
public class CommandLine
{
public string Program { get; set; }
public string OutputFile { get; set; }
public string InputFile { get; set; }
public string[] Arguments { get; set; }
private CommandLine()
{
}
public static CommandLine Parse(string[] args)
{
var commandLine = new CommandLine();
var options = new OptionSet
{
{ "p|program=", v => commandLine.Program = v },
{ "o|out=", v => commandLine.OutputFile = v },
};
try
{
var remaining = options.Parse(args);
commandLine.ParseRemainingArguments(remaining);
}
catch (OptionException e)
{
Console.Error.WriteLine(e.Message);
}
return commandLine;
}
private void ParseRemainingArguments(List<string> remaining)
{
var input = "";
var options = new List<string>();
foreach (var arg in remaining)
{
if (arg.StartsWith("/") || arg.StartsWith("-"))
options.Add(arg);
else if (File.Exists(arg))
input = arg;
else
options.Add(arg);
}
InputFile = input;
Arguments = options.ToArray();
}
}
}```
Fix - The -t command-line switch is optional. Use first argument if omitted. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NDesk.Options;
namespace make
{
public class CommandLine
{
public string Program { get; set; }
public string OutputFile { get; set; }
public string InputFile { get; set; }
public string[] Arguments { get; set; }
private CommandLine()
{
}
public static CommandLine Parse(string[] args)
{
var commandLine = new CommandLine();
var options = new OptionSet
{
{ "p|program=", v => commandLine.Program = v },
{ "o|out=", v => commandLine.OutputFile = v },
};
try
{
var remaining = options.Parse(args);
commandLine.ParseRemainingArguments(remaining);
}
catch (OptionException e)
{
Console.Error.WriteLine(e.Message);
}
return commandLine;
}
private void ParseRemainingArguments(List<string> remaining)
{
var input = "";
var options = new List<string>();
var arguments = remaining.AsEnumerable();
if (Program == null)
{
Program = remaining.FirstOrDefault(a => !a.StartsWith("/") && !a.StartsWith("/"));
if (Program == null)
{
Console.Error.WriteLine("Wrong argument count. Please, use the -t switch to specify a valid program name.");
Environment.Exit(1);
}
arguments = remaining.Skip(1);
}
foreach (var arg in arguments)
{
if (arg.StartsWith("/") || arg.StartsWith("-"))
options.Add(arg);
else if (File.Exists(arg))
input = arg;
else
options.Add(arg);
}
InputFile = input;
Arguments = options.ToArray();
}
}
}``` |
1280c5ce-cffb-401d-a2d3-cfe78a84665a | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Screens.Backgrounds;
namespace osu.Game.Screens.Edit
{
internal class Editor : ScreenWhiteBox
{
//private WorkingBeatmap beatmap;
public Editor(WorkingBeatmap workingBeatmap)
{
//beatmap = workingBeatmap;
}
protected override BackgroundScreen CreateBackground() => new BackgroundScreenCustom(@"Backgrounds/bg4");
protected override void OnEntering(Screen last)
{
base.OnEntering(last);
Background.Schedule(() => Background.FadeColour(Color4.DarkGray, 500));
}
protected override bool OnExiting(Screen next)
{
Background.Schedule(() => Background.FadeColour(Color4.White, 500));
return base.OnExiting(next);
}
}
}
```
Stop playing the track in editor to avoid unused member warning | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Screens.Backgrounds;
namespace osu.Game.Screens.Edit
{
internal class Editor : ScreenWhiteBox
{
private WorkingBeatmap beatmap;
public Editor(WorkingBeatmap workingBeatmap)
{
beatmap = workingBeatmap;
}
protected override BackgroundScreen CreateBackground() => new BackgroundScreenCustom(@"Backgrounds/bg4");
protected override void OnEntering(Screen last)
{
base.OnEntering(last);
Background.Schedule(() => Background.FadeColour(Color4.DarkGray, 500));
beatmap.Track?.Stop();
}
protected override bool OnExiting(Screen next)
{
Background.Schedule(() => Background.FadeColour(Color4.White, 500));
beatmap.Track?.Start();
return base.OnExiting(next);
}
}
}
``` |
d5ab6a06-5bf6-40b9-b64e-85e9a2b98ebe | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using TirkxDownloader.Models;
namespace TirkxDownloader.Framework.Interface
{
public delegate void DownloadCompleteHandler(GeneralDownloadItem downloadInfo);
/// <summary>
/// Implementation that implement this interface should implement PropertyChanged Event for data-binding
/// </summary>
public interface IDownloader
{
bool IsDownloading { get; }
long MaximumBytesPerSecond { get; set; }
int MaxDownloadingItems { get; set; }
string DownloaderErrorMessage { get; set; }
int DownloadingItems { get; set; }
void DownloadItem(IDownloadItem item);
void DownloadItems(IEnumerable<IDownloadItem> items);
void StopDownloadItem(IDownloadItem item);
void StopDownloadItems(IEnumerable<IDownloadItem> items);
}
}
```
Change date type of MaxDownloadingItems to byte and change to get only | ```c#
using System.Collections.Generic;
using TirkxDownloader.Models;
namespace TirkxDownloader.Framework.Interface
{
public delegate void DownloadCompleteHandler(GeneralDownloadItem downloadInfo);
/// <summary>
/// Implementation that implement this interface should implement PropertyChanged Event for data-binding
/// </summary>
public interface IDownloader
{
bool IsDownloading { get; }
long MaximumBytesPerSecond { get; }
byte MaxDownloadingItems { get; }
string DownloaderErrorMessage { get; set; }
int DownloadingItems { get; set; }
void DownloadItem(IDownloadItem item);
void DownloadItems(IEnumerable<IDownloadItem> items);
void StopDownloadItem(IDownloadItem item);
void StopDownloadItems(IEnumerable<IDownloadItem> items);
}
}
``` |
5e5e0c65-14b4-4b31-a812-565ad5a1948e | {
"language": "C#"
} | ```c#
using System;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.Extensions.Configuration;
namespace QueueGettingStarted
{
public class Program
{
public static void Main(string[] args)
{
// configuration
var builder = new ConfigurationBuilder()
.AddJsonFile("./appsettings.json")
.AddUserSecrets()
.AddEnvironmentVariables();
Configuration = builder.Build();
// options
ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options);
Console.WriteLine("Queue encryption sample");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("");
CloudQueueClient client = storageAccount.CreateCloudQueueClient();
if(client != null){
Console.WriteLine("Client created");
} else {
Console.WriteLine("Error creating client");
}
Console.ReadKey();
}
static IConfiguration Configuration { get; set; }
static AzureStorageOptions Options {get; set; } = new AzureStorageOptions();
}
class AzureStorageOptions {
public string ConnectionString { get; set; }
}
}
```
Read connection string from configuration | ```c#
using System;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.Extensions.Configuration;
namespace QueueGettingStarted
{
public class Program
{
public static void Main(string[] args)
{
// configuration
var builder = new ConfigurationBuilder()
.AddJsonFile("./appsettings.json")
.AddUserSecrets()
.AddEnvironmentVariables();
Configuration = builder.Build();
// options
ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options);
Console.WriteLine("Queue encryption sample");
Console.WriteLine($"Configuration for ConnectionString: {Options.ConnectionString}");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Options.ConnectionString);
CloudQueueClient client = storageAccount.CreateCloudQueueClient();
if (client != null)
{
Console.WriteLine("Client created");
}
else
{
Console.WriteLine("Error creating client");
}
Console.ReadKey();
}
static IConfiguration Configuration { get; set; }
static AzureStorageOptions Options { get; set; } = new AzureStorageOptions();
}
class AzureStorageOptions
{
public string ConnectionString { get; set; }
}
}
``` |
76f61dfc-3714-4562-8b50-890773c682f6 | {
"language": "C#"
} | ```c#
using LogBook.Services;
using LogBook.Services.Models;
using Portal.CMS.Web.Architecture.ViewEngines;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Razor;
using System.Web.Routing;
using System.Web.WebPages;
namespace Portal.CMS.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
ViewEngines.Engines.Add(new CSSViewEngine());
RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage());
WebPageHttpHandler.RegisterExtension("cscss");
MvcHandler.DisableMvcResponseHeader = true;
}
protected void Application_Error()
{
var logHandler = new LogHandler();
var exception = Server.GetLastError();
logHandler.WriteLog(LogType.Error, "PortalCMS", exception, "An Exception has occured while Running PortalCMS", string.Empty);
if (System.Configuration.ConfigurationManager.AppSettings["CustomErrorPage"] == "true")
{
Response.Redirect("~/Home/Error");
}
}
}
}```
Add UserName to LogEntries When Authenticated | ```c#
using LogBook.Services;
using LogBook.Services.Models;
using Portal.CMS.Web.Architecture.Helpers;
using Portal.CMS.Web.Architecture.ViewEngines;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Razor;
using System.Web.Routing;
using System.Web.WebPages;
namespace Portal.CMS.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
ViewEngines.Engines.Add(new CSSViewEngine());
RazorCodeLanguage.Languages.Add("cscss", new CSharpRazorCodeLanguage());
WebPageHttpHandler.RegisterExtension("cscss");
MvcHandler.DisableMvcResponseHeader = true;
}
protected void Application_Error()
{
var logHandler = new LogHandler();
var exception = Server.GetLastError();
var userAccount = UserHelper.UserId;
logHandler.WriteLog(LogType.Error, "PortalCMS", exception, "An Exception has occured while Running PortalCMS", userAccount.ToString());
if (System.Configuration.ConfigurationManager.AppSettings["CustomErrorPage"] == "true")
{
Response.Redirect("~/Home/Error");
}
}
}
}``` |
fd34fb6d-3665-4f19-a8d9-f28b7351e58a | {
"language": "C#"
} | ```c#
namespace SnappyMap.IO
{
using System;
using System.Collections.Generic;
using System.Linq;
using SnappyMap.Data;
[Serializable]
public struct SectionMapping
{
public SectionMapping(SectionType type, params string[] sections)
: this()
{
this.Type = type;
this.Sections = sections.ToList();
}
public SectionType Type { get; set; }
public List<string> Sections { get; set; }
}
[Serializable]
public class SectionConfig
{
public SectionConfig()
{
this.SectionMappings = new List<SectionMapping>();
}
public int SeaLevel { get; set; }
public List<SectionMapping> SectionMappings { get; private set; }
}
}
```
Fix potential crash in old .NET versions | ```c#
namespace SnappyMap.IO
{
using System;
using System.Collections.Generic;
using System.Linq;
using SnappyMap.Data;
[Serializable]
public struct SectionMapping
{
public SectionMapping(SectionType type, params string[] sections)
: this()
{
this.Type = type;
this.Sections = sections.ToList();
}
public SectionType Type { get; set; }
public List<string> Sections { get; set; }
}
[Serializable]
public class SectionConfig
{
public SectionConfig()
{
this.SectionMappings = new List<SectionMapping>();
}
public int SeaLevel { get; set; }
public List<SectionMapping> SectionMappings { get; set; }
}
}
``` |
0b8f0300-506a-4a5d-9494-8b0a861fa4fe | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace elbgb.gameboy
{
class Timer
{
public static class Registers
{
public const ushort DIV = 0xFF04;
public const ushort TIMA = 0xFF05;
public const ushort TMA = 0xFF06;
public const ushort TAC = 0xFF07;
}
private GameBoy _gb;
private ulong _lastUpdate;
private ushort _div;
public Timer(GameBoy gameBoy)
{
_gb = gameBoy;
}
public byte ReadByte(ushort address)
{
switch (address)
{
case Registers.DIV: return (byte)(_div >> 8);
default:
throw new NotImplementedException();
}
}
public void WriteByte(ushort address, byte value)
{
switch (address)
{
// a write always clears the upper 8 bits of DIV, regardless of value
case Registers.DIV: _div &= 0x00FF; break;
default:
throw new NotImplementedException();
}
}
public void Update()
{
ulong cyclesToUpdate = _gb.Timestamp - _lastUpdate;
_lastUpdate = _gb.Timestamp;
// update divider
_div += (ushort)cyclesToUpdate;
}
}
}
```
Split out divider update in timer | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace elbgb.gameboy
{
class Timer
{
public static class Registers
{
public const ushort DIV = 0xFF04;
public const ushort TIMA = 0xFF05;
public const ushort TMA = 0xFF06;
public const ushort TAC = 0xFF07;
}
private GameBoy _gb;
private ulong _lastUpdate;
private ushort _div;
public Timer(GameBoy gameBoy)
{
_gb = gameBoy;
}
public byte ReadByte(ushort address)
{
switch (address)
{
case Registers.DIV: return (byte)(_div >> 8);
default:
throw new NotImplementedException();
}
}
public void WriteByte(ushort address, byte value)
{
switch (address)
{
// a write always clears the upper 8 bits of DIV, regardless of value
case Registers.DIV: _div &= 0x00FF; break;
default:
throw new NotImplementedException();
}
}
public void Update()
{
ulong cyclesToUpdate = _gb.Timestamp - _lastUpdate;
_lastUpdate = _gb.Timestamp;
UpdateDivider(cyclesToUpdate);
}
private void UpdateDivider(ulong cyclesToUpdate)
{
_div += (ushort)cyclesToUpdate;
}
}
}
``` |
c1981c1b-3305-4dd9-93ff-3e97e9ab21f9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MeDaUmFilme
{
public class Movie
{
public string Title { get; set; }
public string Year { get; set; }
}
public class OmdbResult
{
public List<Movie> Search { get; set; }
}
}
```
Add image link to movie | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MeDaUmFilme
{
public class Movie
{
public string Title { get; set; }
public string Year { get; set; }
public string Poster { get; set; }
public string Type { get; set; }
}
public class OmdbResult
{
public List<Movie> Search { get; set; }
}
}
``` |
791b2599-91ca-454d-ae12-c0368f76409f | {
"language": "C#"
} | ```c#
using Microsoft.EntityFrameworkCore;
using Mitternacht.Services.Database;
namespace Mitternacht.Services
{
public class DbService
{
private readonly DbContextOptions _options;
public DbService(IBotCredentials creds)
{
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlite(creds.DbConnectionString);
_options = optionsBuilder.Options;
//switch (_creds.Db.Type.ToUpperInvariant())
//{
// case "SQLITE":
// dbType = typeof(NadekoSqliteContext);
// break;
// //case "SQLSERVER":
// // dbType = typeof(NadekoSqlServerContext);
// // break;
// default:
// break;
//}
}
public NadekoContext GetDbContext()
{
var context = new NadekoContext(_options);
context.Database.SetCommandTimeout(60);
context.Database.Migrate();
context.EnsureSeedData();
//set important sqlite stuffs
var conn = context.Database.GetDbConnection();
conn.Open();
context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL");
using (var com = conn.CreateCommand())
{
com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF";
com.ExecuteNonQuery();
}
return context;
}
public IUnitOfWork UnitOfWork =>
new UnitOfWork(GetDbContext());
}
}```
Format file, remove outcommented code. | ```c#
using Microsoft.EntityFrameworkCore;
using Mitternacht.Services.Database;
namespace Mitternacht.Services {
public class DbService {
private readonly DbContextOptions _options;
public DbService(IBotCredentials creds) {
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlite(creds.DbConnectionString);
_options = optionsBuilder.Options;
}
public NadekoContext GetDbContext() {
var context = new NadekoContext(_options);
context.Database.SetCommandTimeout(60);
context.Database.Migrate();
context.EnsureSeedData();
//set important sqlite stuffs
var conn = context.Database.GetDbConnection();
conn.Open();
context.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL");
using(var com = conn.CreateCommand()) {
com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF";
com.ExecuteNonQuery();
}
return context;
}
public IUnitOfWork UnitOfWork =>
new UnitOfWork(GetDbContext());
}
}``` |
2e5041ee-728d-4664-9830-6bffc7a79c99 | {
"language": "C#"
} | ```c#
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Log4NetIntegration.Logging
{
using System.IO;
using MassTransit.Logging;
using log4net;
using log4net.Config;
public class Log4NetLogger :
ILogger
{
public MassTransit.Logging.ILog Get(string name)
{
return new Log4NetLog(LogManager.GetLogger(name));
}
public static void Use()
{
Logger.UseLogger(new Log4NetLogger());
}
public static void Use(string file)
{
Logger.UseLogger(new Log4NetLogger());
var configFile = new FileInfo(file);
XmlConfigurator.Configure(configFile);
}
}
}```
Fix Log4Net path for loading config file | ```c#
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Log4NetIntegration.Logging
{
using System;
using System.IO;
using MassTransit.Logging;
using log4net;
using log4net.Config;
public class Log4NetLogger :
ILogger
{
public MassTransit.Logging.ILog Get(string name)
{
return new Log4NetLog(LogManager.GetLogger(name));
}
public static void Use()
{
Logger.UseLogger(new Log4NetLogger());
}
public static void Use(string file)
{
Logger.UseLogger(new Log4NetLogger());
file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
var configFile = new FileInfo(file);
XmlConfigurator.Configure(configFile);
}
}
}``` |
5014f385-b21a-46af-b7f0-4099914e7ef6 | {
"language": "C#"
} | ```c#
// TokenList.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
public class TokenList {
internal TokenList() {
}
[IntrinsicProperty]
[ScriptName("length")]
public int Count {
get {
return 0;
}
}
[IntrinsicProperty]
public string this[int index] {
get {
return null;
}
}
public bool Contains(string token) {
return false;
}
public void Add(string token) {
}
public void Remove(string token) {
}
public bool Toggle(string token) {
return false;
}
public override string ToString() {
return null;
}
}
}```
Update access modifiers for metadata class | ```c#
// TokenList.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
public sealed class TokenList {
private TokenList() {
}
[IntrinsicProperty]
[ScriptName("length")]
public int Count {
get {
return 0;
}
}
[IntrinsicProperty]
public string this[int index] {
get {
return null;
}
}
public bool Contains(string token) {
return false;
}
public void Add(string token) {
}
public void Remove(string token) {
}
public bool Toggle(string token) {
return false;
}
public override string ToString() {
return null;
}
}
}
``` |
1e50fa1d-6342-4598-aac2-018f260aaaef | {
"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 System;
using osu.Framework;
using osu.Framework.Platform;
namespace osu.Game.Tests
{
public static class VisualTestRunner
{
[STAThread]
public static int Main(string[] args)
{
using (DesktopGameHost host = Host.GetSuitableDesktopHost(@"osu", new HostOptions { BindIPC = true, }))
{
host.Run(new OsuTestBrowser());
return 0;
}
}
}
}
```
Update interactive visual test runs to use development directory | ```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 System;
using osu.Framework;
using osu.Framework.Platform;
namespace osu.Game.Tests
{
public static class VisualTestRunner
{
[STAThread]
public static int Main(string[] args)
{
using (DesktopGameHost host = Host.GetSuitableDesktopHost(@"osu-development", new HostOptions { BindIPC = true, }))
{
host.Run(new OsuTestBrowser());
return 0;
}
}
}
}
``` |
627ebf99-042c-41c6-b45a-466a20c0c584 | {
"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("DiffPlex")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DiffPlex")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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.2.0.*")]
```
Update file version of DLL to match NuGet package. | ```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("DiffPlex")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DiffPlex")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Assembly version should consist of just major and minor versions.
// We omit revision and build numbers so that folks who compile against
// 1.2.0 can also run against 1.2.1 without a recompile or a binding redirect.
[assembly: AssemblyVersion("1.2.0.0")]
// File version can include the revision and build numbers so
// file properties can reveal the true version of this build.
[assembly: AssemblyFileVersion("1.2.1.0")]
``` |
b260e21b-534d-41db-b9bd-292432319ca8 | {
"language": "C#"
} | ```c#
using System.IO;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Wox.Plugin.WebSearch
{
public class WebSearch
{
public const string DefaultIcon = "web_search.png";
public string Title { get; set; }
public string ActionKeyword { get; set; }
[NotNull]
private string _icon = DefaultIcon;
[NotNull]
public string Icon
{
get { return _icon; }
set
{
_icon = value;
IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value);
}
}
/// <summary>
/// All icon should be put under Images directory
/// </summary>
[NotNull]
[JsonIgnore]
internal string IconPath { get; private set; }
public string Url { get; set; }
public bool Enabled { get; set; }
}
}```
Fix default icon path when add new web search | ```c#
using System.IO;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Wox.Plugin.WebSearch
{
public class WebSearch
{
public const string DefaultIcon = "web_search.png";
public string Title { get; set; }
public string ActionKeyword { get; set; }
[NotNull]
private string _icon = DefaultIcon;
[NotNull]
public string Icon
{
get { return _icon; }
set
{
_icon = value;
IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value);
}
}
/// <summary>
/// All icon should be put under Images directory
/// </summary>
[NotNull]
[JsonIgnore]
internal string IconPath { get; private set; } = Path.Combine
(
WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, DefaultIcon
);
public string Url { get; set; }
public bool Enabled { get; set; }
}
}``` |
71213c53-c4b6-4a7c-9189-a600c467fe33 | {
"language": "C#"
} | ```c#
using MultiMiner.Blockchain.Data;
using MultiMiner.ExchangeApi;
using MultiMiner.ExchangeApi.Data;
using MultiMiner.Utility.Net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace MultiMiner.Blockchain
{
public class ApiContext : IApiContext
{
public IEnumerable<ExchangeInformation> GetExchangeInformation()
{
WebClient webClient = new ApiWebClient();
webClient.Encoding = Encoding.UTF8;
string response = webClient.DownloadString(new Uri(GetApiUrl()));
Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response);
List<ExchangeInformation> results = new List<ExchangeInformation>();
foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries)
{
results.Add(new ExchangeInformation()
{
SourceCurrency = "BTC",
TargetCurrency = keyValuePair.Key,
TargetSymbol = keyValuePair.Value.Symbol,
ExchangeRate = keyValuePair.Value.Last
});
}
return results;
}
public string GetInfoUrl()
{
return "https://blockchain.info";
}
public string GetApiUrl()
{
//use HTTP as HTTPS is down at times and returns:
//The request was aborted: Could not create SSL/TLS secure channel.
return "http://blockchain.info/ticker";
}
public string GetApiName()
{
return "Blockchain";
}
}
}
```
Introduce a retry machanism with the Blockchain API | ```c#
using MultiMiner.Blockchain.Data;
using MultiMiner.ExchangeApi;
using MultiMiner.ExchangeApi.Data;
using MultiMiner.Utility.Net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace MultiMiner.Blockchain
{
public class ApiContext : IApiContext
{
public IEnumerable<ExchangeInformation> GetExchangeInformation()
{
ApiWebClient webClient = new ApiWebClient();
webClient.Encoding = Encoding.UTF8;
string response = webClient.DownloadFlakyString(new Uri(GetApiUrl()));
Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response);
List<ExchangeInformation> results = new List<ExchangeInformation>();
foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries)
{
results.Add(new ExchangeInformation()
{
SourceCurrency = "BTC",
TargetCurrency = keyValuePair.Key,
TargetSymbol = keyValuePair.Value.Symbol,
ExchangeRate = keyValuePair.Value.Last
});
}
return results;
}
public string GetInfoUrl()
{
return "https://blockchain.info";
}
public string GetApiUrl()
{
//use HTTP as HTTPS is down at times and returns:
//The request was aborted: Could not create SSL/TLS secure channel.
return "https://blockchain.info/ticker";
}
public string GetApiName()
{
return "Blockchain";
}
}
}
``` |
af3ef207-f075-493e-ac64-e4680655a22c | {
"language": "C#"
} | ```c#
// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Annotations
{
/// <summary>
/// Indicates that a value-type field which would otherwise by <c>readonly</c>
/// is read/write so that invoking members on the field avoids taking a copy of
/// the field value.
/// </summary>
/// <remarks>
/// See http://msmvps.com/blogs/jon_skeet/archive/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields.aspx
/// for details of why we're doing this at all.
/// </remarks>
[AttributeUsage(AttributeTargets.Field)]
internal sealed class ReadWriteForEfficiencyAttribute : Attribute
{
}
}
```
Fix the URL to point at the Noda Time blog because msmvps.com 503. | ```c#
// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Annotations
{
/// <summary>
/// Indicates that a value-type field which would otherwise by <c>readonly</c>
/// is read/write so that invoking members on the field avoids taking a copy of
/// the field value.
/// </summary>
/// <remarks>
/// See http://noda-time.blogspot.com/2014/07/micro-optimization-surprising.html
/// for details of why we're doing this at all.
/// </remarks>
[AttributeUsage(AttributeTargets.Field)]
internal sealed class ReadWriteForEfficiencyAttribute : Attribute
{
}
}
``` |
abafac8f-318d-4c65-9d44-1c1edb6e85aa | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Training.CSharpWorkshop.Tests
{
[TestClass]
public class ProgramTests
{
[Ignore]
[TestMethod]
public void IgnoreTest()
{
Assert.Fail();
}
[TestMethod()]
public void GetRoleMessageForAdminTest()
{
// Arrange
var userName = "Andrew";
var expected = "Role: Admin.";
// Act
var actual = Program.GetRoleMessage(userName);
// Assert
Assert.AreEqual(expected, actual);
}
}
}
```
Update Console Program with a Condition - Add unit test for Guest role | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Training.CSharpWorkshop.Tests
{
[TestClass]
public class ProgramTests
{
[Ignore]
[TestMethod]
public void IgnoreTest()
{
Assert.Fail();
}
[TestMethod()]
public void GetRoleMessageForAdminTest()
{
// Arrange
var userName = "Andrew";
var expected = "Role: Admin.";
// Act
var actual = Program.GetRoleMessage(userName);
// Assert
Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void GetRoleMessageForGuestTest()
{
// Arrange
var userName = "Dave";
var expected = "Role: Guest.";
// Act
var actual = Program.GetRoleMessage(userName);
// Assert
Assert.AreEqual(expected, actual);
}
}
}
``` |
39d58d9e-1208-41ec-84d7-36fa2bfd5f5c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace TramlineFive.Converters
{
public class TimingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string[] timings = (string[])value;
StringBuilder builder = new StringBuilder();
foreach (string singleTiming in timings)
{
TimeSpan timing;
if (TimeSpan.TryParse((string)singleTiming, out timing))
{
TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes < 0 ? 0 : timeLeft.Minutes);
}
}
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
```
Fix showing only minutes of the hour insteal of total minutes in virtual table. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace TramlineFive.Converters
{
public class TimingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string[] timings = (string[])value;
StringBuilder builder = new StringBuilder();
foreach (string singleTiming in timings)
{
TimeSpan timing;
if (TimeSpan.TryParse((string)singleTiming, out timing))
{
int timeLeft = (int)(timing - DateTime.Now.TimeOfDay).TotalMinutes;
builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft < 0 ? 0 : timeLeft);
}
}
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
``` |
2a793ab2-86be-4c25-a300-5c388fb7b2aa | {
"language": "C#"
} | ```c#
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Hangfire.Mongo.Migration.Steps.Version11
{
/// <summary>
/// Create signal capped collection
/// </summary>
internal class UseObjectIdForJob : IMongoMigrationStep
{
public MongoSchema TargetSchema => MongoSchema.Version11;
public long Sequence => 0;
public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationBag migrationBag)
{
var jobsCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".job");
SetFieldAsObjectId(jobsCollection, "_id");
var jobQueueCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".jobQueue");
SetFieldAsObjectId(jobQueueCollection, "JobId");
return true;
}
private static void SetFieldAsObjectId(IMongoCollection<BsonDocument> collection, string fieldName)
{
var documents = collection.Find(new BsonDocument()).ToList();
if(!documents.Any()) return;
foreach (var doc in documents)
{
var jobIdString = doc[fieldName].ToString();
doc[fieldName] = ObjectId.Parse(jobIdString);
}
collection.DeleteMany(new BsonDocument());
collection.InsertMany(documents);
}
}
}
```
Fix broken migration for v11 | ```c#
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Hangfire.Mongo.Migration.Steps.Version11
{
/// <summary>
/// Create signal capped collection
/// </summary>
internal class UseObjectIdForJob : IMongoMigrationStep
{
public MongoSchema TargetSchema => MongoSchema.Version11;
public long Sequence => 0;
public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationBag migrationBag)
{
var jobsCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".job");
SetFieldAsObjectId(jobsCollection, "_id");
var jobQueueCollection = database.GetCollection<BsonDocument>(storageOptions.Prefix + ".jobQueue");
SetFieldAsObjectId(jobQueueCollection, "JobId");
return true;
}
private static void SetFieldAsObjectId(IMongoCollection<BsonDocument> collection, string fieldName)
{
var filter = Builders<BsonDocument>.Filter.Exists(fieldName);
var documents = collection.Find(filter).ToList();
if (!documents.Any()) return;
foreach (var doc in documents)
{
var jobIdString = doc[fieldName].ToString();
doc[fieldName] = ObjectId.Parse(jobIdString);
}
collection.DeleteMany(new BsonDocument());
collection.InsertMany(documents);
}
}
}
``` |
2f4207b8-4307-4dcc-94b2-7de1e9bd3c46 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hjson;
namespace HjsonSample
{
class Program
{
static void Main(string[] args)
{
var data=HjsonValue.Load("test.hjson").Qo();
Console.WriteLine(data.Qs("hello"));
Console.WriteLine("Saving as json...");
HjsonValue.Save(data, "test.json");
Console.WriteLine("Saving as hjson...");
HjsonValue.Save(data, "test2.hjson");
// edit (preserve whitespace and comments)
var wdata=(WscJsonObject)HjsonValue.LoadWsc(new StreamReader("test.hjson")).Qo();
// edit like you normally would
wdata["hugo"]="value";
// optionally set order and comments:
wdata.Order.Insert(2, "hugo");
wdata.Comments["hugo"]="just another test";
var sw=new StringWriter();
HjsonValue.SaveWsc(wdata, sw);
Console.WriteLine(sw.ToString());
}
}
}
```
Update sample to use Save() and Load() | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hjson;
namespace HjsonSample
{
class Program
{
static void Main(string[] args)
{
var data=HjsonValue.Load("test.hjson").Qo();
Console.WriteLine(data.Qs("hello"));
Console.WriteLine("Saving as json...");
HjsonValue.Save(data, "test.json");
Console.WriteLine("Saving as hjson...");
HjsonValue.Save(data, "test2.hjson");
// edit (preserve whitespace and comments)
var wdata=(WscJsonObject)HjsonValue.Load(new StreamReader("test.hjson"), preserveComments:true).Qo();
// edit like you normally would
wdata["hugo"]="value";
// optionally set order and comments:
wdata.Order.Insert(2, "hugo");
wdata.Comments["hugo"]="just another test";
var sw=new StringWriter();
HjsonValue.Save(wdata, sw, new HjsonOptions() { KeepWsc = true });
Console.WriteLine(sw.ToString());
}
}
}
``` |
2180bf70-cde7-467f-9b71-334e8021735c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;
namespace SolidworksAddinFramework
{
public static class DisposableExtensions
{
public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
{
return new CompositeDisposable(d);
}
}
}
```
Add extension method to add a disposable to a composite disposable | ```c#
using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;
namespace SolidworksAddinFramework
{
public static class DisposableExtensions
{
public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
{
return new CompositeDisposable(d);
}
public static void DisposeWith(this IDisposable disposable, CompositeDisposable container)
{
container.Add(disposable);
}
}
}
``` |
01e4eb65-1ee8-400e-8003-41648d473e49 | {
"language": "C#"
} | ```c#
// -----------------------------------------------------------------------
// <copyright file="MenuStyle.cs" company="Steven Kirk">
// Copyright 2015 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Perspex.Themes.Default
{
using Perspex.Controls;
using Perspex.Controls.Presenters;
using Perspex.Styling;
using System.Linq;
public class MenuStyle : Styles
{
public MenuStyle()
{
this.AddRange(new[]
{
new Style(x => x.OfType<Menu>())
{
Setters = new[]
{
new Setter(Menu.TemplateProperty, ControlTemplate.Create<Menu>(this.Template)),
},
},
});
}
private Control Template(Menu control)
{
return new Border
{
[~Border.BackgroundProperty] = control[~Menu.BackgroundProperty],
[~Border.BorderBrushProperty] = control[~Menu.BorderBrushProperty],
[~Border.BorderThicknessProperty] = control[~Menu.BorderThicknessProperty],
[~Border.PaddingProperty] = control[~Menu.PaddingProperty],
Content = new ItemsPresenter
{
Name = "itemsPresenter",
[~ItemsPresenter.ItemsProperty] = control[~Menu.ItemsProperty],
[~ItemsPresenter.ItemsPanelProperty] = control[~Menu.ItemsPanelProperty],
}
};
}
}
}
```
Use TabNavigation.Continue for top-level menu. | ```c#
// -----------------------------------------------------------------------
// <copyright file="MenuStyle.cs" company="Steven Kirk">
// Copyright 2015 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Perspex.Themes.Default
{
using System.Linq;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using Perspex.Input;
using Perspex.Styling;
public class MenuStyle : Styles
{
public MenuStyle()
{
this.AddRange(new[]
{
new Style(x => x.OfType<Menu>())
{
Setters = new[]
{
new Setter(Menu.TemplateProperty, ControlTemplate.Create<Menu>(this.Template)),
},
},
});
}
private Control Template(Menu control)
{
return new Border
{
[~Border.BackgroundProperty] = control[~Menu.BackgroundProperty],
[~Border.BorderBrushProperty] = control[~Menu.BorderBrushProperty],
[~Border.BorderThicknessProperty] = control[~Menu.BorderThicknessProperty],
[~Border.PaddingProperty] = control[~Menu.PaddingProperty],
Content = new ItemsPresenter
{
Name = "itemsPresenter",
[~ItemsPresenter.ItemsProperty] = control[~Menu.ItemsProperty],
[~ItemsPresenter.ItemsPanelProperty] = control[~Menu.ItemsPanelProperty],
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Continue,
}
};
}
}
}
``` |
9512f6ae-cf76-486e-a25c-eaee25b855e9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Bugsnag.Common
{
public class BugsnagClient : IClient
{
static Uri _uri = new Uri("http://notify.bugsnag.com");
static Uri _sslUri = new Uri("https://notify.bugsnag.com");
static JsonSerializerSettings _settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
static HttpClient _HttpClient { get; } = new HttpClient();
public void Send(INotice notice) => Send(notice, true);
public void Send(INotice notice, bool useSSL)
{
var _ = SendAsync(notice, useSSL).Result;
}
public Task<HttpResponseMessage> SendAsync(INotice notice) => SendAsync(notice, true);
public Task<HttpResponseMessage> SendAsync(INotice notice, bool useSSL)
{
var uri = useSSL ? _sslUri : _uri;
var json = JsonConvert.SerializeObject(notice, _settings);
var content = new StringContent(json, Encoding.UTF8, "application/json");
return _HttpClient.PostAsync(uri, content);
}
}
}
```
Use Wait() instead of Result in void overload | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Bugsnag.Common
{
public class BugsnagClient : IClient
{
static Uri _uri = new Uri("http://notify.bugsnag.com");
static Uri _sslUri = new Uri("https://notify.bugsnag.com");
static JsonSerializerSettings _settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
static HttpClient _HttpClient { get; } = new HttpClient();
public void Send(INotice notice) => Send(notice, true);
public void Send(INotice notice, bool useSSL) => SendAsync(notice, useSSL).Wait();
public Task<HttpResponseMessage> SendAsync(INotice notice) => SendAsync(notice, true);
public Task<HttpResponseMessage> SendAsync(INotice notice, bool useSSL)
{
var uri = useSSL ? _sslUri : _uri;
var json = JsonConvert.SerializeObject(notice, _settings);
var content = new StringContent(json, Encoding.UTF8, "application/json");
return _HttpClient.PostAsync(uri, content);
}
}
}
``` |
29179b78-8666-4b53-aba9-f68b2ce6b6f2 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;
namespace StackExchange.Profiling.Mvc
{
/// <summary>
/// Extension methods for configuring MiniProfiler for MVC
/// </summary>
public static class MvcExtensions
{
/// <summary>
/// Adds MiniProfiler timings for actions and views
/// </summary>
/// <param name="services">The services collection to configure</param>
public static IServiceCollection AddMiniProfiler(this IServiceCollection services) =>
services.AddTransient<IConfigureOptions<MvcOptions>, MiniPofilerSetup>()
.AddTransient<IConfigureOptions<MvcViewOptions>, MiniPofilerSetup>();
}
internal class MiniPofilerSetup : IConfigureOptions<MvcViewOptions>, IConfigureOptions<MvcOptions>
{
public void Configure(MvcViewOptions options)
{
var copy = options.ViewEngines.ToList();
options.ViewEngines.Clear();
foreach (var item in copy)
{
options.ViewEngines.Add(new ProfilingViewEngine(item));
}
}
public void Configure(MvcOptions options)
{
options.Filters.Add(new ProfilingActionFilter());
}
}
}
```
Simplify view engine wrapping for MVC Core | ```c#
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;
namespace StackExchange.Profiling.Mvc
{
/// <summary>
/// Extension methods for configuring MiniProfiler for MVC
/// </summary>
public static class MvcExtensions
{
/// <summary>
/// Adds MiniProfiler timings for actions and views
/// </summary>
/// <param name="services">The services collection to configure</param>
public static IServiceCollection AddMiniProfiler(this IServiceCollection services) =>
services.AddTransient<IConfigureOptions<MvcOptions>, MiniPofilerSetup>()
.AddTransient<IConfigureOptions<MvcViewOptions>, MiniPofilerSetup>();
}
internal class MiniPofilerSetup : IConfigureOptions<MvcViewOptions>, IConfigureOptions<MvcOptions>
{
public void Configure(MvcViewOptions options)
{
for (var i = 0; i < options.ViewEngines.Count; i++)
{
options.ViewEngines[i] = new ProfilingViewEngine(options.ViewEngines[i]);
}
}
public void Configure(MvcOptions options)
{
options.Filters.Add(new ProfilingActionFilter());
}
}
}
``` |
fe23914d-4a59-45f4-b306-d04a4cc6f691 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Host.Client.Test {
[ExcludeFromCodeCoverage]
public class RStringExtensionsTest {
[Test]
[Category.Variable.Explorer]
public void ConvertCharacterCodesTest() {
string target = "<U+4E2D><U+570B><U+8A9E>";
target.ConvertCharacterCodes().Should().Be("中國語");
}
}
}
```
Add some tests for string extension. | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Host.Client.Test {
[ExcludeFromCodeCoverage]
public class RStringExtensionsTest {
[Test]
[Category.Variable.Explorer]
public void ConvertCharacterCodesTest() {
string target = "<U+4E2D><U+570B><U+8A9E>";
target.ConvertCharacterCodes().Should().Be("中國語");
}
[CompositeTest]
[InlineData("\t\n", "\"\\t\\n\"")]
[InlineData("\\t\n", "\"\\\\t\\n\"")]
[InlineData("\n", "\"\\n\"")]
[InlineData("\\n", "\"\\\\n\"")]
public void EscapeCharacterTest(string source, string expectedLiteral) {
string actualLiteral = source.ToRStringLiteral();
actualLiteral.Should().Be(expectedLiteral);
string actualSource = actualLiteral.FromRStringLiteral();
actualSource.Should().Be(source);
}
}
}
``` |
0be32616-c2b0-4ec6-bfe9-4aee1d89d63c | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Strike;
using Strike.Jint;
namespace PicklesDoc.Pickles
{
public class StrikeMarkdownProvider : IMarkdownProvider
{
private readonly Markdownify markdownify;
public StrikeMarkdownProvider()
{
this.markdownify = new Markdownify(
new Options { Xhtml = true },
new RenderMethods());
}
public string Transform(string text)
{
return this.markdownify.Transform(text);
}
}
}```
Add handling for non breaking spaces | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Strike;
using Strike.Jint;
namespace PicklesDoc.Pickles
{
public class StrikeMarkdownProvider : IMarkdownProvider
{
private readonly Markdownify markdownify;
public StrikeMarkdownProvider()
{
this.markdownify = new Markdownify(
new Options { Xhtml = true },
new RenderMethods());
}
public string Transform(string text)
{
return this.markdownify.Transform(text).Replace(" ", string.Empty);
}
}
}``` |
45b1f569-3569-4919-846a-04fac1f0be75 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using MonoTorrent.BEncoding;
namespace MonoTorrent.Client.Tracker
{
public abstract class TrackerResponseEventArgs : EventArgs
{
private bool successful;
private Tracker tracker;
/// <summary>
/// True if the request completed successfully
/// </summary>
public bool Successful
{
get { return successful; }
set { successful = value; }
}
/// <summary>
/// The tracker which the request was sent to
/// </summary>
public Tracker Tracker
{
get { return tracker; }
protected set { tracker = value; }
}
protected TrackerResponseEventArgs(Tracker tracker, bool successful)
{
if (tracker == null)
throw new ArgumentNullException("tracker");
this.tracker = tracker;
}
}
}
```
Fix bug spotted with Gendarme. Assign the value of 'successful'. | ```c#
using System;
using System.Collections.Generic;
using MonoTorrent.BEncoding;
namespace MonoTorrent.Client.Tracker
{
public abstract class TrackerResponseEventArgs : EventArgs
{
private bool successful;
private Tracker tracker;
/// <summary>
/// True if the request completed successfully
/// </summary>
public bool Successful
{
get { return successful; }
set { successful = value; }
}
/// <summary>
/// The tracker which the request was sent to
/// </summary>
public Tracker Tracker
{
get { return tracker; }
protected set { tracker = value; }
}
protected TrackerResponseEventArgs(Tracker tracker, bool successful)
{
if (tracker == null)
throw new ArgumentNullException("tracker");
this.successful = successful;
this.tracker = tracker;
}
}
}
``` |
daa79ef2-957c-4ea8-9ddb-70fb99016cfc | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ILGeneratorExtensions
{
public static class MethodFlow
{
public static void JumpTo(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Jmp, method);
public static void Call(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Call, method);
public static void CallVirtual(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Callvirt, method);
public static void TailCall(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Call, method);
}
public static void TailCallVirtual(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Callvirt, method);
}
public static void ConstrainedCallVirtual<T>(this ILGenerator generator, MethodInfo method)
{
generator.ConstrainedCallVirtual(typeof (T), method);
}
public static void ConstrainedCallVirtual(this ILGenerator generator, Type constrainedType, MethodInfo method)
{
generator.Emit(OpCodes.Constrained, constrainedType);
generator.Emit(OpCodes.Callvirt, method);
}
public static void Return(this ILGenerator generator) => generator.Emit(OpCodes.Ret);
}
}
```
Add constrained and tail call methods, and remove virtual from method names, as constrained implies virtual | ```c#
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ILGeneratorExtensions
{
public static class MethodFlow
{
public static void JumpTo(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Jmp, method);
public static void Call(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Call, method);
public static void CallVirtual(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Callvirt, method);
public static void TailCall(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Call, method);
}
public static void TailCallVirtual(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Callvirt, method);
}
public static void ConstrainedCall<T>(this ILGenerator generator, MethodInfo method)
{
generator.ConstrainedCall(typeof (T), method);
}
public static void ConstrainedCall(this ILGenerator generator, Type constrainedType, MethodInfo method)
{
generator.Emit(OpCodes.Constrained, constrainedType);
generator.Emit(OpCodes.Callvirt, method);
}
public static void ConstrainedTailCall<T>(this ILGenerator generator, MethodInfo method)
{
generator.ConstrainedTailCall(typeof(T), method);
}
public static void ConstrainedTailCall(this ILGenerator generator, Type constrainedType, MethodInfo method)
{
generator.Emit(OpCodes.Constrained, constrainedType);
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Callvirt, method);
}
public static void Return(this ILGenerator generator) => generator.Emit(OpCodes.Ret);
}
}
``` |
5b22f309-c456-4f97-81a3-c769f224f761 | {
"language": "C#"
} | ```c#
using UnityEngine;
using Animator = ATP.AnimationPathTools.AnimatorComponent.Animator;
namespace ATP.AnimationPathTools.AudioSourceControllerComponent {
/// <summary>
/// Allows controlling <c>AudioSource</c> component from inspector
/// and with keyboard shortcuts.
/// </summary>
// todo add menu option to create component
public sealed class AudioSourceController : MonoBehaviour {
[SerializeField]
private AudioSource audioSource;
[SerializeField]
private Animator animator;
/// <summary>
/// Reference to audio source component.
/// </summary>
public AudioSource AudioSource {
get { return audioSource; }
set { audioSource = value; }
}
/// <summary>
/// Reference to animator component.
/// </summary>
public Animator Animator {
get { return animator; }
set { animator = value; }
}
private void Reset() {
AudioSource = GetComponent<AudioSource>();
Animator = GetComponent<Animator>();
}
private void Update() {
HandleSpaceShortcut();
}
/// <summary>
/// Handle space shortcut.
/// </summary>
private void HandleSpaceShortcut() {
// If space pressed..
if (Input.GetKeyDown(KeyCode.Space)) {
// Pause
if (AudioSource.isPlaying) {
AudioSource.Pause();
}
// Play
else {
AudioSource.Play();
}
}
}
}
}
```
Disable space shortcut in audio controller | ```c#
using UnityEngine;
using Animator = ATP.AnimationPathTools.AnimatorComponent.Animator;
namespace ATP.AnimationPathTools.AudioSourceControllerComponent {
/// <summary>
/// Allows controlling <c>AudioSource</c> component from inspector
/// and with keyboard shortcuts.
/// </summary>
// todo add menu option to create component
public sealed class AudioSourceController : MonoBehaviour {
[SerializeField]
private AudioSource audioSource;
[SerializeField]
private Animator animator;
/// <summary>
/// Reference to audio source component.
/// </summary>
public AudioSource AudioSource {
get { return audioSource; }
set { audioSource = value; }
}
/// <summary>
/// Reference to animator component.
/// </summary>
public Animator Animator {
get { return animator; }
set { animator = value; }
}
private void Reset() {
AudioSource = GetComponent<AudioSource>();
Animator = GetComponent<Animator>();
}
private void Update() {
HandleSpaceShortcut();
}
/// <summary>
/// Handle space shortcut.
/// </summary>
private void HandleSpaceShortcut() {
// Disable shortcut while animator awaits animation start.
if (Animator.IsInvoking("StartAnimation")) return;
// If space pressed..
if (Input.GetKeyDown(KeyCode.Space)) {
// Pause
if (AudioSource.isPlaying) {
AudioSource.Pause();
}
// Play
else {
AudioSource.Play();
}
}
}
}
}
``` |
28442832-9d0d-4d4a-8773-f0abec09cff4 | {
"language": "C#"
} | ```c#
using System;
using Cake.Core;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Client.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
namespace Cake.DocumentDb.Factories
{
public class ClientFactory
{
private readonly ConnectionSettings settings;
private readonly ICakeContext context;
public ClientFactory(ConnectionSettings settings, ICakeContext context)
{
this.settings = settings;
this.context = context;
}
public IReliableReadWriteDocumentClient GetClient()
{
return new DocumentClient(
new Uri(settings.Endpoint),
settings.Key,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Gateway,
ConnectionProtocol = Protocol.Https
}).AsReliable(new FixedInterval(
15,
TimeSpan.FromSeconds(200)));
}
}
}
```
Add method to create client optimised for write | ```c#
using System;
using Cake.Core;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Client.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
namespace Cake.DocumentDb.Factories
{
public class ClientFactory
{
private readonly ConnectionSettings settings;
private readonly ICakeContext context;
public ClientFactory(ConnectionSettings settings, ICakeContext context)
{
this.settings = settings;
this.context = context;
}
public IReliableReadWriteDocumentClient GetClient()
{
return new DocumentClient(
new Uri(settings.Endpoint),
settings.Key,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Gateway,
ConnectionProtocol = Protocol.Https
})
.AsReliable(
new FixedInterval(
15,
TimeSpan.FromSeconds(200)));
}
// https://github.com/Azure/azure-cosmos-dotnet-v2/blob/master/samples/documentdb-benchmark/Program.cs
public IDocumentClient GetClientOptimistedForWrite()
{
return new DocumentClient(
new Uri(settings.Endpoint),
settings.Key,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp,
RequestTimeout = new TimeSpan(1, 0, 0),
MaxConnectionLimit = 1000,
RetryOptions = new RetryOptions
{
MaxRetryAttemptsOnThrottledRequests = 10,
MaxRetryWaitTimeInSeconds = 60
}
});
}
}
}
``` |
5816f76a-356e-4a69-94c5-730d898d00a6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace anime_downloader {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
String animeFolder;
public MainWindow() {
InitializeComponent();
animeFolder = @"D:\Output\anime downloader";
}
private void button_folder_Click(object sender, RoutedEventArgs e) {
Process.Start(animeFolder);
}
private void button_playlist_Click(object sender, RoutedEventArgs e) {
string[] folders = Directory.GetDirectories(animeFolder)
.Where(s => !s.EndsWith("torrents") && !s.EndsWith("Grace") && !s.EndsWith("Watched"))
.ToArray();
using (StreamWriter file = new StreamWriter(path: animeFolder + @"\playlist.m3u",
append: false)) {
foreach(String folder in folders)
file.WriteLine(String.Join("\n", Directory.GetFiles(folder)));
}
// MessageBox.Show(String.Join(", ", folders));
// System.Windows.MessageBox.Show(String.Join(", ", ));
// Directory.GetDirectories(animeFolder);
}
}
}
```
Make LINQ in playlist function fancier (because why not) | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace anime_downloader {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
String animeFolder;
public MainWindow() {
InitializeComponent();
animeFolder = @"D:\Output\anime downloader";
}
private void button_folder_Click(object sender, RoutedEventArgs e) {
Process.Start(animeFolder);
}
private void button_playlist_Click(object sender, RoutedEventArgs e) {
string[] videos = Directory.GetDirectories(animeFolder)
.Where(s => !s.EndsWith("torrents") && !s.EndsWith("Grace") && !s.EndsWith("Watched"))
.SelectMany(f => Directory.GetFiles(f))
.ToArray();
using (StreamWriter file = new StreamWriter(path: animeFolder + @"\playlist.m3u",
append: false)) {
foreach(String video in videos)
file.WriteLine(video);
}
}
}
}
``` |
119305cb-4546-4e55-8976-6f7af99bcf29 | {
"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("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.*")]
```
Set AssemblyVersion and AssemblyFileVersion to 1.0.0.0 | ```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("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
``` |
b7878206-102a-432b-9b58-3e977cabd881 | {
"language": "C#"
} | ```c#
using Microsoft.TemplateEngine.Abstractions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
public class DerivedSymbol : BaseValueSymbol
{
public const string TypeName = "derived";
public string ValueTransform { get; set; }
public string ValueSource { get; set; }
public static ISymbolModel FromJObject(JObject jObject, IParameterSymbolLocalizationModel localization, string defaultOverride)
{
DerivedSymbol symbol = FromJObject<DerivedSymbol>(jObject, localization, defaultOverride);
symbol.ValueTransform = jObject.ToString(nameof(ValueTransform));
symbol.ValueSource = jObject.ToString(nameof(ValueSource));
return symbol;
}
}
}
```
Change derived symbols type name to an internal const | ```c#
using Microsoft.TemplateEngine.Abstractions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
public class DerivedSymbol : BaseValueSymbol
{
internal const string TypeName = "derived";
public string ValueTransform { get; set; }
public string ValueSource { get; set; }
public static ISymbolModel FromJObject(JObject jObject, IParameterSymbolLocalizationModel localization, string defaultOverride)
{
DerivedSymbol symbol = FromJObject<DerivedSymbol>(jObject, localization, defaultOverride);
symbol.ValueTransform = jObject.ToString(nameof(ValueTransform));
symbol.ValueSource = jObject.ToString(nameof(ValueSource));
return symbol;
}
}
}
``` |
fadafa0d-69c1-4609-a429-66327c0ed33c | {
"language": "C#"
} | ```c#
Task("DevBuild")
.IsDependentOn("Build")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
Task("PrBuild")
.IsDependentOn("Build")
.IsDependentOn("Test-NUnit");
Task("KpiBuild")
.IsDependentOn("Build")
.IsDependentOn("Test-NUnit")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
```
Add uploading of coverage reports to Coveralls | ```c#
Task("DevBuild")
.IsDependentOn("Build")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
Task("KpiBuild")
.IsDependentOn("Build")
.IsDependentOn("Test-NUnit")
.IsDependentOn("Upload-Coverage-Report")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
``` |
6b495240-3dfc-4cfb-9103-8058c8aba868 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EntryPoint {
/// <summary>
/// Used to mark a method as a Command, in a CliCommands class
/// </summary>
[AttributeUsage(
AttributeTargets.Method,
AllowMultiple = false,
Inherited = true)]
public class CommandAttribute : Attribute {
/// <summary>
/// Marks a Method as a Command
/// </summary>
/// <param name="Name">The case in-sensitive name for the command, which is invoked to activate it</param>
public CommandAttribute(string Name) {
if (Name == null || Name.Length == 0) {
throw new ArgumentException(
"You must give a Command a name");
}
this.Name = Name;
}
/// <summary>
/// The case in-sensitive name for the command
/// </summary>
internal string Name { get; set; }
}
}
```
Clarify error throw when Command has no name string provided | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EntryPoint {
/// <summary>
/// Used to mark a method as a Command, in a CliCommands class
/// </summary>
[AttributeUsage(
AttributeTargets.Method,
AllowMultiple = false,
Inherited = true)]
public class CommandAttribute : Attribute {
/// <summary>
/// Marks a Method as a Command
/// </summary>
/// <param name="Name">The case in-sensitive name for the command, which is invoked to activate it</param>
public CommandAttribute(string Name) {
if (Name == null || Name.Length == 0) {
throw new ArgumentException(
$"A {nameof(CommandAttribute)} was not given a name");
}
this.Name = Name;
}
/// <summary>
/// The case in-sensitive name for the command
/// </summary>
internal string Name { get; set; }
}
}
``` |
d57deb5c-b5f5-4769-8cd7-2e5e16cde2ca | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Reflection;
namespace AIMP.SDK
{
internal static class CustomAssemblyResolver
{
private static string curPath;
private static bool isInited;
/// <summary>
/// Initializes the specified path.
/// </summary>
/// <param name="path">The path.</param>
public static void Initialize(string path)
{
curPath = path +"\\";
if (!isInited)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
isInited = true;
}
}
/// <summary>
/// Deinitializes this instance.
/// </summary>
public static void Deinitialize()
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
isInited = false;
}
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
string projectDir = Path.GetDirectoryName(curPath);
string shortAssemblyName = args.Name.Substring(0, args.Name.IndexOf(','));
string fileName = Path.Combine(projectDir, shortAssemblyName + ".dll");
if (File.Exists(fileName))
{
Assembly result = Assembly.LoadFrom(fileName);
return result;
}
return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
}
}
}
```
Fix assembly load for plugins | ```c#
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace AIMP.SDK
{
internal static class CustomAssemblyResolver
{
private static string curPath;
private static bool isInited;
/// <summary>
/// Initializes the specified path.
/// </summary>
/// <param name="path">The path.</param>
public static void Initialize(string path)
{
curPath = path +"\\";
if (!isInited)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
isInited = true;
}
}
/// <summary>
/// Deinitializes this instance.
/// </summary>
public static void Deinitialize()
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
isInited = false;
}
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
string projectDir = Path.GetDirectoryName(curPath);
string shortAssemblyName = args.Name.Substring(0, args.Name.IndexOf(','));
string fileName = Path.Combine(projectDir, shortAssemblyName + ".dll");
if (File.Exists(fileName))
{
Assembly result = Assembly.LoadFrom(fileName);
return result;
}
var assemblyPath = Directory.EnumerateFiles(projectDir, shortAssemblyName + ".dll", SearchOption.AllDirectories).FirstOrDefault();
if (assemblyPath != null)
{
return Assembly.LoadFrom(assemblyPath);
}
return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
}
}
}
``` |
ce3d4013-38fe-4788-85d6-f5bdfa8631ff | {
"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 speech_quickstart]
using Google.Cloud.Speech.V1Beta1;
// [END speech_quickstart]
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// [START speech_quickstart]
var speech = SpeechClient.Create();
var response = speech.SyncRecognize(new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRate = 16000,
}, RecognitionAudio.FromFile("audio.raw"));
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Console.WriteLine(alternative.Transcript);
}
}
// [END speech_quickstart]
}
}
}
```
Move the speech_quickstart doc tag so that users can copy and paste all the code. | ```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 speech_quickstart]
using Google.Cloud.Speech.V1Beta1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
var speech = SpeechClient.Create();
var response = speech.SyncRecognize(new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRate = 16000,
}, RecognitionAudio.FromFile("audio.raw"));
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Console.WriteLine(alternative.Transcript);
}
}
}
}
}
// [END speech_quickstart]
``` |
a4443465-c2f9-4100-aa62-9c5b9d189d64 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Playlists.Response
{
[Serializable]
public class PlaylistLocation : UserBasedUpdatableItem
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("links")]
[XmlArrayItem("link")]
public List<Link> Links { get; set; }
[XmlElement("trackCount")]
public int TrackCount { get; set; }
[XmlElement("visibility")]
public PlaylistVisibilityType Visibility { get; set; }
[XmlElement("status")]
public PlaylistStatusType Status { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", Id, Name);
}
}
}```
Add tags to playlist location | ```c#
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Playlists.Response
{
[Serializable]
public class PlaylistLocation : UserBasedUpdatableItem
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("links")]
[XmlArrayItem("link")]
public List<Link> Links { get; set; }
[XmlElement("trackCount")]
public int TrackCount { get; set; }
[XmlElement("visibility")]
public PlaylistVisibilityType Visibility { get; set; }
[XmlElement("status")]
public PlaylistStatusType Status { get; set; }
[XmlElement("tags")]
public List<Tag> Tags { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", Id, Name);
}
}
}``` |
797458e1-a507-4dd7-b6cd-0d047121d4bf | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BundleConfig.cs" company="KriaSoft LLC">
// Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace App.Web
{
using System.Web.Optimization;
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/js/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/js/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/js/bootstrap").Include("~/Scripts/bootstrap/*"));
bundles.Add(new ScriptBundle("~/js/site").Include(
"~/Scripts/Site.js"));
bundles.Add(new StyleBundle("~/css/bootstrap").Include("~/Styles/bootstrap.css"));
bundles.Add(new StyleBundle("~/css/site").Include("~/Styles/Site.css"));
}
}
}```
Fix wildcard path in bootstrap js bundle | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BundleConfig.cs" company="KriaSoft LLC">
// Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace App.Web
{
using System.Web.Optimization;
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/js/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/js/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/js/bootstrap").Include("~/Scripts/bootstrap/*.js"));
bundles.Add(new ScriptBundle("~/js/site").Include(
"~/Scripts/Site.js"));
bundles.Add(new StyleBundle("~/css/bootstrap").Include("~/Styles/bootstrap.css"));
bundles.Add(new StyleBundle("~/css/site").Include("~/Styles/Site.css"));
}
}
}``` |
e4625109-b5cc-496a-8ca5-6cb09ceaafc0 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Elasticsearch.Net
{
internal class DynamicBodyFormatter : IJsonFormatter<DynamicBody>
{
private static readonly DictionaryFormatter<string, object> DictionaryFormatter =
new DictionaryFormatter<string, object>();
public void Serialize(ref JsonWriter writer, DynamicBody value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteBeginObject();
var formatter = formatterResolver.GetFormatter<object>();
foreach (var kv in (IDictionary<string, object>)value)
{
writer.WritePropertyName(kv.Key);
formatter.Serialize(ref writer, kv.Value, formatterResolver);
}
writer.WriteEndObject();
}
public DynamicBody Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var dictionary = DictionaryFormatter.Deserialize(ref reader, formatterResolver);
return DynamicBody.Create(dictionary);
}
}
}
```
Write value separators when serializing dynamic body | ```c#
using System.Collections.Generic;
namespace Elasticsearch.Net
{
internal class DynamicBodyFormatter : IJsonFormatter<DynamicBody>
{
private static readonly DictionaryFormatter<string, object> DictionaryFormatter =
new DictionaryFormatter<string, object>();
public void Serialize(ref JsonWriter writer, DynamicBody value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteBeginObject();
var formatter = formatterResolver.GetFormatter<object>();
var count = 0;
foreach (var kv in (IDictionary<string, object>)value)
{
if (count > 0)
writer.WriteValueSeparator();
writer.WritePropertyName(kv.Key);
formatter.Serialize(ref writer, kv.Value, formatterResolver);
count++;
}
writer.WriteEndObject();
}
public DynamicBody Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var dictionary = DictionaryFormatter.Deserialize(ref reader, formatterResolver);
return DynamicBody.Create(dictionary);
}
}
}
``` |
05a53c31-15e8-451f-9406-049c6d529d65 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Harmony
{
internal static class PatchTools
{
static readonly Dictionary<object, object> objectReferences = new Dictionary<object, object>();
internal static void RememberObject(object key, object value)
{
objectReferences[key] = value;
}
internal static MethodInfo GetPatchMethod<T>(Type patchType, string name)
{
var attributeType = typeof(T).FullName;
var method = patchType.GetMethods(AccessTools.all)
.FirstOrDefault(m => m.GetCustomAttributes(true).Any(a => a.GetType().FullName == attributeType));
if (method == null)
method = AccessTools.Method(patchType, name);
return method;
}
[UpgradeToLatestVersion(1)]
internal static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler)
{
prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
}
}
}```
Reduce unnecessary logging of missing optional methods | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Harmony
{
internal static class PatchTools
{
static readonly Dictionary<object, object> objectReferences = new Dictionary<object, object>();
internal static void RememberObject(object key, object value)
{
objectReferences[key] = value;
}
internal static MethodInfo GetPatchMethod<T>(Type patchType, string name)
{
var attributeType = typeof(T).FullName;
var method = patchType.GetMethods(AccessTools.all)
.FirstOrDefault(m => m.GetCustomAttributes(true).Any(a => a.GetType().FullName == attributeType));
if (method == null)
{
// not-found is common and normal case, don't use AccessTools which will generate not-found warnings
method = patchType.GetMethod(name, AccessTools.all);
}
return method;
}
[UpgradeToLatestVersion(1)]
internal static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler)
{
prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
}
}
}``` |
b618a22b-7175-42fd-994b-fe64f2972182 | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
namespace Stranne.VasttrafikNET.Models
{
internal class Token
{
private DateTimeOffset _createDate = DateTimeOffset.Now;
[JsonProperty("Expires_In")]
public int ExpiresIn { get; set; }
[JsonProperty("Access_Token")]
public string AccessToken { get; set; }
public bool IsValid() => _createDate.AddSeconds(ExpiresIn) < DateTimeOffset.Now;
}
}
```
Fix bug with logic for if the token is valid | ```c#
using System;
using Newtonsoft.Json;
namespace Stranne.VasttrafikNET.Models
{
internal class Token
{
private DateTimeOffset _createDate = DateTimeOffset.Now;
[JsonProperty("Expires_In")]
public int ExpiresIn { get; set; }
[JsonProperty("Access_Token")]
public string AccessToken { get; set; }
public bool IsValid() => _createDate.AddSeconds(ExpiresIn) > DateTimeOffset.Now;
}
}
``` |
543b90dd-3105-4ada-921b-f9dde5d3cb1f | {
"language": "C#"
} | ```c#
namespace awesome_bot.Giphy
{
public static partial class GiphyEndPoints
{
public class RandomEndPoint
{
private const string RandomPath = "/v1/gifs/random";
public string Build(string searchText, Rating rating = null)
=> string.Join(string.Empty, Root, RandomPath, "?",
$"api_key={ApiKey}&tag={searchText}&rating={rating ?? Rating.G}");
}
}
}```
Raise rating of gif search | ```c#
namespace awesome_bot.Giphy
{
public static partial class GiphyEndPoints
{
public class RandomEndPoint
{
private const string RandomPath = "/v1/gifs/random";
public string Build(string searchText, Rating rating = null)
=> string.Join(string.Empty, Root, RandomPath, "?",
$"api_key={ApiKey}&tag={searchText}&rating={rating ?? Rating.PG13}");
}
}
}``` |
00b99b51-7640-4600-abac-c7163d38928d | {
"language": "C#"
} | ```c#
namespace Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
{
/// <summary>
/// This represents the parameters entity to render api.js.
/// </summary>
/// <remarks>More details: https://developers.google.com/recaptcha/docs/display#js_param</remarks>
public partial class ResourceParameters
{
/// <summary>
/// Gets or sets the callback method name on load.
/// </summary>
public string OnLoad { get; set; }
/// <summary>
/// Gets or sets the render option.
/// </summary>
public WidgetRenderType Render { get; set; }
/// <summary>
/// Gets or sets the language code to display reCaptcha control.
/// </summary>
public WidgetLanguageCode LanguageCode { get; set; }
}
}```
Add JsonProperty attribute on each property | ```c#
using Newtonsoft.Json;
namespace Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
{
/// <summary>
/// This represents the parameters entity to render api.js.
/// </summary>
/// <remarks>More details: https://developers.google.com/recaptcha/docs/display#js_param</remarks>
public partial class ResourceParameters
{
/// <summary>
/// Gets or sets the callback method name on load.
/// </summary>
[JsonProperty(PropertyName = "onload")]
public string OnLoad { get; set; }
/// <summary>
/// Gets or sets the render option.
/// </summary>
[JsonProperty(PropertyName = "render")]
public WidgetRenderType Render { get; set; }
/// <summary>
/// Gets or sets the language code to display reCaptcha control.
/// </summary>
[JsonProperty(PropertyName = "hl")]
public WidgetLanguageCode LanguageCode { get; set; }
}
}``` |
c8f1991f-e118-477e-b4da-b393de5fc75b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
namespace DesktopWidgets.Helpers
{
public static class ImageHelper
{
public static readonly List<string> SupportedExtensions = new List<string>
{
".bmp",
".gif",
".ico",
".jpg",
".jpeg",
".png",
".tiff"
};
public static bool IsSupported(string extension)
{
return SupportedExtensions.Contains(extension.ToLower());
}
public static BitmapImage LoadBitmapImageFromPath(string path)
{
var bmi = new BitmapImage();
bmi.BeginInit();
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
bmi.EndInit();
bmi.Freeze();
return bmi;
}
}
}```
Add more supported image extensions | ```c#
using System;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
namespace DesktopWidgets.Helpers
{
public static class ImageHelper
{
// https://msdn.microsoft.com/en-us/library/ee719654(v=VS.85).aspx#wpfc_codecs.
public static readonly List<string> SupportedExtensions = new List<string>
{
".bmp",
".gif",
".ico",
".jpg",
".jpeg",
".png",
".tiff",
".wmp",
".dds"
};
public static bool IsSupported(string extension)
{
return SupportedExtensions.Contains(extension.ToLower());
}
public static BitmapImage LoadBitmapImageFromPath(string path)
{
var bmi = new BitmapImage();
bmi.BeginInit();
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
bmi.EndInit();
bmi.Freeze();
return bmi;
}
}
}``` |
e1f2ced9-459c-472f-b89f-826c57cf5781 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class PhysicsHelper2D
{
/// <summary>
/// Ignores collision for every single GameObject with a particular tag
/// </summary>
/// <param name="object1"></param>
/// <param name="tag"></param>
/// <param name="ignore"></param>
public static void ignoreCollisionWithTag(GameObject object1, string tag, bool ignore)
{
Collider2D[] colliders = object1.GetComponents<Collider2D>();
GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject taggedObject in taggedObjects)
{
for (int i = 0; i < colliders.Length; i++)
{
Physics2D.IgnoreCollision(colliders[i], taggedObject.GetComponent<Collider2D>(), ignore);
}
}
}
/// <summary>
/// performs Physics2D.raycast and also Debug.DrawLine with the same vector
/// </summary>
public static bool visibleRaycast(Vector2 origin, Vector2 direction, float distance = float.PositiveInfinity, Color? color = null)
{
Debug.DrawLine(origin, origin + (direction.resize(distance)), color ?? Color.white);
return Physics2D.Raycast(origin, direction, distance);
}
}
```
Include all parameters in visibleRaycast | ```c#
using UnityEngine;
using System.Collections;
public class PhysicsHelper2D
{
/// <summary>
/// Ignores collision for every single GameObject with a particular tag
/// </summary>
/// <param name="object1"></param>
/// <param name="tag"></param>
/// <param name="ignore"></param>
public static void ignoreCollisionWithTag(GameObject object1, string tag, bool ignore)
{
Collider2D[] colliders = object1.GetComponents<Collider2D>();
GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject taggedObject in taggedObjects)
{
for (int i = 0; i < colliders.Length; i++)
{
Physics2D.IgnoreCollision(colliders[i], taggedObject.GetComponent<Collider2D>(), ignore);
}
}
}
/// <summary>
/// performs Physics2D.raycast and also Debug.DrawLine with the same vector
/// </summary>
public static RaycastHit2D visibleRaycast(Vector2 origin, Vector2 direction,
float distance = float.PositiveInfinity, int layerMask = Physics2D.DefaultRaycastLayers,
float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity,
Color? color = null)
{
Debug.DrawLine(origin, origin + (direction.resize(distance)), color ?? Color.white);
return Physics2D.Raycast(origin, direction, distance, layerMask, minDepth, maxDepth);
}
}
``` |
9191cf53-7d9b-4c6d-8ca5-e3b46d872b92 | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HarnessTests.cs" company="LunchBox corp">
// Copyright 2014 The Lunch-Box mob:
// Ozgur DEVELIOGLU (@Zgurrr)
// Cyrille DUPUYDAUBY (@Cyrdup)
// Tomasz JASKULA (@tjaskula)
// Mendel MONTEIRO-BECKERMAN (@MendelMonteiro)
// Thomas PIERRAIN (@tpierrain)
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SimpleOrderRouting.Tests
{
using NFluent;
using SimpleOrderRouting.Journey1;
using Xunit;
public class HarnessTests
{
[Fact]
public void ShouldReturnALatency()
{
var runner = new SorTestHarness();
runner.Run();
Check.That<double>(runner.AverageLatency).IsPositive();
}
}
}```
Comment test harness unit test with lame check | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HarnessTests.cs" company="LunchBox corp">
// Copyright 2014 The Lunch-Box mob:
// Ozgur DEVELIOGLU (@Zgurrr)
// Cyrille DUPUYDAUBY (@Cyrdup)
// Tomasz JASKULA (@tjaskula)
// Mendel MONTEIRO-BECKERMAN (@MendelMonteiro)
// Thomas PIERRAIN (@tpierrain)
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SimpleOrderRouting.Tests
{
using NFluent;
using SimpleOrderRouting.Journey1;
using Xunit;
public class HarnessTests
{
//[Fact]
public void ShouldReturnALatency()
{
var runner = new SorTestHarness();
runner.Run();
Check.That<double>(runner.AverageLatency).IsPositive();
}
}
}``` |
d213100a-d043-4185-bf4c-ad3aadc4dec8 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public class DeploymentConfiguration
{
internal const string DeployConfigFile = ".deployment";
private readonly IniFile _iniFile;
private readonly string _path;
public DeploymentConfiguration(string path)
{
_path = path;
_iniFile = new IniFile(Path.Combine(path, DeployConfigFile));
}
public string ProjectPath
{
get
{
string projectPath = _iniFile.GetSectionValue("config", "project");
if (String.IsNullOrEmpty(projectPath))
{
return null;
}
return Path.Combine(_path, projectPath.TrimStart('/', '\\'));
}
}
}
}
```
Resolve full for specified .deployment project file. | ```c#
using System;
using System.IO;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public class DeploymentConfiguration
{
internal const string DeployConfigFile = ".deployment";
private readonly IniFile _iniFile;
private readonly string _path;
public DeploymentConfiguration(string path)
{
_path = path;
_iniFile = new IniFile(Path.Combine(path, DeployConfigFile));
}
public string ProjectPath
{
get
{
string projectPath = _iniFile.GetSectionValue("config", "project");
if (String.IsNullOrEmpty(projectPath))
{
return null;
}
return Path.GetFullPath(Path.Combine(_path, projectPath.TrimStart('/', '\\')));
}
}
}
}
``` |
04948e71-fe5a-42e1-a171-499b2f77f4be | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Owin;
namespace JabbR.Middleware
{
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using AppFunc = Func<IDictionary<string, object>, Task>;
public class FixCookieHandler
{
private readonly AppFunc _next;
private readonly TicketDataHandler _ticketHandler;
public FixCookieHandler(AppFunc next, TicketDataHandler ticketHandler)
{
_ticketHandler = ticketHandler;
_next = next;
}
public Task Invoke(IDictionary<string, object> env)
{
var request = new OwinRequest(env);
var cookies = request.GetCookies();
string cookieValue;
if (cookies != null && cookies.TryGetValue("jabbr.id", out cookieValue))
{
AuthenticationTicket ticket = _ticketHandler.Unprotect(cookieValue);
}
return _next(env);
}
}
}
```
Work around bug in FormsAuthMiddleware | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
namespace JabbR.Middleware
{
using AppFunc = Func<IDictionary<string, object>, Task>;
public class FixCookieHandler
{
private readonly AppFunc _next;
private readonly TicketDataHandler _ticketHandler;
public FixCookieHandler(AppFunc next, TicketDataHandler ticketHandler)
{
_ticketHandler = ticketHandler;
_next = next;
}
public Task Invoke(IDictionary<string, object> env)
{
var request = new OwinRequest(env);
var cookies = request.GetCookies();
string cookieValue;
if (cookies != null && cookies.TryGetValue("jabbr.id", out cookieValue))
{
AuthenticationTicket ticket = _ticketHandler.Unprotect(cookieValue);
if (ticket.Extra == null)
{
// The forms auth module has a bug where it null refs on a null Extra
var headers = request.Get<IDictionary<string, string[]>>(Owin.Types.OwinConstants.RequestHeaders);
var cookieBuilder = new StringBuilder();
foreach (var cookie in cookies)
{
// Skip the jabbr.id cookie
if (cookie.Key == "jabbr.id")
{
continue;
}
if (cookieBuilder.Length > 0)
{
cookieBuilder.Append(";");
}
cookieBuilder.Append(cookie.Key)
.Append("=")
.Append(Uri.EscapeDataString(cookie.Value));
}
headers["Cookie"] = new[] { cookieBuilder.ToString() };
}
}
return _next(env);
}
}
}
``` |
47a4c0bf-956d-460b-95b2-8749b16ba77c | {
"language": "C#"
} | ```c#
using BlackFox.Roslyn.TestDiagnostics.NoNewGuid;
using BlackFox.Roslyn.TestDiagnostics.NoStringEmpty;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NFluent;
using TestDiagnosticsUnitTests.Helpers.DiagnosticTestHelpers;
namespace TestDiagnosticsUnitTests
{
[TestClass]
public class NoNewGuidAnalyzerTests
{
[TestMethod]
public void No_diagnostic_on_guid_empty()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = Guid.Empty;");
Check.That(diagnostics).IsEmpty();
}
[TestMethod]
public void Diagnostic_new_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_namespace_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new System.Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_fully_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new global::System.Guid();");
Check.That(diagnostics).HasSize(1);
}
}
}
```
Remove an useless namespace usage | ```c#
using BlackFox.Roslyn.TestDiagnostics.NoNewGuid;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NFluent;
using TestDiagnosticsUnitTests.Helpers.DiagnosticTestHelpers;
namespace TestDiagnosticsUnitTests
{
[TestClass]
public class NoNewGuidAnalyzerTests
{
[TestMethod]
public void No_diagnostic_on_guid_empty()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = Guid.Empty;");
Check.That(diagnostics).IsEmpty();
}
[TestMethod]
public void Diagnostic_new_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_namespace_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new System.Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_fully_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new global::System.Guid();");
Check.That(diagnostics).HasSize(1);
}
}
}
``` |
b7fb0211-4749-4401-9d43-7264413e9a68 | {
"language": "C#"
} | ```c#
using System.Web;
namespace FeatureSwitcher.DebugConsole.Behaviours
{
public class DebugConsoleBehaviour
{
private readonly bool _isForced = false;
private DebugConsoleBehaviour(bool isForced)
{
this._isForced = isForced;
}
internal static FeatureSwitcher.Feature.Behavior AlwaysEnabled => new DebugConsoleBehaviour(true).Behaviour;
public static FeatureSwitcher.Feature.Behavior IsEnabled => new DebugConsoleBehaviour(false).Behaviour;
private bool? Behaviour(Feature.Name name)
{
if (HttpContext.Current == null)
return null;
if (name == null || string.IsNullOrWhiteSpace(name.Value))
return null;
if (HttpContext.Current.IsDebuggingEnabled || this._isForced)
{
var cookie = HttpContext.Current.Request.Cookies[name.Value];
if (cookie == null)
return null;
return cookie.Value == "true";
}
return null;
}
}
}
```
Add null check for request. | ```c#
using System.Web;
namespace FeatureSwitcher.DebugConsole.Behaviours
{
public class DebugConsoleBehaviour
{
private readonly bool _isForced = false;
private DebugConsoleBehaviour(bool isForced)
{
this._isForced = isForced;
}
internal static FeatureSwitcher.Feature.Behavior AlwaysEnabled => new DebugConsoleBehaviour(true).Behaviour;
public static FeatureSwitcher.Feature.Behavior IsEnabled => new DebugConsoleBehaviour(false).Behaviour;
private bool? Behaviour(Feature.Name name)
{
if (HttpContext.Current == null)
return null;
if (name == null || string.IsNullOrWhiteSpace(name.Value))
return null;
if (HttpContext.Current.IsDebuggingEnabled || this._isForced)
{
if (HttpContext.Current.Request == null)
return null;
var cookie = HttpContext.Current.Request.Cookies[name.Value];
if (cookie == null)
return null;
return cookie.Value == "true";
}
return null;
}
}
}
``` |
2b34eb0b-81e6-4680-ad77-f42d13d7b430 | {
"language": "C#"
} | ```c#
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
namespace NodaTime.Test
{
public class SystemClockTest
{
[Test]
public void InstanceNow()
{
long frameworkNowTicks = NodaConstants.BclEpoch.PlusTicks(DateTime.UtcNow.Ticks).ToUnixTimeTicks();
long nodaTicks = SystemClock.Instance.GetCurrentInstant().ToUnixTimeTicks();
Assert.Less(Math.Abs(nodaTicks - frameworkNowTicks), Duration.FromSeconds(1).BclCompatibleTicks);
}
[Test]
public void Sanity()
{
// Previously all the conversions missed the SystemConversions.DateTimeEpochTicks,
// so they were self-consistent but not consistent with sanity.
Instant minimumExpected = Instant.FromUtc(2011, 8, 1, 0, 0);
Instant maximumExpected = Instant.FromUtc(2020, 1, 1, 0, 0);
Instant now = SystemClock.Instance.GetCurrentInstant();
Assert.Less(minimumExpected.ToUnixTimeTicks(), now.ToUnixTimeTicks());
Assert.Less(now.ToUnixTimeTicks(), maximumExpected.ToUnixTimeTicks());
}
}
}
```
Update SystemClock test to account for time passing. | ```c#
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
namespace NodaTime.Test
{
public class SystemClockTest
{
[Test]
public void InstanceNow()
{
long frameworkNowTicks = NodaConstants.BclEpoch.PlusTicks(DateTime.UtcNow.Ticks).ToUnixTimeTicks();
long nodaTicks = SystemClock.Instance.GetCurrentInstant().ToUnixTimeTicks();
Assert.Less(Math.Abs(nodaTicks - frameworkNowTicks), Duration.FromSeconds(1).BclCompatibleTicks);
}
[Test]
public void Sanity()
{
// Previously all the conversions missed the SystemConversions.DateTimeEpochTicks,
// so they were self-consistent but not consistent with sanity.
Instant minimumExpected = Instant.FromUtc(2019, 8, 1, 0, 0);
Instant maximumExpected = Instant.FromUtc(2025, 1, 1, 0, 0);
Instant now = SystemClock.Instance.GetCurrentInstant();
Assert.Less(minimumExpected.ToUnixTimeTicks(), now.ToUnixTimeTicks());
Assert.Less(now.ToUnixTimeTicks(), maximumExpected.ToUnixTimeTicks());
}
}
}
``` |
00267792-7ede-452d-8fd9-eef2d3f5f869 | {
"language": "C#"
} | ```c#
using SsrsDeploy;
using SsrsDeploy.ReportingService;
using SsrsDeploy.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SsrDeploy.Factory
{
class ServiceFactory
{
private readonly ReportingService2010 rs;
public ServiceFactory(Options options)
{
this.rs = GetReportingService(options);
}
protected virtual ReportingService2010 GetReportingService(Options options)
{
var rs = new ReportingService2010();
rs.Url = GetUrl(options);
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
return rs;
}
public ReportService GetReportService()
{
return new ReportService(rs);
}
public FolderService GetFolderService()
{
return new FolderService(rs);
}
public DataSourceService GetDataSourceService()
{
return new DataSourceService(rs);
}
public static string GetUrl(Options options)
{
var baseUrl = options.Url;
var builder = new UriBuilder(baseUrl);
if (string.IsNullOrEmpty(builder.Scheme))
builder.Scheme = Uri.UriSchemeHttp;
if (builder.Scheme != Uri.UriSchemeHttp && builder.Scheme != Uri.UriSchemeHttps)
throw new ArgumentException();
if (!builder.Path.EndsWith("/ReportService2010.asmx"))
builder.Path += (builder.Path.EndsWith("/") ? "" : "/") + "ReportService2010.asmx";
if (builder.Path.Equals("/ReportService2010.asmx"))
builder.Path = "/ReportServer" + builder.Path;
if (builder.Uri.IsDefaultPort)
return builder.Uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped);
return builder.ToString();
}
}
}
```
Make usage of UrlBuilder and fix namespace | ```c#
using SsrsDeploy;
using SsrsDeploy.ReportingService;
using SsrsDeploy.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SsrsDeploy.Factory
{
class ServiceFactory
{
private readonly ReportingService2010 rs;
public ServiceFactory(Options options)
{
this.rs = GetReportingService(options);
}
protected virtual ReportingService2010 GetReportingService(Options options)
{
var rs = new ReportingService2010();
var urlBuilder = new UrlBuilder();
urlBuilder.Setup(options);
urlBuilder.Build();
rs.Url = urlBuilder.GetUrl();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
return rs;
}
public ReportService GetReportService()
{
return new ReportService(rs);
}
public FolderService GetFolderService()
{
return new FolderService(rs);
}
public DataSourceService GetDataSourceService()
{
return new DataSourceService(rs);
}
}
}
``` |
c3ef6b3e-43c7-48e3-a2c7-6ee72438ccf7 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace Verdeler
{
internal class ConcurrencyLimiter<TSubject>
{
private readonly Func<TSubject, object> _subjectReductionMap;
private readonly int _concurrencyLimit;
private readonly ConcurrentDictionary<object, SemaphoreSlim> _semaphores
= new ConcurrentDictionary<object, SemaphoreSlim>();
public ConcurrencyLimiter(Func<TSubject, object> subjectReductionMap, int concurrencyLimit)
{
if (concurrencyLimit <= 0)
{
throw new ArgumentException(@"Concurrency limit must be greater than 0.", nameof(concurrencyLimit));
}
_subjectReductionMap = subjectReductionMap;
_concurrencyLimit = concurrencyLimit;
}
public async Task WaitFor(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
await semaphore.WaitAsync().ConfigureAwait(false);
}
public void Release(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
semaphore.Release();
}
private SemaphoreSlim GetSemaphoreForReducedSubject(TSubject subject)
{
var reducedSubject = _subjectReductionMap.Invoke(subject);
var semaphore = _semaphores.GetOrAdd(reducedSubject, new SemaphoreSlim(_concurrencyLimit));
return semaphore;
}
}
}
```
Allow for grouping to null | ```c#
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace Verdeler
{
internal class ConcurrencyLimiter<TSubject>
{
private readonly Func<TSubject, object> _subjectReductionMap;
private readonly int _concurrencyLimit;
private readonly ConcurrentDictionary<object, SemaphoreSlim> _semaphores
= new ConcurrentDictionary<object, SemaphoreSlim>();
public ConcurrencyLimiter(Func<TSubject, object> subjectReductionMap, int concurrencyLimit)
{
if (concurrencyLimit <= 0)
{
throw new ArgumentException(@"Concurrency limit must be greater than 0.", nameof(concurrencyLimit));
}
_subjectReductionMap = subjectReductionMap;
_concurrencyLimit = concurrencyLimit;
}
public async Task WaitFor(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
if (semaphore == null)
{
await Task.FromResult(0);
}
else
{
await semaphore.WaitAsync().ConfigureAwait(false);
}
}
public void Release(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
semaphore?.Release();
}
private SemaphoreSlim GetSemaphoreForReducedSubject(TSubject subject)
{
var reducedSubject = _subjectReductionMap.Invoke(subject);
if (reducedSubject == null)
{
return null;
}
var semaphore = _semaphores.GetOrAdd(reducedSubject, new SemaphoreSlim(_concurrencyLimit));
return semaphore;
}
}
}
``` |
371ff056-c960-48b8-8178-e0fcf8c8f0f4 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Bibliotheca.Server.Depository.FileSystem.Core.DataTransferObjects
{
public class ProjectDto
{
public ProjectDto()
{
Tags = new List<string>();
VisibleBranches = new List<string>();
EditLinks = new List<EditLinkDto>();
}
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string DefaultBranch { get; set; }
public List<string> VisibleBranches { get; set; }
public List<string> Tags { get; private set; }
public string Group { get; set; }
public string ProjectSite { get; set; }
public List<ContactPersonDto> ContactPeople { get; set; }
public List<EditLinkDto> EditLinks { get; set; }
}
}```
Add access token to project. | ```c#
using System.Collections.Generic;
namespace Bibliotheca.Server.Depository.FileSystem.Core.DataTransferObjects
{
public class ProjectDto
{
public ProjectDto()
{
Tags = new List<string>();
VisibleBranches = new List<string>();
EditLinks = new List<EditLinkDto>();
}
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string DefaultBranch { get; set; }
public List<string> VisibleBranches { get; set; }
public List<string> Tags { get; private set; }
public string Group { get; set; }
public string ProjectSite { get; set; }
public List<ContactPersonDto> ContactPeople { get; set; }
public List<EditLinkDto> EditLinks { get; set; }
public string AccessToken { get; set; }
}
}``` |
f36171ef-e497-490e-ace1-627867762335 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Duality;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython.Resources
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScript)]
public class PythonScript : Resource
{
protected string _content;
public string Content { get { return _content; } }
public void UpdateContent(string content)
{
_content = content;
}
}
}
```
Add sample script when a script is created | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Duality;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython.Resources
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScript)]
public class PythonScript : Resource
{
protected string _content;
public string Content { get { return _content; } }
public PythonScript()
{
var sb = new StringBuilder();
sb.AppendLine("# You can access the parent GameObject by calling `gameObject`.");
sb.AppendLine("# To use Duality objects, you must first import them.");
sb.AppendLine("# Example:");
sb.AppendLine(@"#\tfrom Duality import Vector2");
sb.AppendLine();
sb.AppendLine("class PyModule: ");
sb.AppendLine(" def __init__(self):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine("# The `start` function is called whenever a component is initializing.");
sb.AppendLine(" def start(self):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine("# The `update` function is called whenever an update happens, and includes a delta.");
sb.AppendLine(" def update(self, delta):");
sb.AppendLine(" pass");
sb.AppendLine();
_content = sb.ToString();
}
public void UpdateContent(string content)
{
_content = content;
}
}
}
``` |
5e73bda3-1016-433e-871f-c723b71cac4c | {
"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 System;
using NUnit.Framework;
namespace osu.Game.Tests
{
/// <summary>
/// An attribute to mark any flaky tests.
/// Will add a retry count unless environment variable `FAIL_FLAKY_TESTS` is set to `1`.
/// </summary>
public class FlakyTestAttribute : RetryAttribute
{
public FlakyTestAttribute()
: this(10)
{
}
public FlakyTestAttribute(int tryCount)
: base(Environment.GetEnvironmentVariable("FAIL_FLAKY_TESTS") == "1" ? 0 : tryCount)
{
}
}
}
```
Rename ENVVAR in line with previous one (`OSU_TESTS_NO_TIMEOUT`) | ```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 System;
using NUnit.Framework;
namespace osu.Game.Tests
{
/// <summary>
/// An attribute to mark any flaky tests.
/// Will add a retry count unless environment variable `FAIL_FLAKY_TESTS` is set to `1`.
/// </summary>
public class FlakyTestAttribute : RetryAttribute
{
public FlakyTestAttribute()
: this(10)
{
}
public FlakyTestAttribute(int tryCount)
: base(Environment.GetEnvironmentVariable("OSU_TESTS_FAIL_FLAKY") == "1" ? 0 : tryCount)
{
}
}
}
``` |
a4521c93-aaa6-4480-a069-106dc2087425 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using Fungus;
public class SpritesRoom : Room
{
public Room menuRoom;
public Animator blueAlienAnim;
public SpriteController blueAlienSprite;
void OnEnter()
{
Say("Pink Alien says to Blue Alien...");
Say("...'Show me your funky moves!'");
SetAnimatorTrigger(blueAlienAnim, "StartBlueWalk");
Say("Blue Alien starts to dance.");
Say("Tap on Blue Alien to stop him dancing.");
}
// This method is called from the Button component on the BlueAlien object
void StopDancing()
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Nice moves there Blue Alien!");
Say("Uh oh, you look like you're turning a little green after all that dancing!");
SetAnimatorTrigger(blueAlienAnim, "StartGreenWalk");
Say("Never mind, you'll feel better soon!");
}
void OnAnimationEvent(string eventName)
{
if (eventName == "GreenAnimationFinished")
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Well done Blue Alien! Time to say goodbye!");
FadeSprite(blueAlienSprite, 0, 1f);
Wait(1f);
Say("Heh. That Blue Alien - what a guy!");
MoveToRoom(menuRoom);
}
}
}
```
Make sure blue alien is visible next time you visit Sprites Room. | ```c#
using UnityEngine;
using System.Collections;
using Fungus;
public class SpritesRoom : Room
{
public Room menuRoom;
public Animator blueAlienAnim;
public SpriteController blueAlienSprite;
void OnEnter()
{
ShowSprite(blueAlienSprite);
Say("Pink Alien says to Blue Alien...");
Say("...'Show me your funky moves!'");
SetAnimatorTrigger(blueAlienAnim, "StartBlueWalk");
Say("Blue Alien starts to dance.");
Say("Tap on Blue Alien to stop him dancing.");
}
// This method is called from the Button component on the BlueAlien object
void StopDancing()
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Nice moves there Blue Alien!");
Say("Uh oh, you look like you're turning a little green after all that dancing!");
SetAnimatorTrigger(blueAlienAnim, "StartGreenWalk");
Say("Never mind, you'll feel better soon!");
}
void OnAnimationEvent(string eventName)
{
if (eventName == "GreenAnimationFinished")
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Well done Blue Alien! Time to say goodbye!");
FadeSprite(blueAlienSprite, 0, 1f);
Wait(1f);
Say("Heh. That Blue Alien - what a guy!");
MoveToRoom(menuRoom);
}
}
}
``` |
89c7e673-151d-46b8-8e2b-430b15363709 | {
"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.Graphics.OpenGL.Buffers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.OpenGL.Vertices;
using osuTK.Graphics.ES30;
namespace osu.Framework.Graphics.Batches
{
/// <summary>
/// A batch to be used when drawing triangles with <see cref="TextureGLSingle.DrawTriangle"/>.
/// </summary>
public class TriangleBatch<T> : VertexBatch<T>
where T : struct, IEquatable<T>, IVertex
{
public TriangleBatch(int size, int maxBuffers)
: base(size, maxBuffers)
{
}
protected override VertexBuffer<T> CreateVertexBuffer() => new QuadVertexBuffer<T>(Size, BufferUsageHint.DynamicDraw);
}
}
```
Add a comment explaining why we're using QuadVertexBuffer | ```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.Graphics.OpenGL.Buffers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.OpenGL.Vertices;
using osuTK.Graphics.ES30;
namespace osu.Framework.Graphics.Batches
{
/// <summary>
/// A batch to be used when drawing triangles with <see cref="TextureGLSingle.DrawTriangle"/>.
/// </summary>
public class TriangleBatch<T> : VertexBatch<T>
where T : struct, IEquatable<T>, IVertex
{
public TriangleBatch(int size, int maxBuffers)
: base(size, maxBuffers)
{
}
//We can re-use the QuadVertexBuffer as both Triangles and Quads have four Vertices and six indices.
protected override VertexBuffer<T> CreateVertexBuffer() => new QuadVertexBuffer<T>(Size, BufferUsageHint.DynamicDraw);
}
}
``` |
6f41bb5f-2f5f-411b-be95-806c7d475e21 | {
"language": "C#"
} | ```c#
/*
AssemblyInfo.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright (c) 2011 - 2018 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) 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.
Morgan's CLR Advanced Runtime (MCART) 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.Reflection;
[assembly: AssemblyCompany("TheXDS! non-Corp.")]
[assembly: AssemblyProduct("Morgan's CLR Advanced Runtime")]
[assembly: AssemblyCopyright("Copyright © 2011-2018 César Andrés Morgan")]
[assembly: AssemblyVersion("0.8.3.4")]
#if CLSCompliance
[assembly: System.CLSCompliant(true)]
#endif```
Bump número de versión a 0.8.4.0 | ```c#
/*
AssemblyInfo.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright (c) 2011 - 2018 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) 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.
Morgan's CLR Advanced Runtime (MCART) 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.Reflection;
[assembly: AssemblyCompany("TheXDS! non-Corp.")]
[assembly: AssemblyProduct("Morgan's CLR Advanced Runtime")]
[assembly: AssemblyCopyright("Copyright © 2011-2018 César Andrés Morgan")]
[assembly: AssemblyVersion("0.8.4.0")]
#if CLSCompliance
[assembly: System.CLSCompliant(true)]
#endif``` |
7795a23b-76dd-4f6a-b0ed-a510b6aab41d | {
"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.
namespace osu.Framework.Timing
{
/// <summary>
/// A clock which will only update its current time when a frame proces is triggered.
/// Useful for keeping a consistent time state across an individual update.
/// </summary>
public interface IFrameBasedClock : IClock
{
/// <summary>
/// Elapsed time since last frame in milliseconds.
/// </summary>
double ElapsedFrameTime { get; }
/// <summary>
/// A moving average representation of the frames per second of this clock.
/// Do not use this for any timing purposes (use <see cref="ElapsedFrameTime"/> instead).
/// </summary>
double FramesPerSecond { get; }
FrameTimeInfo TimeInfo { get; }
/// <summary>
/// Processes one frame. Generally should be run once per update loop.
/// </summary>
void ProcessFrame();
}
}
```
Correct misspelled word in the interface summary | ```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.
namespace osu.Framework.Timing
{
/// <summary>
/// A clock which will only update its current time when a frame process is triggered.
/// Useful for keeping a consistent time state across an individual update.
/// </summary>
public interface IFrameBasedClock : IClock
{
/// <summary>
/// Elapsed time since last frame in milliseconds.
/// </summary>
double ElapsedFrameTime { get; }
/// <summary>
/// A moving average representation of the frames per second of this clock.
/// Do not use this for any timing purposes (use <see cref="ElapsedFrameTime"/> instead).
/// </summary>
double FramesPerSecond { get; }
FrameTimeInfo TimeInfo { get; }
/// <summary>
/// Processes one frame. Generally should be run once per update loop.
/// </summary>
void ProcessFrame();
}
}
``` |
eb91e1b9-1d08-49cc-9cc6-eaf3620c1d54 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComponentPool<T> where T : MonoBehaviour
{
private Func<T> _instantiateAction;
private Action<T> _getComponentAction;
private Action<T> _returnComponentAction;
private Stack<T> _pooledObjects;
private int _lastInstantiatedAmount;
public ComponentPool(int initialPoolSize, Func<T> instantiateFunction, Action<T> getComponentAction = null, Action<T> returnComponentAction = null)
{
this._instantiateAction = instantiateFunction;
this._getComponentAction = getComponentAction;
this._returnComponentAction = returnComponentAction;
this._pooledObjects = new Stack<T>();
InstantiateComponentsIntoPool(initialPoolSize);
}
public T Get()
{
if (_pooledObjects.Count == 0)
InstantiateComponentsIntoPool((_lastInstantiatedAmount * 2) + 1);
T component = _pooledObjects.Pop();
if (_getComponentAction != null)
_getComponentAction(component);
return _pooledObjects.Pop();
}
public void Return(T component)
{
_pooledObjects.Push(component);
if (_returnComponentAction != null)
_returnComponentAction(component);
}
private void InstantiateComponentsIntoPool(int nComponents)
{
for (int i = 0; i < nComponents; i++)
{
var pooledObject = _instantiateAction();
_pooledObjects.Push(pooledObject);
}
_lastInstantiatedAmount = _pooledObjects.Count;
}
}
```
Fix major bug with component pool | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComponentPool<T> where T : MonoBehaviour
{
private Func<T> _instantiateAction;
private Action<T> _getComponentAction;
private Action<T> _returnComponentAction;
private Stack<T> _pooledObjects;
private int _lastInstantiatedAmount;
public ComponentPool(int initialPoolSize, Func<T> instantiateFunction, Action<T> getComponentAction = null, Action<T> returnComponentAction = null)
{
this._instantiateAction = instantiateFunction;
this._getComponentAction = getComponentAction;
this._returnComponentAction = returnComponentAction;
this._pooledObjects = new Stack<T>();
InstantiateComponentsIntoPool(initialPoolSize);
}
public T Get()
{
if (_pooledObjects.Count == 0)
InstantiateComponentsIntoPool((_lastInstantiatedAmount * 2) + 1);
T component = _pooledObjects.Pop();
if (_getComponentAction != null)
_getComponentAction(component);
return component;
}
public void Return(T component)
{
_pooledObjects.Push(component);
if (_returnComponentAction != null)
_returnComponentAction(component);
}
private void InstantiateComponentsIntoPool(int nComponents)
{
for (int i = 0; i < nComponents; i++)
{
var pooledObject = _instantiateAction();
_pooledObjects.Push(pooledObject);
}
_lastInstantiatedAmount = _pooledObjects.Count;
}
}
``` |
7f1f5b5b-5fa3-4f8b-8c30-80cff3498479 | {
"language": "C#"
} | ```c#
using System.Xml.Serialization;
namespace Gigobyte.Daterpillar
{
/// <summary>
/// Represents a database indexed column.
/// </summary>
public struct IndexColumn
{
/// <summary>
/// Gets or sets the column's name.
/// </summary>
/// <value>The name.</value>
[XmlText]
public string Name { get; set; }
/// <summary>
/// Gets or sets the column's order.
/// </summary>
/// <value>The order.</value>
[XmlAttribute("order")]
public SortOrder Order { get; set; }
}
}```
Add new contructors to Index.cs | ```c#
using System.Xml.Serialization;
namespace Gigobyte.Daterpillar
{
/// <summary>
/// Represents a database indexed column.
/// </summary>
public struct IndexColumn
{
/// <summary>
/// Initializes a new instance of the <see cref="IndexColumn"/> struct.
/// </summary>
/// <param name="name">The name.</param>
public IndexColumn(string name) : this(name, SortOrder.ASC)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="IndexColumn"/> struct.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="order">The order.</param>
public IndexColumn(string name, SortOrder order)
{
Name = name;
Order = order;
}
/// <summary>
/// Gets or sets the column's name.
/// </summary>
/// <value>The name.</value>
[XmlText]
public string Name { get; set; }
/// <summary>
/// Gets or sets the column's order.
/// </summary>
/// <value>The order.</value>
[XmlAttribute("order")]
public SortOrder Order { get; set; }
}
}``` |
42531735-691a-4e79-9b41-559cdc1a3322 | {
"language": "C#"
} | ```c#
using CodeHub.Helpers;
using CodeHub.ViewModels;
using Octokit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace CodeHub.Views
{
public sealed partial class IssueDetailView : Windows.UI.Xaml.Controls.Page
{
public IssueDetailViewmodel ViewModel;
public IssueDetailView()
{
this.InitializeComponent();
ViewModel = new IssueDetailViewmodel();
this.DataContext = ViewModel;
NavigationCacheMode = NavigationCacheMode.Required;
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
commentsListView.SelectedIndex = -1;
if (e.NavigationMode != NavigationMode.Back)
{
await ViewModel.Load((e.Parameter as Tuple<string,string, Issue>));
}
}
}
}
```
Clear comments list on navigation | ```c#
using CodeHub.Helpers;
using CodeHub.ViewModels;
using Octokit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace CodeHub.Views
{
public sealed partial class IssueDetailView : Windows.UI.Xaml.Controls.Page
{
public IssueDetailViewmodel ViewModel;
public IssueDetailView()
{
this.InitializeComponent();
ViewModel = new IssueDetailViewmodel();
this.DataContext = ViewModel;
NavigationCacheMode = NavigationCacheMode.Required;
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
commentsListView.SelectedIndex = -1;
if (e.NavigationMode != NavigationMode.Back)
{
if (ViewModel.Comments != null)
{
ViewModel.Comments.Clear();
}
await ViewModel.Load((e.Parameter as Tuple<string,string, Issue>));
}
}
}
}
``` |
3d84a94f-e9ff-41d5-acde-fdaf027f11b3 | {
"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 Newtonsoft.Json;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A container which is serialised and can encapsulate multiple skinnable elements into a single return type (for consumption via <see cref="ISkin.GetDrawableComponent"/>.
/// Will also optionally apply default cross-element layout dependencies when initialised from a non-deserialised source.
/// </summary>
[Serializable]
public class SkinnableTargetWrapper : Container, ISkinnableDrawable
{
public bool IsEditable => false;
private readonly Action<Container> applyDefaults;
/// <summary>
/// Construct a wrapper with defaults that should be applied once.
/// </summary>
/// <param name="applyDefaults">A function to apply the default layout.</param>
public SkinnableTargetWrapper(Action<Container> applyDefaults)
: this()
{
this.applyDefaults = applyDefaults;
}
[JsonConstructor]
public SkinnableTargetWrapper()
{
RelativeSizeAxes = Axes.Both;
}
protected override void LoadComplete()
{
base.LoadComplete();
// schedule is required to allow children to run their LoadComplete and take on their correct sizes.
Schedule(() => applyDefaults?.Invoke(this));
}
}
}
```
Use `ScheduleAfterChildren` to better match comment | ```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 Newtonsoft.Json;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A container which is serialised and can encapsulate multiple skinnable elements into a single return type (for consumption via <see cref="ISkin.GetDrawableComponent"/>.
/// Will also optionally apply default cross-element layout dependencies when initialised from a non-deserialised source.
/// </summary>
[Serializable]
public class SkinnableTargetWrapper : Container, ISkinnableDrawable
{
public bool IsEditable => false;
private readonly Action<Container> applyDefaults;
/// <summary>
/// Construct a wrapper with defaults that should be applied once.
/// </summary>
/// <param name="applyDefaults">A function to apply the default layout.</param>
public SkinnableTargetWrapper(Action<Container> applyDefaults)
: this()
{
this.applyDefaults = applyDefaults;
}
[JsonConstructor]
public SkinnableTargetWrapper()
{
RelativeSizeAxes = Axes.Both;
}
protected override void LoadComplete()
{
base.LoadComplete();
// schedule is required to allow children to run their LoadComplete and take on their correct sizes.
ScheduleAfterChildren(() => applyDefaults?.Invoke(this));
}
}
}
``` |
f8b55ae2-6584-4138-91ac-32f4db4daa8d | {
"language": "C#"
} | ```c#
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=5</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle005 : Puzzle
{
/// <inheritdoc />
public override string Question => "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to the specified value?";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified maximum number is invalid.");
return -1;
}
var divisors = Enumerable.Range(1, max).ToList();
for (int i = 1; i < int.MaxValue; i++)
{
if (divisors.All((p) => i % p == 0))
{
Answer = i;
break;
}
}
return 0;
}
}
}
```
Improve performance of puzzle 5 | ```c#
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=5</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle005 : Puzzle
{
/// <inheritdoc />
public override string Question => "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to the specified value?";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified maximum number is invalid.");
return -1;
}
var divisors = Enumerable.Range(1, max).ToList();
for (int n = max; ; n++)
{
if (divisors.All((p) => n % p == 0))
{
Answer = n;
break;
}
}
return 0;
}
}
}
``` |
5eea338c-a42e-4021-bd34-2c52e6905e68 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AngleSharp")]
[assembly: AssemblyDescription("AngleSharp is the ultimate angle brackets parser library. It parses HTML5, MathML, SVG, XML and CSS to construct a DOM based on the official W3C specification.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AngleVisions")]
[assembly: AssemblyProduct("AngleSharp")]
[assembly: AssemblyCopyright("Copyright © Florian Rappl et al. 2013-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleToAttribute("AngleSharp.Core.Tests")]
[assembly: AssemblyVersion("0.8.6.*")]
[assembly: AssemblyFileVersion("0.8.6")]```
Change version number to 0.8.7 | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AngleSharp")]
[assembly: AssemblyDescription("AngleSharp is the ultimate angle brackets parser library. It parses HTML5, MathML, SVG, XML and CSS to construct a DOM based on the official W3C specification.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AngleVisions")]
[assembly: AssemblyProduct("AngleSharp")]
[assembly: AssemblyCopyright("Copyright © Florian Rappl et al. 2013-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleToAttribute("AngleSharp.Core.Tests")]
[assembly: AssemblyVersion("0.8.7.*")]
[assembly: AssemblyFileVersion("0.8.7")]``` |
9870d861-9bd8-46b2-a52c-c7cdebbbd5cd | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
namespace Mvc.Mailer {
/// <summary>
/// This class is a utility class for instantiating LinkedResource objects
/// </summary>
public class LinkedResourceProvider : ILinkedResourceProvider {
public virtual List<LinkedResource> GetAll(Dictionary<string, string> resources) {
return resources
.Select(resource => Get(resource.Key, resource.Value))
.ToList();
}
public virtual LinkedResource Get(string contentId, string filePath) {
return new LinkedResource(filePath, GetContentType(filePath)) { ContentId = contentId };
}
public virtual ContentType GetContentType(string fileName) {
// Tyler: Possible null reference
var ext = System.IO.Path.GetExtension(fileName).ToLower();
var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null) {
return new ContentType(regKey.GetValue("Content Type").ToString());
}
return null;
}
}
}```
Remove comment, null check unnecessary. | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
namespace Mvc.Mailer {
/// <summary>
/// This class is a utility class for instantiating LinkedResource objects
/// </summary>
public class LinkedResourceProvider : ILinkedResourceProvider {
public virtual List<LinkedResource> GetAll(Dictionary<string, string> resources) {
return resources
.Select(resource => Get(resource.Key, resource.Value))
.ToList();
}
public virtual LinkedResource Get(string contentId, string filePath) {
return new LinkedResource(filePath, GetContentType(filePath)) { ContentId = contentId };
}
public virtual ContentType GetContentType(string fileName) {
var ext = System.IO.Path.GetExtension(fileName).ToLower();
var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null) {
return new ContentType(regKey.GetValue("Content Type").ToString());
}
return null;
}
}
}``` |
f5d689c6-219d-4dec-a99b-ec077534e55c | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System.IO;
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality
{
/// <summary>
/// Class to perform checks for configuration checks for the Windows Mixed Reality provider.
/// </summary>
[InitializeOnLoad]
static class WindowsMixedRealityConfigurationChecker
{
private const string FileName = "Microsoft.Windows.MixedReality.DotNetWinRT.dll";
private static readonly string[] definitions = { "DOTNETWINRT_PRESENT" };
static WindowsMixedRealityConfigurationChecker()
{
ReconcileDotNetWinRTDefine();
}
/// <summary>
/// Ensures that the appropriate symbolic constant is defined based on the presence of the DotNetWinRT binary.
/// </summary>
private static void ReconcileDotNetWinRTDefine()
{
FileInfo[] files = FileUtilities.FindFilesInAssets(FileName);
if (files.Length > 0)
{
ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
else
{
ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
}
}
}
```
Replace InitOnLoad with MRTK > Utils > WMR > Check Config | ```c#
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System.IO;
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality
{
/// <summary>
/// Class to perform checks for configuration checks for the Windows Mixed Reality provider.
/// </summary>
static class WindowsMixedRealityConfigurationChecker
{
private const string FileName = "Microsoft.Windows.MixedReality.DotNetWinRT.dll";
private static readonly string[] definitions = { "DOTNETWINRT_PRESENT" };
/// <summary>
/// Ensures that the appropriate symbolic constant is defined based on the presence of the DotNetWinRT binary.
/// </summary>
[MenuItem("Mixed Reality Toolkit/Utilities/Windows Mixed Reality/Check Configuration")]
private static void ReconcileDotNetWinRTDefine()
{
FileInfo[] files = FileUtilities.FindFilesInAssets(FileName);
if (files.Length > 0)
{
ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
else
{
ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
}
}
}
``` |
229e65b4-b1f5-4eaf-8340-7e21138bffe4 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests
{
internal class VisualTestGame : Game
{
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
};
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
host.Window.CursorState |= CursorState.Hidden;
}
}
}
```
Add the tests executable as a resource store | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests
{
internal class VisualTestGame : Game
{
[BackgroundDependencyLoader]
private void load()
{
Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.exe"), "Resources"));
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
};
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
host.Window.CursorState |= CursorState.Hidden;
}
}
}
``` |
df490eb1-67bb-4aad-92c5-60139bb60abf | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
}
}```
Fix webview reload on rotation | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
if (savedInstanceState == null)
{
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState(outState);
webView.SaveState(outState);
}
protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
base.OnRestoreInstanceState(savedInstanceState);
webView.RestoreState(savedInstanceState);
}
}
}``` |
a34d20ed-0dd1-4dcb-bd12-09aeb6a7eaaa | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Xamarin;
namespace Espera.Core.Analytics
{
internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint
{
private Guid id;
public void Dispose()
{
// Xamarin Insights can only be terminated if it has been started before, otherwise it
// throws an exception
if (Insights.IsInitialized)
{
Insights.Terminate();
}
}
public void Identify(string id, IDictionary<string, string> traits = null)
{
traits.Add(Insights.Traits.Name, id);
Insights.Identify(id, traits);
}
public void Initialize(Guid id)
{
this.id = id;
Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath);
}
public void ReportBug(string message)
{
var exception = new Exception(message);
Insights.Report(exception);
}
public void ReportFatalException(Exception exception) => Insights.Report(exception, ReportSeverity.Error);
public void ReportNonFatalException(Exception exception) => Insights.Report(exception);
public void Track(string key, IDictionary<string, string> traits = null) => Insights.Track(key, traits);
public IDisposable TrackTime(string key, IDictionary<string, string> traits = null) => Insights.TrackTime(key, traits);
public void UpdateEmail(string email) => Insights.Identify(id.ToString(), Insights.Traits.Email, email);
}
}```
Call Insights.Save when reporting a crash | ```c#
using System;
using System.Collections.Generic;
using Xamarin;
namespace Espera.Core.Analytics
{
internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint
{
private Guid id;
public void Dispose()
{
// Xamarin Insights can only be terminated if it has been started before, otherwise it
// throws an exception
if (Insights.IsInitialized)
{
Insights.Terminate();
}
}
public void Identify(string id, IDictionary<string, string> traits = null)
{
traits.Add(Insights.Traits.Name, id);
Insights.Identify(id, traits);
}
public void Initialize(Guid id)
{
this.id = id;
Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath);
}
public void ReportBug(string message)
{
var exception = new Exception(message);
Insights.Report(exception);
}
public void ReportFatalException(Exception exception)
{
Insights.Report(exception, ReportSeverity.Error);
Insights.Save().Wait();
}
public void ReportNonFatalException(Exception exception) => Insights.Report(exception);
public void Track(string key, IDictionary<string, string> traits = null) => Insights.Track(key, traits);
public IDisposable TrackTime(string key, IDictionary<string, string> traits = null) => Insights.TrackTime(key, traits);
public void UpdateEmail(string email) => Insights.Identify(id.ToString(), Insights.Traits.Email, email);
}
}``` |
2d6e9587-566a-4f7a-bdf9-6cc9fa77136c | {
"language": "C#"
} | ```c#
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
app.Run(new MainWindow());
}
}
}
```
Create VM in MVVM app template. | ```c#
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
var window = new MainWindow
{
DataContext = new MainWindowViewModel(),
};
app.Run(window);
}
}
}
``` |
821fa3c4-2169-420e-a04d-f1e9b56f027a | {
"language": "C#"
} | ```c#
namespace TestStack.ConventionTests.ConventionData
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// This is where we set what our convention is all about.
/// </summary>
public class Types : IConventionData
{
public Types(string descriptionOfTypes)
{
Description = descriptionOfTypes;
}
public Type[] TypesToVerify { get; set; }
public string Description { get; private set; }
public bool HasData {get { return TypesToVerify.Any(); }}
public static Types InAssemblyOf<T>()
{
var assembly = typeof(T).Assembly;
return new Types(assembly.GetName().Name)
{
TypesToVerify = assembly.GetTypes()
};
}
public static Types InAssemblyOf<T>(string descriptionOfTypes, Func<IEnumerable<Type>, IEnumerable<Type>> types)
{
var assembly = typeof (T).Assembly;
return new Types(descriptionOfTypes)
{
TypesToVerify = types(assembly.GetTypes()).ToArray()
};
}
}
}```
Exclude compiler generated types by default | ```c#
namespace TestStack.ConventionTests.ConventionData
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
/// <summary>
/// This is where we set what our convention is all about.
/// </summary>
public class Types : IConventionData
{
public Types(string descriptionOfTypes)
{
Description = descriptionOfTypes;
}
public Type[] TypesToVerify { get; set; }
public string Description { get; private set; }
public bool HasData {get { return TypesToVerify.Any(); }}
public static Types InAssemblyOf<T>(bool excludeCompilerGeneratedTypes = true)
{
var assembly = typeof(T).Assembly;
var typesToVerify = assembly.GetTypes();
if (excludeCompilerGeneratedTypes)
{
typesToVerify = typesToVerify
.Where(t => !t.GetCustomAttributes(typeof (CompilerGeneratedAttribute), true).Any())
.ToArray();
}
return new Types(assembly.GetName().Name)
{
TypesToVerify = typesToVerify
};
}
public static Types InAssemblyOf<T>(string descriptionOfTypes, Func<IEnumerable<Type>, IEnumerable<Type>> types)
{
var assembly = typeof (T).Assembly;
return new Types(descriptionOfTypes)
{
TypesToVerify = types(assembly.GetTypes()).ToArray()
};
}
}
}``` |
e9ee342e-f87b-4c7c-a957-e110914871a1 | {
"language": "C#"
} | ```c#
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Redists.Core
{
internal class TimeSeriesWriter : ITimeSeriesWriter
{
private readonly IDatabaseAsync dbAsync;
private TimeSpan? ttl;
private IDataPointParser parser;
private ConcurrentDictionary<string, DateTime> expirations = new ConcurrentDictionary<string, DateTime>();
public TimeSeriesWriter(IDatabaseAsync dbAsync, IDataPointParser parser, TimeSpan? ttl)
{
this.dbAsync = dbAsync;
this.parser = parser;
this.ttl = ttl;
}
public Task<long> AppendAsync(string redisKey, params DataPoint[] dataPoints)
{
ManageKeyExpiration(redisKey);
var toAppend = parser.Serialize(dataPoints) + Constants.InterDelimiter;
return this.dbAsync.StringAppendAsync(redisKey, toAppend);
}
private void ManageKeyExpiration(string key)
{
DateTime lastSent=expirations.GetOrAdd(key, DateTime.MinValue);
if ((DateTime.UtcNow- lastSent)> this.ttl.Value)
{
this.dbAsync.KeyExpireAsync(key, ttl);
expirations.TryUpdate(key, DateTime.UtcNow, lastSent);
}
}
}
}
```
Fix : Null ttl value | ```c#
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Redists.Core
{
internal class TimeSeriesWriter : ITimeSeriesWriter
{
private readonly IDatabaseAsync dbAsync;
private TimeSpan? ttl;
private IDataPointParser parser;
private ConcurrentDictionary<string, DateTime> expirations = new ConcurrentDictionary<string, DateTime>();
public TimeSeriesWriter(IDatabaseAsync dbAsync, IDataPointParser parser, TimeSpan? ttl)
{
this.dbAsync = dbAsync;
this.parser = parser;
this.ttl = ttl;
}
public Task<long> AppendAsync(string redisKey, params DataPoint[] dataPoints)
{
ManageKeyExpiration(redisKey);
var toAppend = parser.Serialize(dataPoints) + Constants.InterDelimiter;
return this.dbAsync.StringAppendAsync(redisKey, toAppend);
}
private void ManageKeyExpiration(string key)
{
if (!this.ttl.HasValue)
return;
DateTime lastSent=expirations.GetOrAdd(key, DateTime.MinValue);
if ((DateTime.UtcNow- lastSent)> this.ttl.Value)
{
this.dbAsync.KeyExpireAsync(key, ttl);
expirations.TryUpdate(key, DateTime.UtcNow, lastSent);
}
}
}
}
``` |
318fdcde-9c0c-4a6c-bc1f-51c038e1f4e3 | {
"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("Utils.Net")]
[assembly: AssemblyDescription("Collection of utilities for .NET projects")]
[assembly: AssemblyProduct("Utils.Net")]
[assembly: AssemblyCopyright("Copyright © Utils.NET 2015")]
// 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("91da47c7-b676-42c6-935f-b42282c46c27")]
// 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: InternalsVisibleTo("UtilsTest")]
```
Revert "Removing the assembly version attribute since appveyor doesn't seem to respect custom version format" | ```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("Utils.Net")]
[assembly: AssemblyDescription("Collection of utilities for .NET projects")]
[assembly: AssemblyProduct("Utils.Net")]
[assembly: AssemblyCopyright("Copyright © Utils.NET 2015")]
// 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("91da47c7-b676-42c6-935f-b42282c46c27")]
// 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: InternalsVisibleTo("UtilsTest")]
``` |
24f4088c-63aa-4128-9f99-5093262ca717 | {
"language": "C#"
} | ```c#
/*
* Copyright 2014 Dominick Baier, Brock Allen
*
* 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.Collections.Generic;
namespace Thinktecture.IdentityServer.Core.Models
{
public class SignInMessage : Message
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public string IdP { get; set; }
public string Tenant { get; set; }
public string DisplayMode { get; set; }
public string UiLocales { get; set; }
public IEnumerable<string> AcrValues { get; set; }
}
}```
Make sure AcrValues is not null | ```c#
/*
* Copyright 2014 Dominick Baier, Brock Allen
*
* 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.Collections.Generic;
using System.Linq;
namespace Thinktecture.IdentityServer.Core.Models
{
public class SignInMessage : Message
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public string IdP { get; set; }
public string Tenant { get; set; }
public string DisplayMode { get; set; }
public string UiLocales { get; set; }
public IEnumerable<string> AcrValues { get; set; }
public SignInMessage()
{
AcrValues = Enumerable.Empty<string>();
}
}
}``` |
8465e366-2999-4de9-8380-fd0398530d4e | {
"language": "C#"
} | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.2.0";
}
}
```
Update file ver to 3.0.3.0 | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.3.0";
}
}
``` |
02df28b9-45f5-4db5-94e7-59f867d498ce | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security;
namespace HttpMock.Integration.Tests
{
internal static class PortHelper
{
internal static int FindLocalAvailablePortForTesting ()
{
for (var i = 1025; i <= 65000; i++)
{
if (!ConnectToPort(i))
return i;
}
throw new HostProtectionException("localhost seems to have ALL ports open, are you mad?");
}
private static bool ConnectToPort(int i)
{
var allIpAddresses = (from adapter in NetworkInterface.GetAllNetworkInterfaces()
from unicastAddress in adapter.GetIPProperties().UnicastAddresses
select unicastAddress.Address)
.ToList();
bool connected = false;
foreach (var ipAddress in allIpAddresses)
{
using (var tcpClient = new TcpClient())
{
try
{
tcpClient.Connect(ipAddress, i);
connected = tcpClient.Connected;
}
catch (SocketException)
{
}
finally
{
try
{
tcpClient.Close();
}
catch
{
}
}
}
if (connected)
return true;
}
return false;
}
}
}
```
Change how we find a local port. Connecting to a local port and releasing it is flaky and slow. use network info to find what port is available | ```c#
using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security;
namespace HttpMock.Integration.Tests
{
internal static class PortHelper
{
internal static int FindLocalAvailablePortForTesting ()
{
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
var activeTcpConnections = properties.GetActiveTcpConnections();
var minPort = activeTcpConnections.Select(a => a.LocalEndPoint.Port).Max();
var random = new Random();
var randomPort = random.Next(minPort, 65000);
while (activeTcpConnections.Any(a => a.LocalEndPoint.Port == randomPort))
{
randomPort = random.Next(minPort, 65000);
}
return randomPort;
}
}
}
``` |
119ab464-3042-40f2-98c2-4f62bf8f26be | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - sniperrifle.sfx.cs
// Sounds for the sniper rifle
//------------------------------------------------------------------------------
datablock AudioProfile(SniperRifleFireSound)
{
filename = "share/sounds/rotc/fire6.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperExplosionSound)
{
filename = "share/sounds/rotc/fire2.wav";
description = AudioFar3D;
preload = true;
};
datablock AudioProfile(SniperDebrisSound)
{
filename = "share/sounds/rotc/debris1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperPowerUpSound)
{
filename = "share/sounds/rotc/charge2.wav";
description = AudioClose3D;
preload = true;
};
datablock AudioProfile(SniperProjectileImpactSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioClose3D;
preload = true;
};
```
Change sniper rifle projectile explosion sound. | ```c#
//------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - sniperrifle.sfx.cs
// Sounds for the sniper rifle
//------------------------------------------------------------------------------
datablock AudioProfile(SniperRifleFireSound)
{
filename = "share/sounds/rotc/fire6.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperExplosionSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioFar3D;
preload = true;
};
datablock AudioProfile(SniperDebrisSound)
{
filename = "share/sounds/rotc/debris1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperPowerUpSound)
{
filename = "share/sounds/rotc/charge2.wav";
description = AudioClose3D;
preload = true;
};
datablock AudioProfile(SniperProjectileImpactSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioClose3D;
preload = true;
};
``` |
e5870913-fe25-44c8-a720-ed335a1c16c5 | {
"language": "C#"
} | ```c#
// Copyright 2015 Renaud Paquay All Rights Reserved.
//
// 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;
namespace mtsuite.shared.Collections {
/// <summary>
/// Default pool factory, create most generally useful <see cref="IPool{T}"/>
/// instances.
/// </summary>
public static class PoolFactory<T> where T : class {
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler);
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler, int size) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler, size);
}
}
}```
Add compile-time constant to switch to no-op pool | ```c#
// Copyright 2015 Renaud Paquay All Rights Reserved.
//
// 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;
namespace mtsuite.shared.Collections {
/// <summary>
/// Default pool factory, create most generally useful <see cref="IPool{T}"/>
/// instances.
/// </summary>
public static class PoolFactory<T> where T : class {
#if USE_NOOP_POOL
public static IPool<T> Create(Func<T> creator) {
return Create(creator, _ => { });
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentNoOpPool<T>(creator);
}
#else
public static IPool<T> Create(Func<T> creator) {
return Create(creator, _ => { });
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler);
}
#endif
}
}``` |
202025f8-0e1a-44f0-b3f5-27512b819d4d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DiplomContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
}```
Set M:M relationsheep beetween Users and Roles | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DiplomContext() : base()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserRole>()
.HasKey(t => new { t.UserId, t.RoleId });
modelBuilder.Entity<UserRole>()
.HasOne(pt => pt.User)
.WithMany(p => p.Roles)
.HasForeignKey(pt => pt.RoleId);
modelBuilder.Entity<UserRole>()
.HasOne(pt => pt.Role)
.WithMany(t => t.Users)
.HasForeignKey(pt => pt.UserId);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
}``` |
95a849e8-dd55-4e88-8504-509832aed1d2 | {
"language": "C#"
} | ```c#
using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
public float blankGazeDistance;
public Transform trackedTransform;
public float lerp;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
Vector3 target;
if (speaker != null && speaker != transform.parent.parent.gameObject)
{
target = speaker.transform.Find("HeadController").position;
}
else
{
target = transform.position + transform.forward * blankGazeDistance;
}
SlowlyRotateTowards(target);
} else {
transform.position = Vector3.Lerp(transform.position, trackedTransform.position, lerp * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, trackedTransform.rotation, lerp * Time.deltaTime);
}
}
void SlowlyRotateTowards(Vector3 target)
{
Vector3 direction = (target - transform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * speed);
}
}
```
Fix look at speaker to follow Performative/Head | ```c#
using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
public float blankGazeDistance;
public Transform trackedTransform;
public float lerp;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
Vector3 target;
if (speaker != null && speaker != transform.parent.parent.gameObject)
{
target = speaker.transform.Find("Performative/Head").position;
}
else
{
target = transform.position + transform.forward * blankGazeDistance;
}
SlowlyRotateTowards(target);
} else {
transform.position = Vector3.Lerp(transform.position, trackedTransform.position, lerp * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, trackedTransform.rotation, lerp * Time.deltaTime);
}
}
void SlowlyRotateTowards(Vector3 target)
{
Vector3 direction = (target - transform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * speed);
}
}
``` |
c8930da2-b7e6-46a9-a8f0-961e5213d250 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDesk.DBus;
namespace Palaso.UsbDrive.Linux
{
public class UDisks
{
private readonly IUDisks _udisks;
public UDisks()
{
_udisks = Bus.System.GetObject<IUDisks>("org.freedesktop.UDisks", new ObjectPath("/org/freedesktop/UDisks"));
}
public IUDisks Interface
{
get { return _udisks; }
}
public IEnumerable<string> EnumerateDeviceOnInterface(string onInterface)
{
var devices = Interface.EnumerateDevices();
foreach (var device in devices)
{
var uDiskDevice = new UDiskDevice(device);
string iface = uDiskDevice.GetProperty("DriveConnectionInterface");
string partition = uDiskDevice.GetProperty("DeviceIsPartition");
if (iface == onInterface && uDiskDevice.IsMounted)
{
yield return device;
}
}
}
}
}
```
Fix Linux hanging bug due to USB drive enumeration | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDesk.DBus;
namespace Palaso.UsbDrive.Linux
{
public class UDisks
{
private readonly IUDisks _udisks;
public UDisks()
{
_udisks = Bus.System.GetObject<IUDisks>("org.freedesktop.UDisks", new ObjectPath("/org/freedesktop/UDisks"));
}
public IUDisks Interface
{
get { return _udisks; }
}
public IEnumerable<string> EnumerateDeviceOnInterface(string onInterface)
{
var devices = Interface.EnumerateDevices();
foreach (var device in devices)
{
var uDiskDevice = new UDiskDevice(device);
string iface = uDiskDevice.GetProperty("DriveConnectionInterface");
string partition = uDiskDevice.GetProperty("DeviceIsPartition");
if (iface == onInterface && uDiskDevice.IsMounted)
{
yield return device;
}
}
// If Bus.System is not closed, the program hangs when it ends, waiting for
// the associated thread to quit. It appears to properly reopen Bus.System
// if we try to use it again after closing it.
// And calling Close() here appears to work okay in conjunction with the
// yield return above.
Bus.System.Close();
}
}
}
``` |
c4e1835d-05a9-4609-b911-96bfcfd4e87b | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using ToDoList.Automation.Api.ApiActions;
using Tranquire;
namespace ToDoList.Automation.Api
{
public static class Remove
{
public static IAction<Task> ToDoItem(string title) => Get.TheToDoItem(title)
.SelectMany<Task<Model.ToDoItem>, Task>(itemTask =>
{
return Actions.Create(
$"Remove to-do item",
async actor =>
{
var item = await itemTask;
return actor.Execute(new RemoveToDoItem(item.Id));
});
});
}
}
```
Use SelectMany in demo application | ```c#
using System.Threading.Tasks;
using ToDoList.Automation.Api.ApiActions;
using Tranquire;
namespace ToDoList.Automation.Api
{
public static class Remove
{
public static IAction<Task> ToDoItem(string title) => Get.TheToDoItem(title)
.SelectMany(item => new RemoveToDoItem(item.Id));
}
}
``` |
dbdee024-66f4-4d84-af45-a826dd5dd303 | {
"language": "C#"
} | ```c#
using System.ComponentModel.DataAnnotations;
namespace Tgstation.Server.Api.Models
{
/// <summary>
/// Parameters for creating a <see cref="TestMerge"/>
/// </summary>
public class TestMergeParameters
{
/// <summary>
/// The number of the pull request
/// </summary>
public int? Number { get; set; }
/// <summary>
/// The sha of the pull request revision to merge. If not specified, the latest commit shall be used (semi-unsafe)
/// </summary>
[Required]
public string PullRequestRevision { get; set; }
/// <summary>
/// Optional comment about the test
/// </summary>
public string Comment { get; set; }
}
}```
Mark this as required since it's nullable now | ```c#
using System.ComponentModel.DataAnnotations;
namespace Tgstation.Server.Api.Models
{
/// <summary>
/// Parameters for creating a <see cref="TestMerge"/>
/// </summary>
public class TestMergeParameters
{
/// <summary>
/// The number of the pull request
/// </summary>
[Required]
public int? Number { get; set; }
/// <summary>
/// The sha of the pull request revision to merge. If not specified, the latest commit shall be used (semi-unsafe)
/// </summary>
[Required]
public string PullRequestRevision { get; set; }
/// <summary>
/// Optional comment about the test
/// </summary>
public string Comment { get; set; }
}
}``` |
74a435ef-51ba-4b38-918b-5e566519cae4 | {
"language": "C#"
} | ```c#
using BittrexSharp;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Tests.IntegrationTests
{
[TestClass]
public class BittrexTests
{
[TestMethod]
public void GetMarketSummaries_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummaries(); };
action.ShouldNotThrow();
}
}
}
```
Add Tests for all public Api Methods | ```c#
using BittrexSharp;
using BittrexSharp.Domain;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Tests.IntegrationTests
{
[TestClass]
public class BittrexTests
{
#region Public Api
private const string DefaultMarketName = "BTC-ETH";
[TestMethod]
public void GetMarkets_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarkets(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetSupportedCurrencies_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetSupportedCurrencies(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetTicker_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetTicker(DefaultMarketName); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketSummaries_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummaries(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketSummary_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummary(DefaultMarketName); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetOrderBook_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetOrderBook(DefaultMarketName, OrderType.Both, 1); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketHistory_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketHistory(DefaultMarketName); };
action.ShouldNotThrow();
}
#endregion
}
}
``` |
e28d85de-1500-412b-a160-360014cc70b3 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using Toolkit.Utils;
namespace Toolkit
{
[TestClass]
public class AlertHandlerTest
{
FirefoxDriver _driver;
[TestMethod]
public void isAlertPresent()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.isAlertPresent(_driver, 3));
}
[TestMethod]
public void handleAlertTest()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.handleAlert(_driver,3));
}
[TestMethod]
public void handleAllAlertTest()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.handleAllAlerts(_driver, 2));
}
[TestCleanup]
public void TearDown()
{
_driver.Quit();
}
}
}```
Update test to ensure page is accessible after alert | ```c#
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using Toolkit.Utils;
namespace Toolkit
{
[TestClass]
public class AlertHandlerTest
{
FirefoxDriver _driver;
[TestInitialize]
public void startup()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
}
[TestMethod]
public void isAlertPresent()
{
Assert.IsTrue(AlertHandler.isAlertPresent(_driver, 3));
}
[TestMethod]
public void handleAlertTest()
{
Assert.IsTrue(AlertHandler.handleAlert(_driver,3));
}
[TestMethod]
public void handleAllAlertTest()
{
Assert.IsTrue(AlertHandler.handleAllAlerts(_driver, 2));
Assert.IsTrue(_driver.FindElement(By.Id("button")).Enabled);
}
[TestCleanup]
public void TearDown()
{
_driver.Quit();
}
}
}``` |
f71bd1d7-d122-4d9f-bbcd-afe0462f4165 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class InvalidTimeZoneException : Exception
{
public InvalidTimeZoneException()
{
}
public InvalidTimeZoneException(String message)
: base(message)
{
}
public InvalidTimeZoneException(String message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
```
Update typeforward assemblyqualifiedname for TimeZoneInfoException | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class InvalidTimeZoneException : Exception
{
public InvalidTimeZoneException()
{
}
public InvalidTimeZoneException(String message)
: base(message)
{
}
public InvalidTimeZoneException(String message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
``` |
43fbd9eb-b64c-4d75-8f68-ed97c607aa80 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NBi.Core.Etl.IntegrationService
{
class SsisEtlRunnerFactory
{
public IEtlRunner Get(IEtl etl)
{
if (string.IsNullOrEmpty(etl.Server))
return new EtlFileRunner(etl);
else if (!string.IsNullOrEmpty(etl.Catalog) || !string.IsNullOrEmpty(etl.Folder) || !string.IsNullOrEmpty(etl.Project))
return new EtlCatalogRunner(etl);
else if (string.IsNullOrEmpty(etl.UserName))
return new EtlDtsWindowsRunner(etl);
else
return new EtlDtsSqlServerRunner(etl);
}
}
}
```
Fix issue that Builder for CatalogRunner is chosen when a builder for DtsRunner should be | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NBi.Core.Etl.IntegrationService
{
class SsisEtlRunnerFactory
{
public IEtlRunner Get(IEtl etl)
{
if (string.IsNullOrEmpty(etl.Server))
return new EtlFileRunner(etl);
else if (!string.IsNullOrEmpty(etl.Catalog) && !string.IsNullOrEmpty(etl.Folder) && !string.IsNullOrEmpty(etl.Project))
return new EtlCatalogRunner(etl);
else if (string.IsNullOrEmpty(etl.UserName))
return new EtlDtsWindowsRunner(etl);
else
return new EtlDtsSqlServerRunner(etl);
}
}
}
``` |
c6d20931-88a8-4473-a2a8-a593a204ea67 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr
{
get
{
// NOTE: Currently unable to access HolographicFrame in XR SDK.
return IntPtr.Zero;
}
}
}
}
```
Update docs on XR SDK IHolographicFramePtr | ```c#
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <summary>
/// Currently unable to access HolographicFrame in XR SDK. Always returns IntPtr.Zero.
/// </summary>
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr => IntPtr.Zero;
}
}
``` |
29063455-35e3-465f-b0be-58ee3760271d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using GeoChallenger.Services.Interfaces;
using GeoChallenger.Web.Api.Models;
namespace GeoChallenger.Web.Api.Controllers
{
/// <summary>
/// Geo tags controller
/// </summary>
[RoutePrefix("api/tags")]
public class PoisController : ApiController
{
private readonly IPoisService _poisService;
private readonly IMapper _mapper;
public PoisController(IPoisService poisService, IMapper mapper)
{
if (poisService == null) {
throw new ArgumentNullException(nameof(poisService));
}
_poisService = poisService;
if (mapper == null) {
throw new ArgumentNullException(nameof(mapper));
}
_mapper = mapper;
}
/// <summary>
/// Get all stub pois
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("")]
public async Task<IList<PoiReadViewModel>> Get()
{
return _mapper.Map<IList<PoiReadViewModel>>(await _poisService.GetPoisAsync());
}
}
}
```
Refactor route url for poiController | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using GeoChallenger.Services.Interfaces;
using GeoChallenger.Web.Api.Models;
namespace GeoChallenger.Web.Api.Controllers
{
/// <summary>
/// Point of Interests controller
/// </summary>
[RoutePrefix("api/pois")]
public class PoisController : ApiController
{
private readonly IPoisService _poisService;
private readonly IMapper _mapper;
public PoisController(IPoisService poisService, IMapper mapper)
{
if (poisService == null) {
throw new ArgumentNullException(nameof(poisService));
}
_poisService = poisService;
if (mapper == null) {
throw new ArgumentNullException(nameof(mapper));
}
_mapper = mapper;
}
/// <summary>
/// Get all stub pois
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("")]
public async Task<IList<PoiReadViewModel>> Get()
{
return _mapper.Map<IList<PoiReadViewModel>>(await _poisService.GetPoisAsync());
}
}
}
``` |
6ddf87df-3ba2-45eb-8243-2dd8b97beed3 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MCloud.Linode {
internal class LinodeResponse {
public LinodeResponse ()
{
}
public string Action {
get;
set;
}
public JObject [] Data {
get;
set;
}
public LinodeError [] Errors {
get;
set;
}
public static LinodeResponse FromJson (string json)
{
JObject obj = JObject.Parse (json);
LinodeResponse response = new LinodeResponse ();
response.Action = (string) obj ["ACTION"];
List<LinodeError> errors = new List<LinodeError> ();
foreach (JObject error in obj ["ERRORARRAY"]) {
errors.Add (new LinodeError ((string) error ["ERRORMESSAGE"], (int) error ["ERRORCODE"]));
}
response.Errors = errors.ToArray ();
List<JObject> datas = new List<JObject> ();
JArray data = obj ["DATA"] as JArray;
if (data != null) {
foreach (JObject dobj in data) {
datas.Add (dobj);
}
} else
datas.Add ((JObject) obj ["DATA"]);
response.Data = datas.ToArray ();
return response;
}
}
}
```
Raise an exception if there is an error from linode | ```c#
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MCloud.Linode {
internal class LinodeResponse {
public LinodeResponse ()
{
}
public string Action {
get;
set;
}
public JObject [] Data {
get;
set;
}
public LinodeError [] Errors {
get;
set;
}
public static LinodeResponse FromJson (string json)
{
JObject obj = JObject.Parse (json);
LinodeResponse response = new LinodeResponse ();
response.Action = (string) obj ["ACTION"];
List<LinodeError> errors = new List<LinodeError> ();
foreach (JObject error in obj ["ERRORARRAY"]) {
errors.Add (new LinodeError ((string) error ["ERRORMESSAGE"], (int) error ["ERRORCODE"]));
}
response.Errors = errors.ToArray ();
if (errors.Count > 0)
throw new Exception (errors [0].Message);
List<JObject> datas = new List<JObject> ();
JArray data = obj ["DATA"] as JArray;
if (data != null) {
foreach (JObject dobj in data) {
datas.Add (dobj);
}
} else
datas.Add ((JObject) obj ["DATA"]);
response.Data = datas.ToArray ();
return response;
}
}
}
``` |
c9b51a97-f71a-4bce-b994-9f9d5bb0f0af | {
"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\" -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;
}
}
}
}
```
Scale summary video to 720p | ```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, scale=-1:720\" -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
{
FileName = "ffmpeg",
Arguments = args
}
})
{
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
}
}
}
``` |
3ee9a27c-cc40-4706-a9d2-568e781e29ce | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Synthesis")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("8.1.1.0")]
[assembly: AssemblyFileVersion("8.1.1.0")]
[assembly: AssemblyInformationalVersion("8.1.1")]
[assembly: CLSCompliant(false)]```
Bump version to 8.2. For Sitecore 8.1. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Synthesis")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("8.2.0.0")]
[assembly: AssemblyFileVersion("8.2.0.0")]
[assembly: AssemblyInformationalVersion("8.2.0")]
[assembly: CLSCompliant(false)]``` |
53edc9c3-a326-4c63-a149-747478efb53a | {
"language": "C#"
} | ```c#
namespace Linterhub.Cli.Strategy
{
using System.IO;
using System.Linq;
using Runtime;
using Engine;
using Engine.Exceptions;
using Linterhub.Engine.Extensions;
public class ActivateStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
var projectConfigFile = Path.Combine(context.Project, ".linterhub.json");
ExtConfig extConfig;
if (!File.Exists(projectConfigFile))
{
extConfig = new ExtConfig();
}
else
{
using (var fs = File.Open(projectConfigFile, FileMode.Open))
{
extConfig = fs.DeserializeAsJson<ExtConfig>();
}
}
var linter = extConfig.Linters.FirstOrDefault(x => x.Name == context.Linter);
if (linter != null)
{
linter.Active = context.Activate;
}
else
{
extConfig.Linters.Add(new ExtConfig.ExtLint
{
Name = context.Linter,
Active = context.Activate,
Command = engine.Factory.GetArguments(context.Linter)
});
}
var content = extConfig.SerializeAsJson();
File.WriteAllText(projectConfigFile, content);
return content;
}
}
}```
Set active to null (true) by default | ```c#
namespace Linterhub.Cli.Strategy
{
using System.IO;
using System.Linq;
using Runtime;
using Engine;
using Engine.Exceptions;
using Linterhub.Engine.Extensions;
public class ActivateStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
var projectConfigFile = Path.Combine(context.Project, ".linterhub.json");
ExtConfig extConfig;
if (!File.Exists(projectConfigFile))
{
extConfig = new ExtConfig();
}
else
{
using (var fs = File.Open(projectConfigFile, FileMode.Open))
{
extConfig = fs.DeserializeAsJson<ExtConfig>();
}
}
var linter = extConfig.Linters.FirstOrDefault(x => x.Name == context.Linter);
if (linter != null)
{
linter.Active = context.Activate ? null : false;
}
else
{
extConfig.Linters.Add(new ExtConfig.ExtLint
{
Name = context.Linter,
Active = context.Activate,
Command = engine.Factory.GetArguments(context.Linter)
});
}
var content = extConfig.SerializeAsJson();
File.WriteAllText(projectConfigFile, content);
return content;
}
}
}``` |
3aef63d7-a849-4335-b143-b4111d38e3de | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Framework.Graphics.Textures
{
public class RawTextureLoaderStore : ResourceStore<RawTexture>
{
private IResourceStore<byte[]> store { get; }
public RawTextureLoaderStore(IResourceStore<byte[]> store)
{
this.store = store;
(store as ResourceStore<byte[]>)?.AddExtension(@"png");
(store as ResourceStore<byte[]>)?.AddExtension(@"jpg");
}
public override async Task<RawTexture> GetAsync(string name)
{
return await Task.Run(() =>
{
try
{
using (var stream = store.GetStream(name))
{
if (stream == null) return null;
return new RawTexture(stream);
}
}
catch
{
return null;
}
});
}
}
}
```
Remove one more async-await pair | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Framework.Graphics.Textures
{
public class RawTextureLoaderStore : ResourceStore<RawTexture>
{
private IResourceStore<byte[]> store { get; }
public RawTextureLoaderStore(IResourceStore<byte[]> store)
{
this.store = store;
(store as ResourceStore<byte[]>)?.AddExtension(@"png");
(store as ResourceStore<byte[]>)?.AddExtension(@"jpg");
}
public override Task<RawTexture> GetAsync(string name)
{
try
{
using (var stream = store.GetStream(name))
{
if (stream != null)
return Task.FromResult(new RawTexture(stream));
}
}
catch
{
}
return Task.FromResult<RawTexture>(null);
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.