doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
2ede4652-f061-4b26-ab9f-7df752244086 | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Search
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Style.Width = 150;
}
[Category("General")]
[DisplayName("URL Prefix")]
public string BaseUrl { get; set; } = "http://";
[Category("General")]
[DisplayName("URL Suffix")]
public string URLSuffix { get; set; }
[Category("Behavior (Hideable)")]
[DisplayName("Hide On Search")]
public bool HideOnSearch { get; set; } = true;
}
}```
Change "Search" "Frame Padding" option default value | ```c#
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Search
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Style.Width = 150;
Style.FramePadding = new Thickness(0);
}
[Category("General")]
[DisplayName("URL Prefix")]
public string BaseUrl { get; set; } = "http://";
[Category("General")]
[DisplayName("URL Suffix")]
public string URLSuffix { get; set; }
[Category("Behavior (Hideable)")]
[DisplayName("Hide On Search")]
public bool HideOnSearch { get; set; } = true;
}
}``` |
ba545d19-0d2d-4fc1-9f6d-5939499c1611 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace wslib.Protocol.Writer
{
public class WsMessageWriter : IDisposable
{
private readonly MessageType messageType;
private readonly Action onDispose;
private readonly IWsMessageWriteStream stream;
public WsMessageWriter(MessageType messageType, Action onDispose, IWsMessageWriteStream stream)
{
this.messageType = messageType;
this.onDispose = onDispose;
this.stream = stream;
}
public Task WriteFrame(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var header = generateFrameHeader(false); // TODO: change opcode to continuation
return stream.WriteFrame(header, buffer, offset, count, cancellationToken);
}
public Task CloseMessageAsync(CancellationToken cancellationToken)
{
var header = generateFrameHeader(true);
return stream.WriteFrame(header, new byte[0], 0, 0, cancellationToken);
}
public Task WriteMessageAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var header = generateFrameHeader(true);
return stream.WriteFrame(header, buffer, offset, count, cancellationToken);
}
private WsFrameHeader generateFrameHeader(bool finFlag)
{
var opcode = messageType == MessageType.Text ? WsFrameHeader.Opcodes.TEXT : WsFrameHeader.Opcodes.BINARY;
return new WsFrameHeader { FIN = finFlag, OPCODE = opcode };
}
public void Dispose()
{
stream.Dispose();
onDispose();
}
}
}```
Set continuation opcode for non-first frames in the writer | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace wslib.Protocol.Writer
{
public class WsMessageWriter : IDisposable
{
private readonly MessageType messageType;
private readonly Action onDispose;
private readonly IWsMessageWriteStream stream;
private bool firstFrame = true;
public WsMessageWriter(MessageType messageType, Action onDispose, IWsMessageWriteStream stream)
{
this.messageType = messageType;
this.onDispose = onDispose;
this.stream = stream;
}
public Task WriteFrameAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var header = generateFrameHeader(false);
firstFrame = false;
return stream.WriteFrame(header, buffer, offset, count, cancellationToken);
}
public Task CloseMessageAsync(CancellationToken cancellationToken)
{
var header = generateFrameHeader(true);
return stream.WriteFrame(header, new byte[0], 0, 0, cancellationToken);
}
public Task WriteMessageAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var header = generateFrameHeader(true);
return stream.WriteFrame(header, buffer, offset, count, cancellationToken);
}
private WsFrameHeader generateFrameHeader(bool finFlag)
{
var opcode = firstFrame ?
(messageType == MessageType.Text ? WsFrameHeader.Opcodes.TEXT : WsFrameHeader.Opcodes.BINARY)
: WsFrameHeader.Opcodes.CONTINUATION;
return new WsFrameHeader { FIN = finFlag, OPCODE = opcode };
}
public void Dispose()
{
stream.Dispose();
onDispose();
}
}
}``` |
a2c50274-bab0-4877-aaca-826b5fd2b154 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
namespace DupImage
{
/// <summary>
/// Structure for containing image information and hash values.
/// </summary>
public class ImageStruct
{
/// <summary>
/// Construct a new ImageStruct from FileInfo.
/// </summary>
/// <param name="file">FileInfo to be used.</param>
public ImageStruct(FileInfo file)
{
if (file == null) throw new ArgumentNullException(nameof(file));
ImagePath = file.FullName;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// Construct a new ImageStruct from image path.
/// </summary>
/// <param name="pathToImage">Image location</param>
public ImageStruct(String pathToImage)
{
ImagePath = pathToImage;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// ImagePath information.
/// </summary>
public String ImagePath { get; private set; }
/// <summary>
/// Hash of the image. Uses longs instead of ulong to be CLS compliant.
/// </summary>
public long[] Hash { get; set; }
}
}
```
Use string instead of String. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
namespace DupImage
{
/// <summary>
/// Structure for containing image information and hash values.
/// </summary>
public class ImageStruct
{
/// <summary>
/// Construct a new ImageStruct from FileInfo.
/// </summary>
/// <param name="file">FileInfo to be used.</param>
public ImageStruct(FileInfo file)
{
if (file == null) throw new ArgumentNullException(nameof(file));
ImagePath = file.FullName;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// Construct a new ImageStruct from image path.
/// </summary>
/// <param name="pathToImage">Image location</param>
public ImageStruct(string pathToImage)
{
ImagePath = pathToImage;
// Init Hash
Hash = new long[1];
}
/// <summary>
/// ImagePath information.
/// </summary>
public string ImagePath { get; private set; }
/// <summary>
/// Hash of the image. Uses longs instead of ulong to be CLS compliant.
/// </summary>
public long[] Hash { get; set; }
}
}
``` |
44a85305-5f06-4088-b474-36c3902b4c8f | {
"language": "C#"
} | ```c#
#region License
// Copyright (c) 2007-2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
namespace FluentMigrator.Runner.Processors.MySql
{
public class MySqlDbFactory : ReflectionBasedDbFactory
{
private static readonly TestEntry[] _entries =
{
new TestEntry("MySql.Data", "MySql.Data.MySqlClient.MySqlClientFactory"),
new TestEntry("MySqlConnector", "MySql.Data.MySqlClient.MySqlClientFactory"),
};
[Obsolete]
public MySqlDbFactory()
: this(serviceProvider: null)
{
}
public MySqlDbFactory(IServiceProvider serviceProvider)
: base(serviceProvider, _entries)
{
}
}
}
```
Add Support for MysqlConnector 1 namespace changes | ```c#
#region License
// Copyright (c) 2007-2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
namespace FluentMigrator.Runner.Processors.MySql
{
public class MySqlDbFactory : ReflectionBasedDbFactory
{
private static readonly TestEntry[] _entries =
{
new TestEntry("MySql.Data", "MySql.Data.MySqlClient.MySqlClientFactory"),
new TestEntry("MySqlConnector", "MySql.Data.MySqlClient.MySqlClientFactory"),
new TestEntry("MySqlConnector", "MySqlConnector.MySqlConnectorFactory")
};
[Obsolete]
public MySqlDbFactory()
: this(serviceProvider: null)
{
}
public MySqlDbFactory(IServiceProvider serviceProvider)
: base(serviceProvider, _entries)
{
}
}
}
``` |
2427d961-3127-4410-b5ab-c30bad846479 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace RestImageResize.Security
{
public class HashGenerator
{
public string ComputeHash(string privateKey, int width, int height, ImageTransform transform)
{
var values = new[] { privateKey, width.ToString(), height.ToString(), transform.ToString() };
var bytes = Encoding.ASCII.GetBytes(string.Join(":", values));
var sha1 = SHA1.Create();
sha1.ComputeHash(bytes);
return BitConverter.ToString(sha1.Hash).Replace("-", "").ToLower();
}
}
}```
Use lowered transform value in hash computing | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace RestImageResize.Security
{
public class HashGenerator
{
public string ComputeHash(string privateKey, int width, int height, ImageTransform transform)
{
var values = new[] { privateKey, width.ToString(), height.ToString(), transform.ToString().ToLower() };
var bytes = Encoding.ASCII.GetBytes(string.Join(":", values));
var sha1 = SHA1.Create();
sha1.ComputeHash(bytes);
return BitConverter.ToString(sha1.Hash).Replace("-", "").ToLower();
}
}
}``` |
aa37a272-8be3-4827-9e9a-f24db2e12a4b | {
"language": "C#"
} | ```c#
using Client.Base;
using Core.Comm;
using Core.Interfaces.ServiceContracts;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 Client.Admin.Plugins
{
/// <summary>
/// Interaction logic for ComponentManagerPanel.xaml
/// </summary>
[PanelMetadata(DisplayName = "Component Manager", IconPath = "images/puzzle-piece.png")]
public partial class ComponentManagerPanel : PanelBase
{
public ComponentManagerPanel()
{
ViewModel = new ComponentManagerViewModel(this);
InitializeComponent();
}
}
}
```
Change panel icon to the cog | ```c#
using Client.Base;
using Core.Comm;
using Core.Interfaces.ServiceContracts;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 Client.Admin.Plugins
{
/// <summary>
/// Interaction logic for ComponentManagerPanel.xaml
/// </summary>
[PanelMetadata(DisplayName = "Component Manager", IconPath = "images/cog.png")]
public partial class ComponentManagerPanel : PanelBase
{
public ComponentManagerPanel()
{
ViewModel = new ComponentManagerViewModel(this);
InitializeComponent();
}
}
}
``` |
92ab72f0-8ab8-47e6-9bc5-22fb6a35c036 | {
"language": "C#"
} | ```c#
using System.Text.RegularExpressions;
namespace FormEditor
{
public static class FieldHelper
{
private static readonly Regex FormSafeNameRegex = new Regex("[ -]", RegexOptions.Compiled);
public static string FormSafeName(string name)
{
return FormSafeNameRegex.Replace(name ?? string.Empty, "_");
}
}
}```
Improve form safe name regex | ```c#
using System.Text.RegularExpressions;
namespace FormEditor
{
public static class FieldHelper
{
private static readonly Regex FormSafeNameRegex = new Regex("[^a-zA-Z0-9_]", RegexOptions.Compiled);
public static string FormSafeName(string name)
{
return FormSafeNameRegex.Replace(name ?? string.Empty, "_");
}
}
}``` |
c9e8a35c-3016-4497-9057-b8d20068c32c | {
"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=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below 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 number is invalid.");
return -1;
}
Answer = ParallelEnumerable.Range(2, max - 2)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
return 0;
}
}
}
```
Improve performance of puzzle 10 | ```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=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below 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 number is invalid.");
return -1;
}
long sum = ParallelEnumerable.Range(3, max - 3)
.Where((p) => p % 2 != 0)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
Answer = sum + 2;
return 0;
}
}
}
``` |
a8375ae7-b530-496f-a933-0c75750ff7f6 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Net;
using System.Text;
using Wox.Plugin;
namespace Wox.Infrastructure.Http
{
public class HttpRequest
{
public static string Get(string url, string encoding = "UTF8")
{
return Get(url, encoding, HttpProxy.Instance);
}
private static string Get(string url, string encoding, IHttpProxy proxy)
{
if (string.IsNullOrEmpty(url)) return string.Empty;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Timeout = 10 * 1000;
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port);
}
else
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port)
{
Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
};
}
}
try
{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{
return reader.ReadToEnd();
}
}
}
}
catch (Exception e)
{
return string.Empty;
}
return string.Empty;
}
}
}```
Fix a http request issues. | ```c#
using System;
using System.IO;
using System.Net;
using System.Text;
using Wox.Plugin;
namespace Wox.Infrastructure.Http
{
public class HttpRequest
{
public static string Get(string url, string encoding = "UTF-8")
{
return Get(url, encoding, HttpProxy.Instance);
}
private static string Get(string url, string encoding, IHttpProxy proxy)
{
if (string.IsNullOrEmpty(url)) return string.Empty;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Timeout = 10 * 1000;
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port);
}
else
{
request.Proxy = new WebProxy(proxy.Server, proxy.Port)
{
Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
};
}
}
try
{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
{
return reader.ReadToEnd();
}
}
}
}
catch (Exception e)
{
return string.Empty;
}
return string.Empty;
}
}
}``` |
fa7175ff-8bc5-4e85-a0ef-753433b61f04 | {
"language": "C#"
} | ```c#
@model OrderModifyModel
@{
var submitMap = new Dictionary<string, string> {{"Request", "Create"}, {"Edit", "Save"}, {"Copy", "Save"}};
var submitText = submitMap[ViewBag.Title];
var submitTitle = ViewBag.Title == "Copy" ? "Save this order which was duplicated from an existing order" : string.Empty;
}
<section id="order-submit-section">
<div class="section-contents">
@if (!string.IsNullOrWhiteSpace(Model.Workgroup.Disclaimer))
{
<div class="section-text">
<p><strong>Disclaimer: </strong>@Model.Workgroup.Disclaimer</p>
</div>
}
<ul>
<li><div class="editor-label"> </div>
<div class="editor-field">
<input type="submit" class="button order-submit" value="@submitText" title="@submitTitle"/>
|
@if (submitText == "Create")
{
<input type="button" class="button" value="Save For Later" id="save-btn"/> <text>|</text>
}
@Html.ActionLink("Cancel", "Landing", "Home", null, new {id="order-cancel"})
</div>
</li>
</ul>
</div>
```
Make consistent and add a comment for clarification | ```c#
@model OrderModifyModel
@{
var submitMap = new Dictionary<string, string> {{"Request", "Create"}, {"Edit", "Save"}, {"Copy", "Save"}};
var submitText = submitMap[ViewBag.Title];
var submitTitle = ViewBag.Title == "Copy" ? "Save this order which was duplicated from an existing order" : string.Empty;
}
<section id="order-submit-section">
<div class="section-contents">
@if (!string.IsNullOrWhiteSpace(Model.Workgroup.Disclaimer))
{
<div class="section-text">
<p><strong>Disclaimer: </strong>@Model.Workgroup.Disclaimer</p>
</div>
}
<ul>
<li><div class="editor-label"> </div>
<div class="editor-field">
<input type="submit" class="button order-submit" value="@submitText" title="@submitTitle"/>
|
@if (submitText == "Create")
{
<input type="button" class="button" value="Save For Later" id="save-btn"/> <text>|</text>
}
@Html.ActionLink("Cancel", "Landing", "Home", new {}, new {id="order-cancel"}) @*This id is an element so the local storage gets cleared out. It is not a route value.*@
</div>
</li>
</ul>
</div>
``` |
8671a75b-0742-4264-9656-f4da33c000a7 | {
"language": "C#"
} | ```c#
using System;
using System.Web.Mvc;
namespace Website.Security
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EnforceHttpsAttribute : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if(filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext));
}
if(filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
if(string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if(filterContext.HttpContext.Request.IsLocal)
{
return;
}
HandleNonHttpsRequest(filterContext);
}
}
}```
Remove nameof operator because it caused a build error in AppHarbor | ```c#
using System;
using System.Web.Mvc;
namespace Website.Security
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EnforceHttpsAttribute : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if(filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if(filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
if(string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if(filterContext.HttpContext.Request.IsLocal)
{
return;
}
HandleNonHttpsRequest(filterContext);
}
}
}``` |
6547b740-b70f-4916-84a4-2839452912a9 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using CacheSleeve.Tests.TestObjects;
namespace CacheSleeve.Tests
{
public static class TestSettings
{
public static string RedisHost = "localhost";
public static int RedisPort = 6379;
public static string RedisPassword = null;
public static int RedisDb = 0;
public static string KeyPrefix = "cs.";
// don't mess with George.. you'll break a lot of tests
public static Monkey George = new Monkey("George") { Bananas = new List<Banana> { new Banana(4, "yellow") }};
}
}```
Change test settings default Redis Db | ```c#
using System.Collections.Generic;
using CacheSleeve.Tests.TestObjects;
namespace CacheSleeve.Tests
{
public static class TestSettings
{
public static string RedisHost = "localhost";
public static int RedisPort = 6379;
public static string RedisPassword = null;
public static int RedisDb = 5;
public static string KeyPrefix = "cs.";
// don't mess with George.. you'll break a lot of tests
public static Monkey George = new Monkey("George") { Bananas = new List<Banana> { new Banana(4, "yellow") }};
}
}``` |
c2b7f01c-fe36-4195-a2bc-184a71af4858 | {
"language": "C#"
} | ```c#
namespace SFA.DAS.EAS.Domain.Configuration
{
public class HmrcConfiguration
{
public string BaseUrl { get; set; }
public string ClientId { get; set; }
public string Scope { get; set; }
public string ClientSecret { get; set; }
public string ServerToken { get; set; }
public string OgdSecret { get; set; }
public string OgdClientId { get; set; }
}
}```
Add configuration options for HMRC to use MI Feed | ```c#
namespace SFA.DAS.EAS.Domain.Configuration
{
public class HmrcConfiguration
{
public string BaseUrl { get; set; }
public string ClientId { get; set; }
public string Scope { get; set; }
public string ClientSecret { get; set; }
public string ServerToken { get; set; }
public string OgdSecret { get; set; }
public string OgdClientId { get; set; }
public string AzureClientId { get; set; }
public string AzureAppKey { get; set; }
public string AzureResourceId { get; set; }
public string AzureTenant { get; set; }
public bool UseHiDataFeed { get; set; }
}
}``` |
e2e27680-d453-4001-a083-7bf8d73decb8 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Contains well known implementations of <see cref="FixAllProvider"/>.
/// </summary>
public static class WellKnownFixAllProviders
{
/// <summary>
/// Default batch fix all provider.
/// This provider batches all the individual diagnostic fixes across the scope of fix all action,
/// computes fixes in parallel and then merges all the non-conflicting fixes into a single fix all code action.
/// This fixer supports fixes for the following fix all scopes:
/// <see cref="FixAllScope.Document"/>, <see cref="FixAllScope.Project"/> and <see cref="FixAllScope.Solution"/>.
/// </summary>
/// <remarks>
/// The batch fix all provider only batches operations (i.e. <see cref="CodeActionOperation"/>) of type
/// <see cref="ApplyChangesOperation"/> present within the individual diagnostic fixes. Other types of
/// operations present within these fixes are ignored.
/// </remarks>
public static FixAllProvider BatchFixer => BatchFixAllProvider.Instance;
/// <summary>
/// Default batch fix all provider for simplification fixers which only add Simplifier annotations to documents.
/// This provider batches all the simplifier annotation actions within a document into a single code action,
/// instead of creating separate code actions for each added annotation.
/// This fixer supports fixes for the following fix all scopes:
/// <see cref="FixAllScope.Document"/>, <see cref="FixAllScope.Project"/> and <see cref="FixAllScope.Solution"/>.
/// </summary>
internal static FixAllProvider BatchSimplificationFixer => BatchSimplificationFixAllProvider.Instance;
}
}
```
Remove static that is unused. | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Contains well known implementations of <see cref="FixAllProvider"/>.
/// </summary>
public static class WellKnownFixAllProviders
{
/// <summary>
/// Default batch fix all provider.
/// This provider batches all the individual diagnostic fixes across the scope of fix all action,
/// computes fixes in parallel and then merges all the non-conflicting fixes into a single fix all code action.
/// This fixer supports fixes for the following fix all scopes:
/// <see cref="FixAllScope.Document"/>, <see cref="FixAllScope.Project"/> and <see cref="FixAllScope.Solution"/>.
/// </summary>
/// <remarks>
/// The batch fix all provider only batches operations (i.e. <see cref="CodeActionOperation"/>) of type
/// <see cref="ApplyChangesOperation"/> present within the individual diagnostic fixes. Other types of
/// operations present within these fixes are ignored.
/// </remarks>
public static FixAllProvider BatchFixer => BatchFixAllProvider.Instance;
}
}
``` |
bfdcd81f-5836-45ac-9a7e-3b0c8be9ff6e | {
"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 System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Screens.Ranking.Statistics
{
/// <summary>
/// Displays the unstable rate statistic for a given play.
/// </summary>
public class UnstableRate : SimpleStatisticItem<double>
{
/// <summary>
/// Creates and computes an <see cref="UnstableRate"/> statistic.
/// </summary>
/// <param name="hitEvents">Sequence of <see cref="HitEvent"/>s to calculate the unstable rate based on.</param>
public UnstableRate(IEnumerable<HitEvent> hitEvents)
: base("Unstable Rate")
{
var timeOffsets = hitEvents.Select(ev => ev.TimeOffset).ToArray();
Value = 10 * standardDeviation(timeOffsets);
}
private static double standardDeviation(double[] timeOffsets)
{
if (timeOffsets.Length == 0)
return double.NaN;
var mean = timeOffsets.Average();
var squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum();
return Math.Sqrt(squares / timeOffsets.Length);
}
protected override string DisplayValue(double value) => double.IsNaN(value) ? "(not available)" : value.ToString("N2");
}
}
```
Exclude misses and empty window hits from UR calculation | ```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 System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Screens.Ranking.Statistics
{
/// <summary>
/// Displays the unstable rate statistic for a given play.
/// </summary>
public class UnstableRate : SimpleStatisticItem<double>
{
/// <summary>
/// Creates and computes an <see cref="UnstableRate"/> statistic.
/// </summary>
/// <param name="hitEvents">Sequence of <see cref="HitEvent"/>s to calculate the unstable rate based on.</param>
public UnstableRate(IEnumerable<HitEvent> hitEvents)
: base("Unstable Rate")
{
var timeOffsets = hitEvents.Where(e => !(e.HitObject.HitWindows is HitWindows.EmptyHitWindows) && e.Result != HitResult.Miss)
.Select(ev => ev.TimeOffset).ToArray();
Value = 10 * standardDeviation(timeOffsets);
}
private static double standardDeviation(double[] timeOffsets)
{
if (timeOffsets.Length == 0)
return double.NaN;
var mean = timeOffsets.Average();
var squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum();
return Math.Sqrt(squares / timeOffsets.Length);
}
protected override string DisplayValue(double value) => double.IsNaN(value) ? "(not available)" : value.ToString("N2");
}
}
``` |
4dcca59b-1696-40c9-87b8-0005fc2dfab2 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
veh.removePlayer(seat, point, angle, true);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
}```
Add group support for NoVehiclesUsage | ```c#
using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
public override bool SupportsGroups => true;
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var group = Region.GetGroup(player);
if(!GetValueSafe(group))
continue;
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
veh.removePlayer(seat, point, angle, true);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
}``` |
8310c7eb-cabb-450a-922d-9364fe27df15 | {
"language": "C#"
} | ```c#
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Connection.Stream.Connection
{
public class StreamInvokerProxy : IStreamInvokerProxy
{
private readonly IHubProxy _hubProxy;
internal StreamInvokerProxy(IHubProxy hubProxy)
{
_hubProxy = hubProxy;
}
public Task Invoke(string method, params object[] args)
{
return _hubProxy.Invoke(method, args);
}
public Task<T> Invoke<T>(string method, params object[] args)
{
return _hubProxy.Invoke<T>(method, args);
}
}
}```
Convert invoker proxy over to be internal | ```c#
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Connection.Stream.Connection
{
internal class StreamInvokerProxy : IStreamInvokerProxy
{
private readonly IHubProxy _hubProxy;
internal StreamInvokerProxy(IHubProxy hubProxy)
{
_hubProxy = hubProxy;
}
public Task Invoke(string method, params object[] args)
{
return _hubProxy.Invoke(method, args);
}
public Task<T> Invoke<T>(string method, params object[] args)
{
return _hubProxy.Invoke<T>(method, args);
}
}
}``` |
b82ef9b7-7ddb-48bd-ad72-d47c8961fab3 | {
"language": "C#"
} | ```c#
using System;
using osu.Game.Beatmaps;
using SQLite;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey]
public int ID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public GameMode Mode { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
}
}```
Use PlayMode instead of GameMode | ```c#
using System;
using osu.Game.GameModes.Play;
using SQLite;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey]
public int ID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public PlayMode Mode { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
}
}``` |
41cb795d-2b80-4e57-854e-b1d3972201ca | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editing
{
internal class GenerationOptions
{
public static readonly PerLanguageOption<bool> PlaceSystemNamespaceFirst = new PerLanguageOption<bool>(nameof(GenerationOptions),
nameof(PlaceSystemNamespaceFirst), defaultValue: true,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"),
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")});
public static readonly PerLanguageOption<bool> SeparateImportDirectiveGroups = new PerLanguageOption<bool>(
nameof(GenerationOptions), nameof(SeparateImportDirectiveGroups), defaultValue: false,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_seperate_import_directive_groups"),
new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")});
}
}
```
Fix spelling of .editorconfig option | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editing
{
internal class GenerationOptions
{
public static readonly PerLanguageOption<bool> PlaceSystemNamespaceFirst = new PerLanguageOption<bool>(nameof(GenerationOptions),
nameof(PlaceSystemNamespaceFirst), defaultValue: true,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"),
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")});
public static readonly PerLanguageOption<bool> SeparateImportDirectiveGroups = new PerLanguageOption<bool>(
nameof(GenerationOptions), nameof(SeparateImportDirectiveGroups), defaultValue: false,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_separate_import_directive_groups"),
new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")});
}
}
``` |
872732e8-2cc0-4e34-abb2-5fd145f2aae1 | {
"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.Collections.Generic;
using osu.Framework.Graphics.OpenGL;
using System;
namespace osu.Framework.Graphics.Shaders
{
public class Uniform<T> : IUniformWithValue<T>
where T : struct, IEquatable<T>
{
public Shader Owner { get; }
public string Name { get; }
public int Location { get; }
public bool HasChanged { get; private set; } = true;
private T val;
public T Value
{
get => val;
set
{
if (value.Equals(val))
return;
val = value;
HasChanged = true;
if (Owner.IsBound)
Update();
}
}
public Uniform(Shader owner, string name, int uniformLocation)
{
Owner = owner;
Name = name;
Location = uniformLocation;
}
public void UpdateValue(ref T newValue)
{
if (newValue.Equals(val))
return;
val= newValue;
HasChanged = true;
if (Owner.IsBound)
Update();
}
public void Update()
{
if (!HasChanged) return;
GLWrapper.SetUniform(this);
HasChanged = false;
}
ref T IUniformWithValue<T>.GetValueByRef() => ref val;
T IUniformWithValue<T>.GetValue() => val;
}
}
```
Fix formatting and remove unnecessary using | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.OpenGL;
using System;
namespace osu.Framework.Graphics.Shaders
{
public class Uniform<T> : IUniformWithValue<T>
where T : struct, IEquatable<T>
{
public Shader Owner { get; }
public string Name { get; }
public int Location { get; }
public bool HasChanged { get; private set; } = true;
private T val;
public T Value
{
get => val;
set
{
if (value.Equals(val))
return;
val = value;
HasChanged = true;
if (Owner.IsBound)
Update();
}
}
public Uniform(Shader owner, string name, int uniformLocation)
{
Owner = owner;
Name = name;
Location = uniformLocation;
}
public void UpdateValue(ref T newValue)
{
if (newValue.Equals(val))
return;
val = newValue;
HasChanged = true;
if (Owner.IsBound)
Update();
}
public void Update()
{
if (!HasChanged) return;
GLWrapper.SetUniform(this);
HasChanged = false;
}
ref T IUniformWithValue<T>.GetValueByRef() => ref val;
T IUniformWithValue<T>.GetValue() => val;
}
}
``` |
40a5ebd1-1fac-4edd-837f-a1ebe46eb151 | {
"language": "C#"
} | ```c#
using System.Windows;
using System.Windows.Controls;
using FlaUInspect.ViewModels;
namespace FlaUInspect.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MainViewModel _vm;
public MainWindow()
{
InitializeComponent();
Height = 550;
Width = 700;
Loaded += MainWindow_Loaded;
_vm = new MainViewModel();
DataContext = _vm;
}
private void MainWindow_Loaded(object sender, System.EventArgs e)
{
if (!_vm.IsInitialized)
{
var dlg = new ChooseVersionWindow { Owner = this };
if (dlg.ShowDialog() != true)
{
Close();
}
_vm.Initialize(dlg.SelectedAutomationType);
Loaded -= MainWindow_Loaded;
}
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void TreeViewSelectedHandler(object sender, RoutedEventArgs e)
{
var item = sender as TreeViewItem;
if (item != null)
{
item.BringIntoView();
e.Handled = true;
}
}
}
}
```
Append version number to title | ```c#
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using FlaUInspect.ViewModels;
namespace FlaUInspect.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MainViewModel _vm;
public MainWindow()
{
InitializeComponent();
AppendVersionToTitle();
Height = 550;
Width = 700;
Loaded += MainWindow_Loaded;
_vm = new MainViewModel();
DataContext = _vm;
}
private void AppendVersionToTitle()
{
var attr = Assembly.GetEntryAssembly().GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
if (attr != null)
{
Title += " v" + attr.InformationalVersion;
}
}
private void MainWindow_Loaded(object sender, System.EventArgs e)
{
if (!_vm.IsInitialized)
{
var dlg = new ChooseVersionWindow { Owner = this };
if (dlg.ShowDialog() != true)
{
Close();
}
_vm.Initialize(dlg.SelectedAutomationType);
Loaded -= MainWindow_Loaded;
}
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void TreeViewSelectedHandler(object sender, RoutedEventArgs e)
{
var item = sender as TreeViewItem;
if (item != null)
{
item.BringIntoView();
e.Handled = true;
}
}
}
}
``` |
e05bf85f-cafd-4109-a96f-95330741555d | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable,
KeyboardStep = 0.1f
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable;
multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
```
Fix legacy control point precision having an adverse effect on the editor | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable,
KeyboardStep = 0.1f
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
var selectedPointBindable = point.NewValue.SpeedMultiplierBindable;
// there may be legacy control points, which contain infinite precision for compatibility reasons (see LegacyDifficultyControlPoint).
// generally that level of precision could only be set by externally editing the .osu file, so at the point
// a user is looking to update this within the editor it should be safe to obliterate this additional precision.
double expectedPrecision = new DifficultyControlPoint().SpeedMultiplierBindable.Precision;
if (selectedPointBindable.Precision < expectedPrecision)
selectedPointBindable.Precision = expectedPrecision;
multiplierSlider.Current = selectedPointBindable;
multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
``` |
7cb29c05-9c37-40cb-8421-5c32ea2fa4e1 | {
"language": "C#"
} | ```c#
using System.IO;
using System.IO.Compression;
namespace Ensconce.Console
{
internal static class Backup
{
internal static void DoBackup()
{
if (File.Exists(Arguments.BackupDestination) && Arguments.BackupOverwrite)
{
File.Delete(Arguments.BackupDestination);
}
ZipFile.CreateFromDirectory(Arguments.BackupSource, Arguments.BackupDestination, CompressionLevel.Optimal, false);
}
}
}
```
Add tag replacement on backup paths | ```c#
using System.IO;
using System.IO.Compression;
namespace Ensconce.Console
{
internal static class Backup
{
internal static void DoBackup()
{
var backupSource = Arguments.BackupSource.Render();
var backupDestination = Arguments.BackupDestination.Render();
if (File.Exists(backupDestination) && Arguments.BackupOverwrite)
{
File.Delete(backupDestination);
}
ZipFile.CreateFromDirectory(backupSource, backupDestination, CompressionLevel.Optimal, false);
}
}
}
``` |
23eb3c35-ba7d-4780-980b-64d74db515ce | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2019")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
```
Increment projects copyright year to 2020 | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2020")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
``` |
59e7553b-a957-4995-a11f-7754344b90c3 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PluginTest
{
public class TestPlugin
{
}
}
```
Add a stronger dependency on UnityEngine for testing. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace PluginTest
{
public class TestPlugin : MonoBehaviour
{
private void Start()
{
Debug.Log("Start called");
}
}
}
``` |
0a830f68-f310-45db-af4b-458619d84281 | {
"language": "C#"
} | ```c#
using TechSmith.Hyde.Common.DataAnnotations;
namespace TechSmith.Hyde.IntegrationTest
{
/// <summary>
/// Class with decorated partition and row key properties, for testing purposes.
/// </summary>
class DecoratedItem
{
[PartitionKey]
public string Id
{
get;
set;
}
[RowKey]
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
class DecoratedItemEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity
{
public string Id
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
}
```
Update test entity with attribute to denote partition/row key | ```c#
using System.Data.Services.Common;
using TechSmith.Hyde.Common.DataAnnotations;
namespace TechSmith.Hyde.IntegrationTest
{
/// <summary>
/// Class with decorated partition and row key properties, for testing purposes.
/// </summary>
class DecoratedItem
{
[PartitionKey]
public string Id
{
get;
set;
}
[RowKey]
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
[DataServiceKey( "PartitionKey", "RowKey")]
class DecoratedItemEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity
{
public string Id
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
}
``` |
3000068a-5e47-4ad6-8132-2b82f780f956 | {
"language": "C#"
} | ```c#
@{
string baseEditUrl = Context.String(DocsKeys.BaseEditUrl);
FilePath editFilePath = Model.FilePath(Wyam.Web.WebKeys.EditFilePath);
if(!string.IsNullOrWhiteSpace(baseEditUrl) && editFilePath != null)
{
string editUrl = baseEditUrl + editFilePath.FullPath;
<div><p><a href="@editUrl"><i class="fa fa-pencil-square" aria-hidden="true"></i> Edit Content</a></p></div>
}
<div id="infobar-headings"></div>
}```
Add handling for missing / | ```c#
@{
string baseEditUrl = Context.String(DocsKeys.BaseEditUrl);
FilePath editFilePath = Model.FilePath(Wyam.Web.WebKeys.EditFilePath);
if(!string.IsNullOrWhiteSpace(baseEditUrl) && editFilePath != null)
{
if (!baseEditUrl[baseEditUrl.Length - 1].equals('/'))
{
baseEditUrl += "/";
}
string editUrl = baseEditUrl + editFilePath.FullPath;
<div><p><a href="@editUrl"><i class="fa fa-pencil-square" aria-hidden="true"></i> Edit Content</a></p></div>
}
<div id="infobar-headings"></div>
}
``` |
e9f3c14e-edfd-434f-b09a-b93274deb23b | {
"language": "C#"
} | ```c#
using System;
using System.Net;
namespace a
{
class Program
{
//Code is dirty, who cares, it's C#.
static void Main(string[] args)
{
//IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());
//foreach (IPAddress curAdd in heserver.AddressList)
//{
Server server = new Server(IPAddress.Loopback, 5000);
server.Start();
Console.WriteLine("Press q to exit");
while (true)
{
try
{
char c = (char)Console.ReadLine()[0];
if (c == 'q')
{
server.Stop();
break;
}
}
catch (Exception)
{
//who cares ?
}
}
//}
}
}
}
```
Fix problems with launching and exiting the app | ```c#
using System;
using System.Net;
namespace a
{
class Program
{
//Code is dirty, who cares, it's C#.
static void Main(string[] args)
{
Server server = new Server(IPAddress.Any, 5000);
server.Start();
Console.WriteLine("Press q to exit");
while (true)
{
try
{
if (Console.ReadKey().KeyChar == 'q')
{
server.Stop();
return;
}
}
catch (Exception)
{
//who cares ?
}
}
}
}
}
``` |
ca489ac6-f9a9-4665-b8ff-7ea56ec30473 | {
"language": "C#"
} | ```c#
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace BobTheBuilder.Tests
{
public class BuildFacts
{
[Fact]
public void CreateADynamicInstanceOfTheRequestedType()
{
var sut = A.BuilderFor<SampleType>();
var result = sut.Build();
Assert.IsAssignableFrom<dynamic>(result);
Assert.IsAssignableFrom<SampleType>(result);
}
[Theory, AutoData]
public void SetStringStateByName(string expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithStringProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.StringProperty);
}
[Theory, AutoData]
public void SetIntStateByName(int expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithIntProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.IntProperty);
}
}
}
```
Add unit test for complex types. | ```c#
using System;
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace BobTheBuilder.Tests
{
public class BuildFacts
{
[Fact]
public void CreateADynamicInstanceOfTheRequestedType()
{
var sut = A.BuilderFor<SampleType>();
var result = sut.Build();
Assert.IsAssignableFrom<dynamic>(result);
Assert.IsAssignableFrom<SampleType>(result);
}
[Theory, AutoData]
public void SetStringStateByName(string expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithStringProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.StringProperty);
}
[Theory, AutoData]
public void SetIntStateByName(int expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithIntProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.IntProperty);
}
[Theory, AutoData]
public void SetComplexStateByName(Exception expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithComplexProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.ComplexProperty);
}
}
}
``` |
ce303cff-e664-4e8e-85e1-d8d01efd090e | {
"language": "C#"
} | ```c#
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.Fonts.Unicode;
namespace SixLabors.Fonts.Tables.AdvancedTypographic.Shapers
{
internal static class ShaperFactory
{
/// <summary>
/// Creates a Shaper based on the given script language.
/// </summary>
/// <param name="script">The script language.</param>
/// <returns>A shaper for the given script.</returns>
public static BaseShaper Create(Script script)
{
switch (script)
{
case Script.Arabic:
return new ArabicShaper();
default:
return new DefaultShaper();
}
}
}
}
```
Add additional script languages which use the arabic shaper | ```c#
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.Fonts.Unicode;
namespace SixLabors.Fonts.Tables.AdvancedTypographic.Shapers
{
internal static class ShaperFactory
{
/// <summary>
/// Creates a Shaper based on the given script language.
/// </summary>
/// <param name="script">The script language.</param>
/// <returns>A shaper for the given script.</returns>
public static BaseShaper Create(Script script)
{
switch (script)
{
case Script.Arabic:
case Script.Mongolian:
case Script.Syriac:
case Script.Nko:
case Script.PhagsPa:
case Script.Mandaic:
case Script.Manichaean:
case Script.PsalterPahlavi:
return new ArabicShaper();
default:
return new DefaultShaper();
}
}
}
}
``` |
082795c0-a818-4e47-8a60-63847d3e2101 | {
"language": "C#"
} | ```c#
using Lbookshelf.Business;
using Microsoft.Expression.Interactivity.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Configuration;
using Lbookshelf.Utils;
using Lbookshelf.Models;
using Lapps.Utils;
using Lapps.Utils.Collections;
namespace Lbookshelf.ViewModels
{
public class SettingsFileSystemViewModel : ObservableObject
{
public SettingsFileSystemViewModel()
{
CleanCommand = new ActionCommand(
() =>
{
var used = BookManager.Instance.Books.Select(b => Path.Combine(Environment.CurrentDirectory, b.Thumbnail));
var cached = Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "Images"));
var disused = cached.Except(used).ToArray();
if (disused.Length > 0)
{
disused.ForEach(p => File.Delete(p));
DialogService.ShowDialog(String.Format("{0} disused thumbnails were removed.", disused.Length));
}
else
{
DialogService.ShowDialog("All thumbnails are in use.");
}
});
}
public string RootDirectory
{
get { return StorageManager.Instance.RootDirectory; }
set
{
StorageManager.Instance.RootDirectory = value;
SettingManager.Default.RootDirectory = StorageManager.Instance.RootDirectory;
SettingManager.Default.Save();
}
}
public ICommand CleanCommand { get; private set; }
}
}
```
Fix a bug: When clean up disused images, the DefaultThumbnail.jpg could be removed by mistake if all books have their own images. | ```c#
using Lbookshelf.Business;
using Microsoft.Expression.Interactivity.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Configuration;
using Lbookshelf.Utils;
using Lbookshelf.Models;
using Lapps.Utils;
using Lapps.Utils.Collections;
namespace Lbookshelf.ViewModels
{
public class SettingsFileSystemViewModel : ObservableObject
{
public SettingsFileSystemViewModel()
{
CleanCommand = new ActionCommand(
() =>
{
var used = BookManager.Instance.Books.Select(b => Path.Combine(Environment.CurrentDirectory, b.Thumbnail));
var cached = Directory
.GetFiles(Path.Combine(Environment.CurrentDirectory, "Images"))
.Where(p => Path.GetFileName(p) != "DefaultThumbnail.jpg");
var disused = cached.Except(used).ToArray();
if (disused.Length > 0)
{
disused.ForEach(p => File.Delete(p));
DialogService.ShowDialog(String.Format("{0} disused thumbnails were removed.", disused.Length));
}
else
{
DialogService.ShowDialog("All thumbnails are in use.");
}
});
}
public string RootDirectory
{
get { return StorageManager.Instance.RootDirectory; }
set
{
StorageManager.Instance.RootDirectory = value;
SettingManager.Default.RootDirectory = StorageManager.Instance.RootDirectory;
SettingManager.Default.Save();
}
}
public ICommand CleanCommand { get; private set; }
}
}
``` |
6d55f26d-f543-4b9c-aaee-944339fd36c8 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
```
Create server side API for single multiple answer question | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
``` |
1798baf2-cc7f-4e55-a56b-4c8e497583c4 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
```
Update server side API for single multiple answer question | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
``` |
6f6bcc21-3dc1-4a17-9054-f404b7ef2ff1 | {
"language": "C#"
} | ```c#
namespace MailTrace.Host.Selfhost
{
using System;
using MailTrace.Data.Postgresql;
using MailTrace.Host;
using MailTrace.Host.Data;
using Microsoft.Owin.Hosting;
internal static class Program
{
private static void Main(string[] args)
{
const string baseAddress = "http://localhost:9900/";
Startup.PostConfigureKernel += kernel => { kernel.Bind<TraceContext>().To<PostgresqlTraceContext>(); };
Console.WriteLine("Running Migration...");
var context = new PostgresqlTraceContext();
context.Migrate();
using (WebApp.Start<Startup>(baseAddress))
{
Console.WriteLine("Ready.");
Console.ReadLine();
}
}
}
}```
Allow bind interface to be customized. | ```c#
namespace MailTrace.Host.Selfhost
{
using System;
using System.Linq;
using MailTrace.Data.Postgresql;
using MailTrace.Host.Data;
using Microsoft.Owin.Hosting;
internal static class Program
{
private static void Main(string[] args)
{
var baseAddress = args.FirstOrDefault() ?? "http://localhost:9900";
Startup.PostConfigureKernel += kernel => { kernel.Bind<TraceContext>().To<PostgresqlTraceContext>(); };
Console.WriteLine("Running Migration...");
var context = new PostgresqlTraceContext();
context.Migrate();
using (WebApp.Start<Startup>(baseAddress))
{
Console.WriteLine("Ready.");
Console.ReadLine();
}
}
}
}``` |
e4a97e4f-0d6b-4104-8764-feb44ee990e0 | {
"language": "C#"
} | ```c#
namespace Avalonia.Platform
{
public enum AlphaFormat
{
Premul,
Unpremul,
Opaque
}
}
```
Add documentation for alpha format. | ```c#
namespace Avalonia.Platform
{
/// <summary>
/// Describes how to interpret the alpha component of a pixel.
/// </summary>
public enum AlphaFormat
{
/// <summary>
/// All pixels have their alpha premultiplied in their color components.
/// </summary>
Premul,
/// <summary>
/// All pixels have their color components stored without any regard to the alpha. e.g. this is the default configuration for PNG images.
/// </summary>
Unpremul,
/// <summary>
/// All pixels are stored as opaque.
/// </summary>
Opaque
}
}
``` |
c54ad504-e746-461c-a70d-235ba4376ed6 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Post.Users.CustomListItems;
using TraktApiSharp.Objects.Post.Users.CustomListItems.Responses;
[TestClass]
public class TraktUserCustomListItemsRemoveRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsNotAbstract()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSealed()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSubclassOfATraktUsersPostByIdRequest()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSubclassOf(typeof(ATraktUsersPostByIdRequest<TraktUserCustomListItemsRemovePostResponse, TraktUserCustomListItemsPost>)).Should().BeTrue();
}
}
}
```
Add test for authorization requirement in TraktUserCustomListItemsRemoveRequest | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Post.Users.CustomListItems;
using TraktApiSharp.Objects.Post.Users.CustomListItems.Responses;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserCustomListItemsRemoveRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsNotAbstract()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSealed()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSubclassOfATraktUsersPostByIdRequest()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSubclassOf(typeof(ATraktUsersPostByIdRequest<TraktUserCustomListItemsRemovePostResponse, TraktUserCustomListItemsPost>)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestHasAuthorizationRequired()
{
var request = new TraktUserCustomListItemsRemoveRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
``` |
b6655363-9de7-4627-8b92-725b2b94e46a | {
"language": "C#"
} | ```c#
using System.Web.Mvc;
using Amry.Gst.Properties;
using WebMarkupMin.Mvc.ActionFilters;
namespace Amry.Gst.Web.Controllers
{
public class HomeController : Controller
{
const int OneWeek = 604800;
const int OneYear = 31536000;
[Route, MinifyHtml, OutputCache(Duration = OneWeek)]
public ActionResult Index()
{
return View();
}
[Route("about"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult About()
{
return View();
}
[Route("api"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult Api()
{
return View();
}
[Route("ver")]
public ActionResult Version()
{
return Content("Version: " + AssemblyInfoConstants.Version, "text/plain");
}
}
}```
Revert "Change controller action to debug Kudu issue .." | ```c#
using System.Web.Mvc;
using Amry.Gst.Properties;
using WebMarkupMin.Mvc.ActionFilters;
namespace Amry.Gst.Web.Controllers
{
public class HomeController : Controller
{
const int OneWeek = 604800;
const int OneYear = 31536000;
[Route, MinifyHtml, OutputCache(Duration = OneWeek)]
public ActionResult Index()
{
return View();
}
[Route("about"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult About()
{
return View();
}
[Route("api"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult Api()
{
return View();
}
[Route("ver")]
public ActionResult Version()
{
return Content(AssemblyInfoConstants.Version, "text/plain");
}
}
}``` |
b07006d1-d707-49b5-bed9-a4ff8ef180c8 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CefSharp;
namespace TweetDuck.Core.Handling.General{
sealed class FileDialogHandler : IDialogHandler{
public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback){
CefFileDialogMode dialogType = mode & CefFileDialogMode.TypeMask;
if (dialogType == CefFileDialogMode.Open || dialogType == CefFileDialogMode.OpenMultiple){
string allFilters = string.Join(";", acceptFilters.Select(filter => "*"+filter));
using(OpenFileDialog dialog = new OpenFileDialog{
AutoUpgradeEnabled = true,
DereferenceLinks = true,
Multiselect = dialogType == CefFileDialogMode.OpenMultiple,
Title = "Open Files",
Filter = $"All Supported Formats ({allFilters})|{allFilters}|All Files (*.*)|*.*"
}){
if (dialog.ShowDialog() == DialogResult.OK){
callback.Continue(acceptFilters.FindIndex(filter => filter == Path.GetExtension(dialog.FileName)), dialog.FileNames.ToList());
}
else{
callback.Cancel();
}
callback.Dispose();
}
return true;
}
else{
callback.Dispose();
return false;
}
}
}
}
```
Fix uploading files with uppercase extensions | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CefSharp;
namespace TweetDuck.Core.Handling.General{
sealed class FileDialogHandler : IDialogHandler{
public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback){
CefFileDialogMode dialogType = mode & CefFileDialogMode.TypeMask;
if (dialogType == CefFileDialogMode.Open || dialogType == CefFileDialogMode.OpenMultiple){
string allFilters = string.Join(";", acceptFilters.Select(filter => "*"+filter));
using(OpenFileDialog dialog = new OpenFileDialog{
AutoUpgradeEnabled = true,
DereferenceLinks = true,
Multiselect = dialogType == CefFileDialogMode.OpenMultiple,
Title = "Open Files",
Filter = $"All Supported Formats ({allFilters})|{allFilters}|All Files (*.*)|*.*"
}){
if (dialog.ShowDialog() == DialogResult.OK){
string ext = Path.GetExtension(dialog.FileName);
callback.Continue(acceptFilters.FindIndex(filter => filter.Equals(ext, StringComparison.OrdinalIgnoreCase)), dialog.FileNames.ToList());
}
else{
callback.Cancel();
}
callback.Dispose();
}
return true;
}
else{
callback.Dispose();
return false;
}
}
}
}
``` |
3f30bb74-5f57-4e45-927f-f47af7c13f55 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
namespace Bridge.Translator
{
public partial class Translator
{
protected static readonly char ps = System.IO.Path.DirectorySeparatorChar;
protected virtual string GetBuilderPath()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return Environment.GetEnvironmentVariable("windir") + ps + "Microsoft.NET" + ps + "Framework" + ps +
this.MSBuildVersion + ps + "msbuild";
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual string GetBuilderArguments()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return String.Format(" \"{0}\" /t:Rebuild /p:Configuation={1}", Location, this.Configuration);
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual void BuildAssembly()
{
var info = new ProcessStartInfo()
{
FileName = this.GetBuilderPath(),
Arguments = this.GetBuilderArguments()
};
info.WindowStyle = ProcessWindowStyle.Hidden;
using (var p = Process.Start(info))
{
p.WaitForExit();
if (p.ExitCode != 0)
{
Bridge.Translator.Exception.Throw("Compilation was not successful, exit code - " + p.ExitCode);
}
}
}
}
}
```
Correct builder path - .Net Framework folder starts from "v" | ```c#
using System;
using System.Diagnostics;
namespace Bridge.Translator
{
public partial class Translator
{
protected static readonly char ps = System.IO.Path.DirectorySeparatorChar;
protected virtual string GetBuilderPath()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return Environment.GetEnvironmentVariable("windir") + ps + "Microsoft.NET" + ps + "Framework" + ps +
"v" + this.MSBuildVersion + ps + "msbuild";
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual string GetBuilderArguments()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return String.Format(" \"{0}\" /t:Rebuild /p:Configuation={1}", Location, this.Configuration);
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual void BuildAssembly()
{
var info = new ProcessStartInfo()
{
FileName = this.GetBuilderPath(),
Arguments = this.GetBuilderArguments(),
UseShellExecute = true
};
info.WindowStyle = ProcessWindowStyle.Hidden;
using (var p = Process.Start(info))
{
p.WaitForExit();
if (p.ExitCode != 0)
{
Bridge.Translator.Exception.Throw("Compilation was not successful, exit code - " + p.ExitCode);
}
}
}
}
}
``` |
4d65a7c9-cdb0-4f42-b12e-0d8dd75aab10 | {
"language": "C#"
} | ```c#
namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit, bool monitorHostProcess)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
// the methods below are to support legacy versions of the API to the Create() method
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit)
{
return Create(assemblyName, openDebugConsole, false, false);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
```
Fix for assuming any legacy call is 32-bit | ```c#
namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit, bool monitorHostProcess)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
// the methods below are to support legacy versions of the API to the Create() method
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit)
{
return Create(assemblyName, openDebugConsole, is64Bit, false);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
``` |
2aad29ef-2923-4621-9605-aa4cc36e2eab | {
"language": "C#"
} | ```c#
using System.Text;
using Models = EntityCore.Initialization.Metadata.Models;
namespace EntityCore.DynamicEntity
{
internal class EntityDatabaseStructure
{
public static string GenerateCreateTableSqlQuery(Models.Entity entity)
{
var createTable = new StringBuilder();
createTable.AppendFormat("CREATE TABLE [{0}] (Id int IDENTITY(1,1) NOT NULL, ", entity.Name);
foreach (var attribute in entity.Attributes)
{
createTable.AppendFormat("{0} {1}{2} {3} {4}, ", attribute.Name,
attribute.Type.SqlServerName,
attribute.Length == null ? string.Empty : "(" + attribute.Length.ToString() + ")",
attribute.IsNullable ? "NULL" : string.Empty,
attribute.DefaultValue != null ? "DEFAULT(" + attribute.DefaultValue + ")" : string.Empty);
}
createTable.AppendFormat("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED", entity.Name);
createTable.AppendFormat("(Id ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF," +
"ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
return createTable.ToString();
}
}
}
```
Use of metadata proxies to generate table. | ```c#
using EntityCore.Proxy.Metadata;
using System.Text;
namespace EntityCore.DynamicEntity
{
internal class EntityDatabaseStructure
{
public static string GenerateCreateTableSqlQuery(IEntity entity)
{
var createTable = new StringBuilder();
createTable.AppendFormat("CREATE TABLE [{0}] (Id int IDENTITY(1,1) NOT NULL, ", entity.Name);
foreach (var attribute in entity.Attributes)
{
createTable.AppendFormat("{0} {1}{2} {3} {4}, ", attribute.Name,
attribute.Type.SqlServerName,
attribute.Length == null ? string.Empty : "(" + attribute.Length.ToString() + ")",
(attribute.IsNullable ?? true) ? "NULL" : string.Empty,
attribute.DefaultValue != null ? "DEFAULT(" + attribute.DefaultValue + ")" : string.Empty);
}
createTable.AppendFormat("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED", entity.Name);
createTable.AppendFormat("(Id ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF," +
"ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
return createTable.ToString();
}
}
}
``` |
14e5b39f-dbed-4bc6-b974-1d91806ea170 | {
"language": "C#"
} | ```c#
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Configuration")]
[assembly: AssemblyDescription("Autofac XML Configuration Support")]
[assembly: InternalsVisibleTo("Autofac.Tests.Configuration, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Configuration")]
[assembly: InternalsVisibleTo("Autofac.Tests.Configuration, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
``` |
d2619666-5874-40a5-9498-1e21e00a0ea1 | {
"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 UIKit;
namespace osu.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, "GameUIApplication", "AppDelegate");
}
}
}
```
Update deprecated code in iOS main entry | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.iOS;
using UIKit;
namespace osu.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
``` |
3d53b9aa-296a-4cb7-a41b-aa9c8bca9f56 | {
"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("AltFunding")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AltFunding")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2c84adb4-a8b2-453a-941a-dca4e9383182")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1")]
[assembly: AssemblyFileVersion("0.1.0")]
```
Update assembly info for development of the next version | ```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("AltFunding")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AltFunding")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2c84adb4-a8b2-453a-941a-dca4e9383182")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2")]
[assembly: AssemblyFileVersion("0.2.0")]
``` |
0360729e-44f2-453f-902f-2d3b2165f258 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.SPOT;
namespace Idiot.Net
{
class Credentials
{
}
}
```
Add credentials class for user authorization | ```c#
using System;
using Microsoft.SPOT;
using System.Text;
using GHIElectronics.NETMF.Net;
namespace Idiot.Net
{
public class Credentials
{
private string username;
private string password;
public Credentials(string username, string password)
{
this.username = username;
this.password = password;
this.AuthorizationHeader = this.toAuthorizationHeader();
}
/// <summary>
/// Basic authorization header value to be used for server authentication
/// </summary>
public string AuthorizationHeader { get; private set; }
private string toAuthorizationHeader()
{
return "Basic " + ConvertBase64.ToBase64String(Encoding.UTF8.GetBytes(this.username + ":" + this.password));
}
}
}
``` |
3ecab2ef-8d36-4ef6-acb7-ec6c0a5d761d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace SNPPlib
{
public class PagerCollection : Collection<string>
{
public PagerCollection()
{
Pagers = new List<string>();
}
internal IList<string> Pagers { get; set; }
public new void Add(string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers.Add(pager);
}
public void AddRange(IEnumerable<string> pagers)
{
foreach (var pager in pagers)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers.Add(pager);
}
}
public override string ToString()
{
return String.Join(", ", Pagers);
}
protected override void InsertItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers.Insert(index, pager);
}
protected override void SetItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException("Pager ids must be numeric.", "pager");
Pagers[index] = pager;
}
}
}```
Change missed exception message to resource. | ```c#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace SNPPlib
{
public class PagerCollection : Collection<string>
{
public PagerCollection()
{
Pagers = new List<string>();
}
internal IList<string> Pagers { get; set; }
public new void Add(string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers.Add(pager);
}
public void AddRange(IEnumerable<string> pagers)
{
foreach (var pager in pagers)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers.Add(pager);
}
}
public override string ToString()
{
return String.Join(", ", Pagers);
}
protected override void InsertItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers.Insert(index, pager);
}
protected override void SetItem(int index, string pager)
{
if (!SnppClientProtocol.PagerIdFormat.IsMatch(pager))
throw new ArgumentException(Resource.PagerIdNumeric, "pager");
Pagers[index] = pager;
}
}
}``` |
83bcd74b-fe50-4fc4-9447-98c080a8740e | {
"language": "C#"
} | ```c#
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DriftUe4PluginServerTarget : TargetRules
{
public DriftUe4PluginServerTarget(TargetInfo Target)
{
Type = TargetType.Server;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
OutExtraModuleNames.Add("DriftUe4Plugin");
}
public override bool GetSupportedPlatforms(ref List<UnrealTargetPlatform> OutPlatforms)
{
// It is valid for only server platforms
return UnrealBuildTool.UnrealBuildTool.GetAllServerPlatforms(ref OutPlatforms, false);
}
}
```
Remove use of obsolete function | ```c#
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DriftUe4PluginServerTarget : TargetRules
{
public DriftUe4PluginServerTarget(TargetInfo Target)
{
Type = TargetType.Server;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
OutExtraModuleNames.Add("DriftUe4Plugin");
}
}
``` |
f39c20d9-a2ff-4986-abe7-26c7c173283c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJ
{
class Program
{
static void Main(string[] args)
{
}
}
}
```
Add beginnings of a method to parse TMD files | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using LBD2OBJ.Types;
namespace LBD2OBJ
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("LBD2OBJ - Made by Figglewatts 2015");
foreach (string arg in args)
{
if (Path.GetExtension(arg).ToLower().Equals("tmd"))
{
// convert from tmd
}
else if (Path.GetExtension(arg).ToLower().Equals("lbd"))
{
// convert from lbd
}
else
{
Console.WriteLine("Invalid input file. Extension: {0} not recognized.", Path.GetExtension(arg));
}
}
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
public static void ConvertTMD(string path)
{
Console.WriteLine("Converting TMD...");
TMD tmd;
bool fixP; // if true, pointers are fixed i.e. non-relative
using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
{
tmd.header = readHeader(b);
fixP = (tmd.header.flags & 1) == 1 ? true : false;
tmd.objTable = new OBJECT[tmd.header.numObjects];
for (int i = 0; i < tmd.header.numObjects; i++)
{
tmd.objTable[i] = readObject(b);
}
}
}
private static TMDHEADER readHeader(BinaryReader b)
{
TMDHEADER tmdHeader;
tmdHeader.ID = b.ReadUInt32();
tmdHeader.flags = b.ReadUInt32();
tmdHeader.numObjects = b.ReadUInt32();
return tmdHeader;
}
private static OBJECT readObject(BinaryReader b)
{
OBJECT obj;
obj.vertTop = b.ReadUInt32();
obj.numVerts = b.ReadUInt32();
obj.normTop = b.ReadUInt32();
obj.numNorms = b.ReadUInt32();
obj.primTop = b.ReadUInt32();
obj.numPrims = b.ReadUInt32();
obj.scale = b.ReadInt32();
return obj;
}
}
}
``` |
b137789a-02e2-4ce8-969e-6be936fe8bce | {
"language": "C#"
} | ```c#
using System;
namespace GitReleaseNotes
{
public class ArgumentVerifier
{
public static bool VerifyArguments(GitReleaseNotesArguments arguments)
{
if (arguments.IssueTracker == null)
{
Console.WriteLine("The IssueTracker argument must be provided, see help (/?) for possible options");
{
return false;
}
}
if (string.IsNullOrEmpty(arguments.OutputFile) || !arguments.OutputFile.EndsWith(".md"))
{
Console.WriteLine("Specify an output file (*.md) [/OutputFile ...]");
{
return false;
}
}
return true;
}
}
}```
Allow publish without outputting a .md file | ```c#
using System;
namespace GitReleaseNotes
{
public class ArgumentVerifier
{
public static bool VerifyArguments(GitReleaseNotesArguments arguments)
{
if (arguments.IssueTracker == null)
{
Console.WriteLine("The IssueTracker argument must be provided, see help (/?) for possible options");
{
return false;
}
}
if ((string.IsNullOrEmpty(arguments.OutputFile) || !arguments.OutputFile.EndsWith(".md")) && !arguments.Publish)
{
Console.WriteLine("Specify an output file (*.md) [/OutputFile ...]");
{
return false;
}
}
return true;
}
}
}``` |
ae487e6e-5821-4f94-b8c2-70e59ff6cb4e | {
"language": "C#"
} | ```c#
@model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<noscript>
<img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" />
</noscript>
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
```
Add Ids to footer links | ```c#
@model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git-commit" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a id="link-git-branch" href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<noscript>
<img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" />
</noscript>
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
``` |
cbbcca01-2ea2-481e-b3e1-00243baa3187 | {
"language": "C#"
} | ```c#
namespace IronFoundry.Warden.Service
{
public static class Constants
{
public const string DisplayName = "Iron Foundry Warden Service";
public const string ServiceName = "ironfoundry.warden";
}
}
```
Fix casing of warden service. | ```c#
namespace IronFoundry.Warden.Service
{
public static class Constants
{
public const string DisplayName = "Iron Foundry Warden Service";
public const string ServiceName = "IronFoundry.Warden";
}
}
``` |
8d8efee5-81ab-4a93-9a48-50061824f621 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Text;
namespace KuduSync.NET
{
public class Logger : IDisposable
{
private const int KeepAliveLogTimeInSeconds = 20;
private int _logCounter = 0;
private StreamWriter _writer;
private int _maxLogLines;
private DateTime _nextLogTime;
/// <summary>
/// Logger class
/// </summary>
/// <param name="maxLogLines">sets the verbosity, 0 is verbose, less is quiet, more is the number of maximum log lines to write.</param>
public Logger(int maxLogLines)
{
var stream = Console.OpenStandardOutput();
_writer = new StreamWriter(stream);
_maxLogLines = maxLogLines;
}
public void Log(string format, params object[] args)
{
if (_maxLogLines == 0 || _logCounter < _maxLogLines)
{
_writer.WriteLine(format, args);
}
else if (_logCounter == _maxLogLines)
{
_writer.WriteLine("Omitting next output lines...");
}
else
{
// Make sure some output is still logged every 20 seconds
if (DateTime.Now >= _nextLogTime)
{
_writer.WriteLine("Working...");
_nextLogTime = DateTime.Now.Add(TimeSpan.FromSeconds(KeepAliveLogTimeInSeconds));
}
}
_logCounter++;
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
}
}
```
Fix flushing issue and added number of files being processed. | ```c#
using System;
using System.IO;
using System.Text;
namespace KuduSync.NET
{
public class Logger : IDisposable
{
private const int KeepAliveLogTimeInSeconds = 20;
private int _logCounter = 0;
private StreamWriter _writer;
private int _maxLogLines;
private DateTime _nextLogTime;
/// <summary>
/// Logger class
/// </summary>
/// <param name="maxLogLines">sets the verbosity, 0 is verbose, less is quiet, more is the number of maximum log lines to write.</param>
public Logger(int maxLogLines)
{
var stream = Console.OpenStandardOutput();
_writer = new StreamWriter(stream);
_maxLogLines = maxLogLines;
}
public void Log(string format, params object[] args)
{
bool logged = false;
if (_maxLogLines == 0 || _logCounter < _maxLogLines)
{
_writer.WriteLine(format, args);
}
else if (_logCounter == _maxLogLines)
{
_writer.WriteLine("Omitting next output lines...");
logged = true;
}
else
{
// Make sure some output is still logged every 20 seconds
if (DateTime.Now >= _nextLogTime)
{
_writer.WriteLine("Processed {0} files...", _logCounter - 1);
logged = true;
}
}
if (logged)
{
_writer.Flush();
_nextLogTime = DateTime.Now.Add(TimeSpan.FromSeconds(KeepAliveLogTimeInSeconds));
}
_logCounter++;
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
}
}
``` |
ec3ad16d-899e-483b-b313-c38c53e2072f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : IPathElement
{
public static bool IsApplicable(string pathElement)
{
return Regex.IsMatch(pathElement, @"\w+");
}
private string property;
public Property(string property)
{
this.property = property;
}
public object Apply(object target)
{
PropertyInfo p = target.GetType().GetProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
```
Remove unnecessary static method IsApplicable | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : IPathElement
{
private string property;
public Property(string property)
{
this.property = property;
}
public object Apply(object target)
{
PropertyInfo p = target.GetType().GetProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
``` |
9aef6beb-cfd7-4c82-b1df-0665119ffbb0 | {
"language": "C#"
} | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EOLib.IO.Map
{
public enum MapEffect : byte
{
None = 0,
HPDrain = 1,
TPDrain = 2,
Quake = 3
}
}```
Add more quakes to map effect | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EOLib.IO.Map
{
public enum MapEffect : byte
{
None = 0,
HPDrain = 1,
TPDrain = 2,
Quake1 = 3,
Quake2 = 4,
Quake3 = 5,
Quake4 = 6
}
}``` |
6b765825-6093-4534-b569-3aabe230968e | {
"language": "C#"
} | ```c#
using System;
using System.Web.Mvc;
namespace Foo.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
throw new NotImplementedException();
}
}
}
```
Return view from index action | ```c#
using System;
using System.Web.Mvc;
namespace Foo.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
``` |
a2406931-f651-43d7-ad09-d9fcf836955b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreMvc.Models;
using Ooui;
using Ooui.AspNetCore;
namespace AspNetCoreMvc.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var element = new Label { Text = "Hello Oooooui from Controller" };
return new ElementResult (element);
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
```
Make the ASP.NET demo more interesting | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreMvc.Models;
using Ooui;
using Ooui.AspNetCore;
namespace AspNetCoreMvc.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var count = 0;
var head = new Heading { Text = "Ooui!" };
var label = new Label { Text = "0" };
var btn = new Button { Text = "Increase" };
btn.Clicked += (sender, e) => {
count++;
label.Text = count.ToString ();
};
var div = new Div ();
div.AppendChild (head);
div.AppendChild (label);
div.AppendChild (btn);
return new ElementResult (div);
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
``` |
d59c3ce3-437c-4d0d-be19-32cf9aface5f | {
"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 System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailJudgement : TestSceneAllRulesetPlayers
{
protected override Player CreatePlayer(Ruleset ruleset)
{
SelectedMods.Value = Array.Empty<Mod>();
return new FailPlayer();
}
protected override void AddCheckSteps()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for multiple judged objects", () => ((FailPlayer)Player).DrawableRuleset.Playfield.AllHitObjects.Count(h => h.AllJudged) > 1);
AddAssert("total judgements == 1", () => ((FailPlayer)Player).HealthProcessor.JudgedHits >= 1);
}
private class FailPlayer : TestPlayer
{
public new HealthProcessor HealthProcessor => base.HealthProcessor;
public FailPlayer()
: base(false, false)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
HealthProcessor.FailConditions += (_, __) => true;
}
}
}
}
```
Fix broken fail judgement test | ```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 System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailJudgement : TestSceneAllRulesetPlayers
{
protected override Player CreatePlayer(Ruleset ruleset)
{
SelectedMods.Value = Array.Empty<Mod>();
return new FailPlayer();
}
protected override void AddCheckSteps()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for multiple judgements", () => ((FailPlayer)Player).ScoreProcessor.JudgedHits > 1);
AddAssert("total number of results == 1", () =>
{
var score = new ScoreInfo();
((FailPlayer)Player).ScoreProcessor.PopulateScore(score);
return score.Statistics.Values.Sum() == 1;
});
}
private class FailPlayer : TestPlayer
{
public new HealthProcessor HealthProcessor => base.HealthProcessor;
public FailPlayer()
: base(false, false)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
HealthProcessor.FailConditions += (_, __) => true;
}
}
}
}
``` |
ff03d681-28fe-4d96-9b47-fea6dc0919cd | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Cosmos.Kernel.LogTail
{
public class ErrorStrippingFileStream : FileStream
{
public ErrorStrippingFileStream(string file)
: base(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite)
{
}
public override int ReadByte()
{
int result;
while ((result = base.ReadByte()) == 0) ;
return result;
}
public override int Read(byte[] array, int offset, int count)
{
int i;
for (i = 0; i < count; i++)
{
int b = ReadByte();
if (b == -1)
return i;
array[offset + i] = (byte) b;
}
return i;
}
}
}
```
Make sure you run the log after qemu starts... But it works. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Cosmos.Kernel.LogTail
{
public class ErrorStrippingFileStream : FileStream
{
public ErrorStrippingFileStream(string file)
: base(file, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)
{
}
public override int ReadByte()
{
int result;
while ((result = base.ReadByte()) == 0) ;
return result;
}
public override int Read(byte[] array, int offset, int count)
{
int i;
for (i = 0; i < count; i++)
{
int b = ReadByte();
if (b == -1)
return i;
array[offset + i] = (byte) b;
}
return i;
}
}
}
``` |
a29f0b45-0f0c-4be1-9622-724c0f49f0d2 | {
"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.Input.Bindings;
using osu.Game.Database;
using Realms;
namespace osu.Game.Input.Bindings
{
[MapTo(nameof(KeyBinding))]
public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding
{
[PrimaryKey]
public string StringGuid { get; set; }
[Ignored]
public Guid ID
{
get => Guid.Parse(StringGuid);
set => StringGuid = value.ToString();
}
public int? RulesetID { get; set; }
public int? Variant { get; set; }
public KeyCombination KeyCombination
{
get => KeyCombinationString;
set => KeyCombinationString = value.ToString();
}
public object Action
{
get => ActionInt;
set => ActionInt = (int)value;
}
[MapTo(nameof(Action))]
public int ActionInt { get; set; }
[MapTo(nameof(KeyCombination))]
public string KeyCombinationString { get; set; }
}
}
```
Revert "Switch Guid implementation temporarily to avoid compile time error" | ```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.Input.Bindings;
using osu.Game.Database;
using Realms;
namespace osu.Game.Input.Bindings
{
[MapTo(nameof(KeyBinding))]
public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding
{
[PrimaryKey]
public Guid ID { get; set; }
public int? RulesetID { get; set; }
public int? Variant { get; set; }
public KeyCombination KeyCombination
{
get => KeyCombinationString;
set => KeyCombinationString = value.ToString();
}
public object Action
{
get => ActionInt;
set => ActionInt = (int)value;
}
[MapTo(nameof(Action))]
public int ActionInt { get; set; }
[MapTo(nameof(KeyCombination))]
public string KeyCombinationString { get; set; }
}
}
``` |
1cd7bbf6-0f46-4d73-a82d-ecbdd3dab3a0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
namespace MsgPack.Serialization.DefaultSerializers
{
/// <summary>
/// Dictionary interface serializer.
/// </summary>
internal sealed class NonGenericDictionarySerializer : MessagePackSerializer<IDictionary>
{
private readonly System_Collections_DictionaryEntryMessagePackSerializer _entrySerializer;
private readonly IMessagePackSerializer _collectionDeserializer;
public NonGenericDictionarySerializer( SerializationContext ownerContext, Type targetType )
: base( ownerContext )
{
this._entrySerializer = new System_Collections_DictionaryEntryMessagePackSerializer( ownerContext );
this._collectionDeserializer = ownerContext.GetSerializer( targetType );
}
protected internal override void PackToCore( Packer packer, IDictionary objectTree )
{
packer.PackMapHeader( objectTree.Count );
foreach ( DictionaryEntry item in objectTree )
{
this._entrySerializer.PackToCore( packer, item );
}
}
protected internal override IDictionary UnpackFromCore( Unpacker unpacker )
{
return this._collectionDeserializer.UnpackFrom( unpacker ) as IDictionary;
}
}
}```
Fix non-generic dictionary serializer does not pack key value pair correctly. | ```c#
using System;
using System.Collections;
using System.Runtime.Serialization;
namespace MsgPack.Serialization.DefaultSerializers
{
/// <summary>
/// Dictionary interface serializer.
/// </summary>
internal sealed class NonGenericDictionarySerializer : MessagePackSerializer<IDictionary>
{
private readonly IMessagePackSerializer _collectionDeserializer;
public NonGenericDictionarySerializer( SerializationContext ownerContext, Type targetType )
: base( ownerContext )
{
this._collectionDeserializer = ownerContext.GetSerializer( targetType );
}
protected internal override void PackToCore( Packer packer, IDictionary objectTree )
{
packer.PackMapHeader( objectTree.Count );
foreach ( DictionaryEntry item in objectTree )
{
if ( !( item.Key is MessagePackObject ) )
{
throw new SerializationException("Non generic dictionary may contain only MessagePackObject typed key.");
}
( item.Key as IPackable ).PackToMessage( packer, null );
if ( !( item.Value is MessagePackObject ) )
{
throw new SerializationException("Non generic dictionary may contain only MessagePackObject typed value.");
}
( item.Value as IPackable ).PackToMessage( packer, null ); }
}
protected internal override IDictionary UnpackFromCore( Unpacker unpacker )
{
return this._collectionDeserializer.UnpackFrom( unpacker ) as IDictionary;
}
}
}``` |
254da04e-f2c0-43aa-83f0-50f8d369fc56 | {
"language": "C#"
} | ```c#
using BackOffice.Jobs.Interfaces;
using BackOffice.Jobs.Reports;
using System;
namespace BackOffice.Worker
{
public class CProductAlwaysFailingReportWorker : IJobWorker
{
private readonly AlwaysFailingReport report;
public CProductAlwaysFailingReportWorker(AlwaysFailingReport report)
{
this.report = report;
}
public void Start()
{
throw new NotImplementedException();
}
}
}
```
Add 10s delay for always failing worker | ```c#
using BackOffice.Jobs.Interfaces;
using BackOffice.Jobs.Reports;
using System;
using System.Threading;
namespace BackOffice.Worker
{
public class CProductAlwaysFailingReportWorker : IJobWorker
{
private readonly AlwaysFailingReport report;
public CProductAlwaysFailingReportWorker(AlwaysFailingReport report)
{
this.report = report;
}
public void Start()
{
Thread.Sleep(10 * 1000);
throw new NotImplementedException();
}
}
}
``` |
948aa5ad-25b3-4c41-b25a-7602e399d6a3 | {
"language": "C#"
} | ```c#
namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
throw new NotImplementedException();
}
}
}```
Make the discovery context null tests pass. | ```c#
namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
else if (discoveryContext == null)
{
throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
}
throw new NotImplementedException();
}
}
}``` |
108cd852-2209-4169-9662-42993dc77708 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Moq.Proxy
{
public class ProxyDiscoverer
{
public async Task<IImmutableSet<ImmutableArray<ITypeSymbol>>> DiscoverProxiesAsync(Project project, CancellationToken cancellationToken = default(CancellationToken))
{
var discoverer = project.LanguageServices.GetRequiredService<IProxyDiscoverer>();
var compilation = await project.GetCompilationAsync(cancellationToken);
var proxyGeneratorSymbol = compilation.GetTypeByMetadataName(typeof(ProxyGeneratorAttribute).FullName);
// TODO: message.
if (proxyGeneratorSymbol == null)
throw new InvalidOperationException();
var proxies = new List<ImmutableArray<ITypeSymbol>>();
foreach (var document in project.Documents)
{
var discovered = await discoverer.DiscoverProxiesAsync(document, proxyGeneratorSymbol, cancellationToken);
proxies.AddRange(discovered);
}
return proxies.ToImmutableHashSet(StructuralComparer<ImmutableArray<ITypeSymbol>>.Default);
}
}
}
```
Reduce memory usage by using a hashset instead of a list | ```c#
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Moq.Proxy
{
public class ProxyDiscoverer
{
public async Task<IImmutableSet<ImmutableArray<ITypeSymbol>>> DiscoverProxiesAsync(Project project, CancellationToken cancellationToken = default(CancellationToken))
{
var discoverer = project.LanguageServices.GetRequiredService<IProxyDiscoverer>();
var compilation = await project.GetCompilationAsync(cancellationToken);
var proxyGeneratorSymbol = compilation.GetTypeByMetadataName(typeof(ProxyGeneratorAttribute).FullName);
// TODO: message.
if (proxyGeneratorSymbol == null)
throw new InvalidOperationException();
var proxies = new HashSet<ImmutableArray<ITypeSymbol>>(StructuralComparer<ImmutableArray<ITypeSymbol>>.Default);
foreach (var document in project.Documents)
{
var discovered = await discoverer.DiscoverProxiesAsync(document, proxyGeneratorSymbol, cancellationToken);
foreach (var proxy in discovered)
{
proxies.Add(proxy);
}
}
return proxies.ToImmutableHashSet(StructuralComparer<ImmutableArray<ITypeSymbol>>.Default);
}
}
}
``` |
987f83fc-bc3e-4dbc-9198-b1673a682cae | {
"language": "C#"
} | ```c#
using System.Linq;
using JetBrains.ActionManagement;
using JetBrains.Annotations;
using JetBrains.Application.DataContext;
using JetBrains.ReSharper.Features.Inspections.Actions;
using JetBrains.UI.ActionsRevised;
namespace Roflcopter.Plugin.TodoItems
{
[Action(nameof(TodoItemsCountDummyAction), Id = 944208914)]
public class TodoItemsCountDummyAction : IExecutableAction, IInsertLast<TodoExplorerActionBarActionGroup>
{
public bool Update(IDataContext context, ActionPresentation presentation, [CanBeNull] DelegateUpdate nextUpdate)
{
var todoItemsCountProvider = context.GetComponent<TodoItemsCountProvider>();
var todoItemsCounts = todoItemsCountProvider.TodoItemsCounts;
if (todoItemsCounts == null)
presentation.Text = null;
else
presentation.Text = string.Join(", ", todoItemsCounts.Select(x => $"{x.Definition}: {x.Count}"));
return false;
}
public void Execute(IDataContext context, [CanBeNull] DelegateExecute nextExecute)
{
}
}
}
```
Add separator before action item in tool bar | ```c#
using System.Linq;
using JetBrains.ActionManagement;
using JetBrains.Annotations;
using JetBrains.Application.DataContext;
using JetBrains.ReSharper.Features.Inspections.Actions;
using JetBrains.UI.ActionsRevised;
namespace Roflcopter.Plugin.TodoItems
{
[ActionGroup(nameof(TodoItemsCountDummyActionGroup), ActionGroupInsertStyles.Separated, Id = 944208910)]
public class TodoItemsCountDummyActionGroup : IAction, IInsertLast<TodoExplorerActionBarActionGroup>
{
public TodoItemsCountDummyActionGroup(TodoItemsCountDummyAction _)
{
}
}
[Action(nameof(TodoItemsCountDummyAction), Id = 944208920)]
public class TodoItemsCountDummyAction : IExecutableAction
{
public bool Update(IDataContext context, ActionPresentation presentation, [CanBeNull] DelegateUpdate nextUpdate)
{
var todoItemsCountProvider = context.GetComponent<TodoItemsCountProvider>();
var todoItemsCounts = todoItemsCountProvider.TodoItemsCounts;
if (todoItemsCounts == null)
presentation.Text = null;
else
presentation.Text = string.Join(", ", todoItemsCounts.Select(x => $"{x.Definition}: {x.Count}"));
return false;
}
public void Execute(IDataContext context, [CanBeNull] DelegateExecute nextExecute)
{
}
}
}
``` |
52e7be7a-2f56-4f8c-a4d1-25f54c3fe57c | {
"language": "C#"
} | ```c#
using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
}
}
}
```
Fix mono bug in the FontHelper class | ```c#
using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
Assert.IsTrue(true);
}
}
}
``` |
07861716-610e-4d1c-abee-7844dc2d796d | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
public static class MvcBuilderExtensions
{
/// <summary>
/// Adds conventions to turn off MVC's built-in <see cref="ApiBehaviorOptions.ClientErrorMapping"/>,
/// adds a <see cref="ProducesErrorResponseTypeAttribute"/> to all actions with in controllers with an
/// <see cref="ApiControllerAttribute"/> and a result filter that transforms <see cref="ObjectResult"/>
/// containing a <see cref="string"/> to <see cref="ProblemDetails"/> responses.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddProblemDetailsConventions(this IMvcBuilder builder)
{
// Forward the MVC problem details factory registration to the factory used by the middleware.
builder.Services.TryAddSingleton<MvcProblemDetailsFactory>(p => p.GetRequiredService<ProblemDetailsFactory>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<ApiBehaviorOptions>, ProblemDetailsApiBehaviorOptionsSetup>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, ProblemDetailsApplicationModelProvider>());
return builder;
}
}
}
```
Replace the existing ProblemDetailsFactory from MVC | ```c#
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
public static class MvcBuilderExtensions
{
/// <summary>
/// Adds conventions to turn off MVC's built-in <see cref="ApiBehaviorOptions.ClientErrorMapping"/>,
/// adds a <see cref="ProducesErrorResponseTypeAttribute"/> to all actions with in controllers with an
/// <see cref="ApiControllerAttribute"/> and a result filter that transforms <see cref="ObjectResult"/>
/// containing a <see cref="string"/> to <see cref="ProblemDetails"/> responses.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddProblemDetailsConventions(this IMvcBuilder builder)
{
// Forward the MVC problem details factory registration to the factory used by the middleware.
builder.Services.Replace(
ServiceDescriptor.Singleton<MvcProblemDetailsFactory>(p => p.GetRequiredService<ProblemDetailsFactory>()));
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<ApiBehaviorOptions>, ProblemDetailsApiBehaviorOptionsSetup>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, ProblemDetailsApplicationModelProvider>());
return builder;
}
}
}
``` |
a1995ff8-f48f-4a0d-aa45-f50899edc349 | {
"language": "C#"
} | ```c#
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification
public static class DApplication
{
public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data)
{
//Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition);
connection.Iterate ();
//Console.Error.WriteLine ("Dispatch done");
return true;
}
public static Connection Connection
{
get {
return connection;
}
}
static Connection connection;
static Bus bus;
public static void Init ()
{
connection = new Connection ();
//ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
//string name = "org.freedesktop.DBus";
/*
bus = connection.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.Error.WriteLine ("NameAcquired: " + acquired_name);
};
string myName = bus.Hello ();
Console.Error.WriteLine ("myName: " + myName);
*/
IOChannel channel = new IOChannel ((int)connection.sock.Handle);
IO.AddWatch (channel, IOCondition.In, Dispatch);
}
}
}
```
Remove dead private and comments | ```c#
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification
public static class DApplication
{
public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data)
{
//Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition);
connection.Iterate ();
//Console.Error.WriteLine ("Dispatch done");
return true;
}
static Connection connection;
public static Connection Connection
{
get {
return connection;
}
}
public static void Init ()
{
connection = new Connection ();
IOChannel channel = new IOChannel ((int)connection.sock.Handle);
IO.AddWatch (channel, IOCondition.In, Dispatch);
}
}
}
``` |
f6762d70-b7bf-4b7a-8bf6-53820cae4f28 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Diagnostics;
namespace osu_database_reader.Components.HitObjects
{
public class HitObjectSlider : HitObject
{
public CurveType CurveType;
public List<Vector2> Points = new List<Vector2>(); //does not include initial point!
public int RepeatCount;
public double Length; //seems to be length in o!p, so it doesn't have to be calculated?
public void ParseSliderSegments(string sliderString)
{
string[] split = sliderString.Split('|');
foreach (var s in split) {
if (s.Length == 1) { //curve type
switch (s[0]) {
case 'L': CurveType = CurveType.Linear; break;
case 'C': CurveType = CurveType.Catmull; break;
case 'P': CurveType = CurveType.Perfect; break;
case 'B': CurveType = CurveType.Bezier; break;
}
continue;
}
string[] split2 = s.Split(':');
Debug.Assert(split2.Length == 2);
Points.Add(new Vector2(
int.Parse(split2[0]),
int.Parse(split2[1])));
}
}
}
}
```
Make CodeFactor happy at the cost of my own happiness (code unfolding) | ```c#
using System.Collections.Generic;
using System.Diagnostics;
namespace osu_database_reader.Components.HitObjects
{
public class HitObjectSlider : HitObject
{
public CurveType CurveType;
public List<Vector2> Points = new List<Vector2>(); //does not include initial point!
public int RepeatCount;
public double Length; //seems to be length in o!p, so it doesn't have to be calculated?
public void ParseSliderSegments(string sliderString)
{
string[] split = sliderString.Split('|');
foreach (var s in split) {
if (s.Length == 1) { //curve type
switch (s[0]) {
case 'L':
CurveType = CurveType.Linear;
break;
case 'C':
CurveType = CurveType.Catmull;
break;
case 'P':
CurveType = CurveType.Perfect;
break;
case 'B':
CurveType = CurveType.Bezier;
break;
}
continue;
}
string[] split2 = s.Split(':');
Debug.Assert(split2.Length == 2);
Points.Add(new Vector2(
int.Parse(split2[0]),
int.Parse(split2[1])));
}
}
}
}
``` |
13c5cc90-0711-40be-ba6a-82067a8f3cd0 | {
"language": "C#"
} | ```c#
using Cake.Common;
using Cake.Frosting;
namespace Build
{
public sealed class Lifetime : FrostingLifetime<Context>
{
public override void Setup(Context context)
{
context.Configuration = context.Argument("configuration", "Release");
context.BaseDir = context.Environment.WorkingDirectory;
context.SourceDir = context.BaseDir.Combine("src");
context.BuildDir = context.BaseDir.Combine("build");
context.CakeToolsDir = context.BaseDir.Combine("tools/cake");
context.LibraryDir = context.SourceDir.Combine("VGAudio");
context.CliDir = context.SourceDir.Combine("VGAudio.Cli");
context.TestsDir = context.SourceDir.Combine("VGAudio.Tests");
context.BenchmarkDir = context.SourceDir.Combine("VGAudio.Benchmark");
context.UwpDir = context.SourceDir.Combine("VGAudio.Uwp");
context.SlnFile = context.SourceDir.CombineWithFilePath("VGAudio.sln");
context.TestsCsproj = context.TestsDir.CombineWithFilePath("VGAudio.Tests.csproj");
context.PublishDir = context.BaseDir.Combine("Publish");
context.LibraryPublishDir = context.PublishDir.Combine("NuGet");
context.CliPublishDir = context.PublishDir.Combine("cli");
context.UwpPublishDir = context.PublishDir.Combine("uwp");
context.ReleaseCertThumbprint = "2043012AE523F7FA0F77A537387633BEB7A9F4DD";
}
}
}```
Use separate output directories for debug and release builds | ```c#
using Cake.Common;
using Cake.Frosting;
namespace Build
{
public sealed class Lifetime : FrostingLifetime<Context>
{
public override void Setup(Context context)
{
context.Configuration = context.Argument("configuration", "Release");
context.BaseDir = context.Environment.WorkingDirectory;
context.SourceDir = context.BaseDir.Combine("src");
context.BuildDir = context.BaseDir.Combine("build");
context.CakeToolsDir = context.BaseDir.Combine("tools/cake");
context.LibraryDir = context.SourceDir.Combine("VGAudio");
context.CliDir = context.SourceDir.Combine("VGAudio.Cli");
context.TestsDir = context.SourceDir.Combine("VGAudio.Tests");
context.BenchmarkDir = context.SourceDir.Combine("VGAudio.Benchmark");
context.UwpDir = context.SourceDir.Combine("VGAudio.Uwp");
context.SlnFile = context.SourceDir.CombineWithFilePath("VGAudio.sln");
context.TestsCsproj = context.TestsDir.CombineWithFilePath("VGAudio.Tests.csproj");
context.PublishDir = context.BaseDir.Combine($"bin/{(context.IsReleaseBuild ? "release" : "debug")}");
context.LibraryPublishDir = context.PublishDir.Combine("NuGet");
context.CliPublishDir = context.PublishDir.Combine("cli");
context.UwpPublishDir = context.PublishDir.Combine("uwp");
context.ReleaseCertThumbprint = "2043012AE523F7FA0F77A537387633BEB7A9F4DD";
}
}
}``` |
919537e1-d999-429a-a9d1-6d4fd0b48679 | {
"language": "C#"
} | ```c#
using System;
namespace ExternalTemplates
{
/// <summary>
/// Default generator options.
/// </summary>
public class GeneratorOptions : IGeneratorOptions
{
/// <summary>
/// Gets the path relative to the web root where the templates are stored.
/// Default is "/Content/templates".
/// </summary>
public string VirtualPath { get; set; } = "/Content/templates";
/// <summary>
/// Gets the extension of the templates.
/// Default is ".tmpl.html".
/// </summary>
public string Extension { get; set; } = ".tmpl.html";
/// <summary>
/// Gets the post string to add to the end of the script tag's id following its name.
/// Default is "-tmpl".
/// </summary>
public string PostString { get; set; } = "-tmpl";
}
}```
Fix the default virtual path | ```c#
using System;
namespace ExternalTemplates
{
/// <summary>
/// Default generator options.
/// </summary>
public class GeneratorOptions : IGeneratorOptions
{
/// <summary>
/// Gets the path relative to the web root where the templates are stored.
/// Default is "Content/templates".
/// </summary>
public string VirtualPath { get; set; } = "Content/templates";
/// <summary>
/// Gets the extension of the templates.
/// Default is ".tmpl.html".
/// </summary>
public string Extension { get; set; } = ".tmpl.html";
/// <summary>
/// Gets the post string to add to the end of the script tag's id following its name.
/// Default is "-tmpl".
/// </summary>
public string PostString { get; set; } = "-tmpl";
}
}``` |
56675ef7-206a-49f0-8bf2-1c4f896dbe7b | {
"language": "C#"
} | ```c#
namespace testproj
{
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
Assert.AreEqual(10, memory.ObjectsCount);
});
}
}
}
```
Fix test in the testproj | ```c#
namespace testproj
{
using System;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
var str1 = "1";
var str2 = "2";
var str3 = "3";
Assert.LessOrEqual(2, memory.ObjectsCount);
Console.WriteLine(str1 + str2 + str3);
});
}
}
}
``` |
3e12f452-231f-4eda-bc2b-d18794b7309e | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Graphite.System
{
public partial class ServiceInstaller
{
private IContainer components = null;
private global::System.ServiceProcess.ServiceInstaller serviceInstaller;
private ServiceProcessInstaller serviceProcessInstaller;
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.serviceInstaller = new global::System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller = new ServiceProcessInstaller();
//
// serviceInstaller
//
this.serviceInstaller.Description = "Graphite System Monitoring";
this.serviceInstaller.DisplayName = "Graphite System Monitoring";
this.serviceInstaller.ServiceName = "GraphiteSystemMonitoring";
this.serviceInstaller.StartType = ServiceStartMode.Automatic;
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// ServiceInstaller
//
this.Installers.AddRange(new Installer[]
{
this.serviceInstaller,
this.serviceProcessInstaller
});
}
}
}```
Install service with "delayed auto start". | ```c#
using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Graphite.System
{
public partial class ServiceInstaller
{
private IContainer components = null;
private global::System.ServiceProcess.ServiceInstaller serviceInstaller;
private ServiceProcessInstaller serviceProcessInstaller;
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.serviceInstaller = new global::System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller = new ServiceProcessInstaller();
//
// serviceInstaller
//
this.serviceInstaller.Description = "Graphite System Monitoring";
this.serviceInstaller.DisplayName = "Graphite System Monitoring";
this.serviceInstaller.ServiceName = "GraphiteSystemMonitoring";
this.serviceInstaller.StartType = ServiceStartMode.Automatic;
this.serviceInstaller.DelayedAutoStart = true;
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// ServiceInstaller
//
this.Installers.AddRange(new Installer[]
{
this.serviceInstaller,
this.serviceProcessInstaller
});
}
}
}``` |
a2d2f6ea-e512-4d9d-9ae9-219f55933ab1 | {
"language": "C#"
} | ```c#
//
// Nikon3MakerNoteEntryTag.cs:
//
// Author:
// Ruben Vermeersch (ruben@savanne.be)
//
// Copyright (C) 2010 Ruben Vermeersch
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
namespace TagLib.IFD.Tags
{
/// <summary>
/// Nikon format 3 makernote tags.
/// Based on http://www.exiv2.org/tags-nikon.html
/// </summary>
public enum Nikon3MakerNoteEntryTag : ushort
{
/// <summary>
/// Offset to an IFD containing a preview image. (Hex: 0x0011)
/// </summary>
Preview = 16,
}
}
```
Fix wrong value for the Preview tag. | ```c#
//
// Nikon3MakerNoteEntryTag.cs:
//
// Author:
// Ruben Vermeersch (ruben@savanne.be)
//
// Copyright (C) 2010 Ruben Vermeersch
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
namespace TagLib.IFD.Tags
{
/// <summary>
/// Nikon format 3 makernote tags.
/// Based on http://www.exiv2.org/tags-nikon.html
/// </summary>
public enum Nikon3MakerNoteEntryTag : ushort
{
/// <summary>
/// Offset to an IFD containing a preview image. (Hex: 0x0011)
/// </summary>
Preview = 17,
}
}
``` |
8610485c-75ac-47d5-b00a-f24a9cfee9ac | {
"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("IS24RestApi")]
[assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Ganss")]
[assembly: AssemblyProduct("IS24RestApi")]
[assembly: AssemblyCopyright("Copyright © 2013 IS24RestApi project contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
```
Change version number to 1.1 | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IS24RestApi")]
[assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Ganss")]
[assembly: AssemblyProduct("IS24RestApi")]
[assembly: AssemblyCopyright("Copyright © 2013 IS24RestApi project contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.*")]
``` |
8c6dcb0f-f8be-4e6b-be9d-e9355058a2d5 | {
"language": "C#"
} | ```c#
using System.IO;
using Containerizer.Services.Interfaces;
namespace Containerizer.Services.Implementations
{
public class StreamOutService : IStreamOutService
{
private readonly IContainerPathService containerPathService;
private readonly ITarStreamService tarStreamService;
public StreamOutService(IContainerPathService containerPathService, ITarStreamService tarStreamService)
{
this.containerPathService = containerPathService;
this.tarStreamService = tarStreamService;
}
public Stream StreamOutFile(string id, string source)
{
string rootDir = containerPathService.GetContainerRoot(id);
string path = Path.Combine(rootDir, source);
Stream stream = tarStreamService.WriteTarToStream(path);
return stream;
}
}
}```
Fix path issue for StreamOut | ```c#
using System.IO;
using Containerizer.Services.Interfaces;
namespace Containerizer.Services.Implementations
{
public class StreamOutService : IStreamOutService
{
private readonly IContainerPathService containerPathService;
private readonly ITarStreamService tarStreamService;
public StreamOutService(IContainerPathService containerPathService, ITarStreamService tarStreamService)
{
this.containerPathService = containerPathService;
this.tarStreamService = tarStreamService;
}
public Stream StreamOutFile(string id, string source)
{
string rootDir = containerPathService.GetContainerRoot(id);
string path = rootDir + source;
Stream stream = tarStreamService.WriteTarToStream(path);
return stream;
}
}
}``` |
06aafa28-df3d-49a2-878d-a4ad0c7fe5ad | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dokas.FluentStrings;
using Mozilla.CharDet;
namespace dokas.EncodingConverter.Logic
{
internal sealed class EncodingManager
{
private readonly FileManager _fileManager;
private static readonly IEnumerable<Encoding> _encodings;
private static readonly UniversalDetector _detector;
static EncodingManager()
{
_encodings = Encoding.GetEncodings().Select(e => e.GetEncoding()).ToArray();
_detector = new UniversalDetector();
}
public static IEnumerable<Encoding> Encodings
{
get { return _encodings; }
}
public EncodingManager(FileManager fileManager)
{
_fileManager = fileManager;
}
public async Task<Encoding> Resolve(string filePath)
{
_detector.Reset();
await Task.Factory.StartNew(() =>
{
var bytes = _fileManager.Load(filePath);
_detector.HandleData(bytes);
});
return !_detector.DetectedCharsetName.IsEmpty() ? Encoding.GetEncoding(_detector.DetectedCharsetName) : null;
}
public void Convert(string filePath, Encoding from, Encoding to)
{
var bytes = _fileManager.Load(filePath);
var convertedBytes = Encoding.Convert(from, to, bytes);
_fileManager.Save(filePath, convertedBytes);
}
}
}
```
Fix error with multithreaded UniversalDetector reseting | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dokas.FluentStrings;
using Mozilla.CharDet;
namespace dokas.EncodingConverter.Logic
{
internal sealed class EncodingManager
{
private readonly FileManager _fileManager;
private static readonly IEnumerable<Encoding> _encodings;
static EncodingManager()
{
_encodings = Encoding.GetEncodings().Select(e => e.GetEncoding()).ToArray();
}
public static IEnumerable<Encoding> Encodings
{
get { return _encodings; }
}
public EncodingManager(FileManager fileManager)
{
_fileManager = fileManager;
}
public async Task<Encoding> Resolve(string filePath)
{
UniversalDetector detector = null;
await Task.Factory.StartNew(() =>
{
var bytes = _fileManager.Load(filePath);
detector = new UniversalDetector();
detector.HandleData(bytes);
});
return !detector.DetectedCharsetName.IsEmpty() ? Encoding.GetEncoding(detector.DetectedCharsetName) : null;
}
public void Convert(string filePath, Encoding from, Encoding to)
{
if (from == null)
{
throw new ArgumentOutOfRangeException("from");
}
if (to == null)
{
throw new ArgumentOutOfRangeException("to");
}
var bytes = _fileManager.Load(filePath);
var convertedBytes = Encoding.Convert(from, to, bytes);
_fileManager.Save(filePath, convertedBytes);
}
}
}
``` |
7296bce5-e9ca-4825-a405-7f0180b658b0 | {
"language": "C#"
} | ```c#
using FabricStore.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FabricStore.Data.Migrations;
using FabricStore.Web.Infrastructure.Mapping;
using System.Reflection;
namespace FabricStore.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MigrationConfiguration>());
var automapperConfig = new AutoMapperConfig(Assembly.GetExecutingAssembly());
automapperConfig.Execute();
}
}
}
```
Set Razor to be the only view engine | ```c#
using FabricStore.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FabricStore.Data.Migrations;
using FabricStore.Web.Infrastructure.Mapping;
using System.Reflection;
namespace FabricStore.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MigrationConfiguration>());
var automapperConfig = new AutoMapperConfig(Assembly.GetExecutingAssembly());
automapperConfig.Execute();
}
}
}
``` |
0a9057ed-36f1-4467-ad8c-048bfabe64f1 | {
"language": "C#"
} | ```c#
#region
using System;
using BinaryTree.Models;
#endregion
namespace BinaryTree
{
internal class Program
{
private static void Main()
{
var binaryTree = new BinaryTree<int> {5, 3, 9, 1, -5, 0, 2};
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
const int val = 1;
Console.WriteLine("Removing value - {0}...", val);
binaryTree.Remove(val);
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
Console.ReadKey();
}
}
}```
Add binaryTree.Clear(); to binary tree test. | ```c#
#region
using System;
using BinaryTree.Models;
#endregion
namespace BinaryTree
{
internal class Program
{
private static void Main()
{
var binaryTree = new BinaryTree<int> {5, 3, 9, 1, -5, 0, 2};
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
const int val = 1;
Console.WriteLine("Removing value - {0}...", val);
binaryTree.Remove(val);
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
Console.ReadKey();
binaryTree.Clear();
}
}
}``` |
e61d1bac-7c7d-4311-87bc-b1d007619e8a | {
"language": "C#"
} | ```c#
using System;
namespace csnex
{
[Serializable()]
public class NeonException: ApplicationException
{
public NeonException() {
}
public NeonException(string message) : base(message) {
}
public NeonException(string message, params object[] args) : base(string.Format(message, args)) {
}
public NeonException(string message, System.Exception innerException) : base(message, innerException) {
}
}
[Serializable]
public class InvalidOpcodeException: NeonException
{
public InvalidOpcodeException() {
}
public InvalidOpcodeException(string message) : base(message) {
}
}
[Serializable]
public class BytecodeException: NeonException
{
public BytecodeException() {
}
public BytecodeException(string message) : base(message) {
}
}
[Serializable]
public class NotImplementedException: NeonException
{
public NotImplementedException() {
}
public NotImplementedException(string message) : base(message) {
}
}
}
```
Add Neon runtime information to NeonException | ```c#
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace csnex
{
[Serializable()]
public class NeonException: ApplicationException
{
public NeonException() {
}
public NeonException(string name, string info) : base(name) {
Name = name;
Info = info;
}
public NeonException(string message) : base(message) {
}
public NeonException(string message, params object[] args) : base(string.Format(message, args)) {
}
public NeonException(string message, System.Exception innerException) : base(message, innerException) {
}
// Satisfy Warning CA2240 to implement a GetObjectData() to our custom exception type.
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null) {
throw new ArgumentNullException("info");
}
info.AddValue("NeonException", Name);
info.AddValue("NeonInfo", Info);
base.GetObjectData(info, context);
}
public string Name;
public string Info;
}
[Serializable]
public class InvalidOpcodeException: NeonException
{
public InvalidOpcodeException() {
}
public InvalidOpcodeException(string message) : base(message) {
}
}
[Serializable]
public class BytecodeException: NeonException
{
public BytecodeException() {
}
public BytecodeException(string message) : base(message) {
}
}
[Serializable]
public class NotImplementedException: NeonException
{
public NotImplementedException() {
}
public NotImplementedException(string message) : base(message) {
}
}
[Serializable]
public class NeonRuntimeException: NeonException
{
public NeonRuntimeException()
{
}
public NeonRuntimeException(string name, string info) : base(name, info)
{
}
}
}
``` |
1cba2c52-c742-43b9-b28e-536b09249c8f | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Addins;
namespace MonoDevelop.Addins.Tasks
{
public abstract class AddinTask : Task
{
[Required]
public string ConfigDir { get; set; }
[Required]
public string AddinsDir { get; set; }
[Required]
public string DatabaseDir { get; set; }
[Required]
public string BinDir { get; set; }
protected bool InitializeAddinRegistry ()
{
if (string.IsNullOrEmpty (ConfigDir))
Log.LogError ("ConfigDir must be specified");
if (string.IsNullOrEmpty (AddinsDir))
Log.LogError ("AddinsDir must be specified");
if (string.IsNullOrEmpty (DatabaseDir))
Log.LogError ("DatabaseDir must be specified");
if (string.IsNullOrEmpty (BinDir))
Log.LogError ("BinDir must be specified");
Registry = new AddinRegistry (
ConfigDir,
BinDir,
AddinsDir,
DatabaseDir
);
Log.LogMessage (MessageImportance.Normal, "Updating addin database at {0}", DatabaseDir);
Registry.Update (new LogProgressStatus (Log, 2));
return !Log.HasLoggedErrors;
}
protected AddinRegistry Registry { get; private set; }
}
}
```
Fix use of private addin registry | ```c#
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Addins;
namespace MonoDevelop.Addins.Tasks
{
public abstract class AddinTask : Task
{
[Required]
public string ConfigDir { get; set; }
[Required]
public string AddinsDir { get; set; }
[Required]
public string DatabaseDir { get; set; }
[Required]
public string BinDir { get; set; }
protected bool InitializeAddinRegistry ()
{
if (string.IsNullOrEmpty (ConfigDir))
Log.LogError ("ConfigDir must be specified");
if (string.IsNullOrEmpty (AddinsDir))
Log.LogError ("AddinsDir must be specified");
if (string.IsNullOrEmpty (DatabaseDir))
Log.LogError ("DatabaseDir must be specified");
if (string.IsNullOrEmpty (BinDir))
Log.LogError ("BinDir must be specified");
ConfigDir = Path.GetFullPath (ConfigDir);
BinDir = Path.GetFullPath (BinDir);
AddinsDir = Path.GetFullPath (AddinsDir);
DatabaseDir = Path.GetFullPath (DatabaseDir);
Registry = new AddinRegistry (
ConfigDir,
BinDir,
AddinsDir,
DatabaseDir
);
Log.LogMessage (MessageImportance.Normal, "Updating addin database at {0}", DatabaseDir);
Registry.Update (new LogProgressStatus (Log, 2));
return !Log.HasLoggedErrors;
}
protected AddinRegistry Registry { get; private set; }
}
}
``` |
9f9682f5-4427-439b-a5dd-53aa4c6ffc6d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
//public Dictionary<String, JToken> fields = new Dictionary<string, JToken>();
}
}
```
Support fields and highlights in responses | ```c#
using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>();
public Dictionary<string, IEnumerable<string>> highlight;
}
}
``` |
cf127745-89fe-4b24-b4f4-b099e86158a1 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wslib;
using wslib.Protocol;
namespace LocalServer
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;
var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
using (var listener = new WebSocketListener(listenerOptions, appFunc))
{
listener.StartAccepting();
Console.ReadLine();
}
}
private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
throw new NotImplementedException(); // TODO: log
}
private static async Task appFunc(IWebSocket webSocket)
{
while (webSocket.IsConnected())
{
using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
{
if (msg != null)
{
using (var ms = new MemoryStream())
{
await msg.ReadStream.CopyToAsync(ms);
var text = Encoding.UTF8.GetString(ms.ToArray());
using (var w = await webSocket.CreateMessageWriter(MessageType.Text, CancellationToken.None))
{
await w.WriteMessageAsync(ms.ToArray(), 0, (int)ms.Length, CancellationToken.None);
}
}
}
}
}
}
}
}```
Update local echo server to work with binary messages | ```c#
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using wslib;
namespace LocalServer
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;
var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
using (var listener = new WebSocketListener(listenerOptions, appFunc))
{
listener.StartAccepting();
Console.ReadLine();
}
}
private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
//Console.WriteLine(unobservedTaskExceptionEventArgs.Exception);
}
private static async Task appFunc(IWebSocket webSocket)
{
while (webSocket.IsConnected())
{
using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
{
if (msg == null) continue;
using (var ms = new MemoryStream())
{
await msg.ReadStream.CopyToAsync(ms);
byte[] array = ms.ToArray();
using (var w = await webSocket.CreateMessageWriter(msg.Type, CancellationToken.None))
{
await w.WriteMessageAsync(array, 0, array.Length, CancellationToken.None);
}
}
}
}
}
}
}``` |
e8a5f44b-2e49-4710-aee6-dc6dbff02c8c | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Resources;
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("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
```
Set Treenumerable version to 1.0.0 | ```c#
using System.Reflection;
using System.Resources;
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("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
``` |
0bf4a286-a95d-41b5-86b8-d2dc44037db7 | {
"language": "C#"
} | ```c#
namespace UnwindMC.Analysis
{
public class Function
{
public Function(ulong address)
{
Address = address;
Status = FunctionStatus.Created;
}
public ulong Address { get; }
public FunctionStatus Status { get; set; }
}
public enum FunctionStatus
{
Created,
BoundsResolved,
BoundsNotResolvedInvalidAddress,
BoundsNotResolvedIncompleteGraph,
}
}
```
Add flow tree body to the function | ```c#
using System;
using System.Collections.Generic;
using UnwindMC.Analysis.Flow;
using UnwindMC.Analysis.IL;
namespace UnwindMC.Analysis
{
public class Function
{
private List<IBlock> _blocks;
public Function(ulong address)
{
Address = address;
Status = FunctionStatus.Created;
}
public ulong Address { get; }
public FunctionStatus Status { get; set; }
public IReadOnlyList<IBlock> Blocks => _blocks;
public ILInstruction FirstInstruction
{
get
{
if (_blocks == null || _blocks.Count == 0)
{
return null;
}
var seq = _blocks[0] as SequentialBlock;
if (seq != null)
{
return seq.Instructions[0];
}
var loop = _blocks[0] as LoopBlock;
if (loop != null)
{
return loop.Condition;
}
var cond = _blocks[0] as ConditionalBlock;
if (cond != null)
{
return cond.Condition;
}
throw new InvalidOperationException("Unknown block type");
}
}
public void ResolveBody(InstructionGraph graph)
{
if (Status != FunctionStatus.BoundsResolved)
{
throw new InvalidOperationException("Cannot resolve function body when bounds are not resolved");
}
_blocks = FlowAnalyzer.Analyze(ILDecompiler.Decompile(graph, Address));
Status = FunctionStatus.BodyResolved;
}
}
public enum FunctionStatus
{
Created,
BoundsResolved,
BoundsNotResolvedInvalidAddress,
BoundsNotResolvedIncompleteGraph,
BodyResolved,
}
}
``` |
4a30122a-e6c0-4790-bda9-cbf03f37c7a9 | {
"language": "C#"
} | ```c#
using System;
using System.Text;
namespace SCPI.Display
{
public class DISPLAY_GRID : ICommand
{
public string Description => "Set or query the grid type of screen display.";
public string Grid { get; private set; }
private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };
public string Command(params string[] parameters)
{
var cmd = ":DISPlay:GRID";
if (parameters.Length > 0)
{
var grid = parameters[0];
cmd = $"{cmd} {grid}";
}
else
{
cmd += "?";
}
return cmd;
}
public string HelpMessage()
{
var syntax = nameof(DISPLAY_GRID) + "\n" +
nameof(DISPLAY_GRID) + " <grid>";
var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
var example = "Example: " + nameof(DISPLAY_GRID) + "?";
return $"{syntax}\n{parameters}\n{example}";
}
public bool Parse(byte[] data)
{
if (data != null)
{
Grid = Encoding.ASCII.GetString(data).Trim();
if (Array.Exists(gridRange, g => g.Equals(Grid)))
{
return true;
}
}
Grid = null;
return false;
}
}
}
```
Change example to contain default values | ```c#
using System;
using System.Text;
namespace SCPI.Display
{
public class DISPLAY_GRID : ICommand
{
public string Description => "Set or query the grid type of screen display.";
public string Grid { get; private set; }
private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };
public string Command(params string[] parameters)
{
var cmd = ":DISPlay:GRID";
if (parameters.Length > 0)
{
var grid = parameters[0];
cmd = $"{cmd} {grid}";
}
else
{
cmd += "?";
}
return cmd;
}
public string HelpMessage()
{
var syntax = nameof(DISPLAY_GRID) + "\n" +
nameof(DISPLAY_GRID) + " <grid>";
var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
var example = "Example: " + nameof(DISPLAY_GRID) + " FULL";
return $"{syntax}\n{parameters}\n{example}";
}
public bool Parse(byte[] data)
{
if (data != null)
{
Grid = Encoding.ASCII.GetString(data).Trim();
if (Array.Exists(gridRange, g => g.Equals(Grid)))
{
return true;
}
}
Grid = null;
return false;
}
}
}
``` |
44f07d0f-b338-41b2-b5e3-2079eae07466 | {
"language": "C#"
} | ```c#
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
{
/* todo: remove hard coding of email addresses */
private static readonly EmailAddress U21Coordinator = new EmailAddress("ndu21c@croquet-australia.com.au", "Croquet Australia - National Co-ordinator Under 21 Croquet");
private static readonly EmailAddress[] BCC =
{
U21Coordinator,
new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia")
};
public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
: base(emailMessageSettings, U21Coordinator, BCC)
{
}
protected override string GetTemplateName(EntrySubmitted entrySubmitted)
{
return "EOI";
}
}
}```
Fix BCC for EOI emails | ```c#
using System.Linq;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
{
/* todo: remove hard coding of email addresses */
private static readonly EmailAddress U21Coordinator = new EmailAddress("ndu21c@croquet-australia.com.au", "Croquet Australia - National Co-ordinator Under 21 Croquet");
private static readonly EmailAddress[] BCC =
{
U21Coordinator,
new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia")
};
public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
: base(emailMessageSettings, U21Coordinator, GetBCC(emailMessageSettings))
{
}
protected override string GetTemplateName(EntrySubmitted entrySubmitted)
{
return "EOI";
}
private static EmailAddress[] GetBCC(EmailMessageSettings emailMessageSettings)
{
return emailMessageSettings.Bcc.Any() ? BCC : new EmailAddress[] {};
}
}
}``` |
30338871-fb06-4bab-9c3c-bcced00dbbe8 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Tests
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class TraktConfigurationTests
{
[TestMethod]
public void TestTraktConfigurationDefaultConstructor()
{
var client = new TraktClient();
client.Configuration.ApiVersion.Should().Be(2);
client.Configuration.UseStagingApi.Should().BeFalse();
client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/");
client.Configuration.UseStagingApi = true;
client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/");
}
}
}
```
Fix issues due to merge conflict. | ```c#
namespace TraktApiSharp.Tests
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class TraktConfigurationTests
{
[TestMethod]
public void TestTraktConfigurationDefaultConstructor()
{
var client = new TraktClient();
client.Configuration.ApiVersion.Should().Be(2);
client.Configuration.UseStagingUrl.Should().BeFalse();
client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/");
client.Configuration.UseStagingUrl = true;
client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/");
}
}
}
``` |
f05ed092-563b-4372-b8b9-360f87ebad79 | {
"language": "C#"
} | ```c#
using System;
using FormsToolkit;
using Xamarin.Forms;
namespace ToolkitTests
{
public class App : Application
{
public App()
{
var messagingCenter = new Button
{
Text = "Messaging Center",
Command = new Command(()=>MainPage.Navigation.PushAsync(new MessagingServicePage()))
};
var line = new EntryLine
{
Placeholder = "This nifty place for entering text!",
HorizontalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.FillAndExpand,
Text = "",
FontSize = 30,
BorderColor = Color.Red
};
// The root page of your application
MainPage = new NavigationPage(new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(32,32,32,32),
Children =
{
messagingCenter,
line
}
}
});
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
```
Add sample of data trigger | ```c#
using System;
using FormsToolkit;
using Xamarin.Forms;
namespace ToolkitTests
{
public class App : Application
{
public App()
{
var messagingCenter = new Button
{
Text = "Messaging Center",
Command = new Command(()=>MainPage.Navigation.PushAsync(new MessagingServicePage()))
};
var line = new EntryLine
{
Placeholder = "This nifty place for entering text!",
HorizontalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.FillAndExpand,
Text = "",
FontSize = 30,
BorderColor = Color.Red
};
var trigger = new Trigger(typeof(EntryLine));
trigger.Property = EntryLine.IsFocusedProperty;
trigger.Value = true;
Setter setter = new Setter();
setter.Property = EntryLine.BorderColorProperty;
setter.Value = Color.Yellow;
trigger.Setters.Add(setter);
line.Triggers.Add(trigger);
var line2 = new EntryLine
{
PlaceholderColor = Color.Orange,
Placeholder = "This nifty place for entering text!",
HorizontalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.FillAndExpand,
Text = "",
FontSize = 10,
BorderColor = Color.Red
};
// The root page of your application
MainPage = new NavigationPage(new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(32,32,32,32),
Children =
{
messagingCenter,
line,
line2
}
}
});
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
``` |
3d0c375a-4892-4e22-827c-2192545ad8e5 | {
"language": "C#"
} | ```c#
using BusinessObjects.Validators;
namespace FatturaElettronicaPA.Validators
{
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public class FModalitaPagamentoValidator : DomainValidator
{
private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP17].";
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public FModalitaPagamentoValidator() : this(null, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description)
{
Domain = new[]
{
"MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13",
"MP14", "MP15", "MP16", "MP17"
};
}
}
}
```
Update ModalitaPagamento validator with MP18..21 values | ```c#
using BusinessObjects.Validators;
namespace FatturaElettronicaPA.Validators
{
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public class FModalitaPagamentoValidator : DomainValidator
{
private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP21].";
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public FModalitaPagamentoValidator() : this(null, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description)
{
Domain = new[]
{
"MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13",
"MP14", "MP15", "MP16", "MP17", "MP18", "MP19", "MP20", "MP21"
};
}
}
}
``` |
3a05e76e-7f73-4ded-9a0f-732c2474c5d6 | {
"language": "C#"
} | ```c#
// Copyright 2013 Xamarin Inc.
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSUrlCredential {
public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty)
{
if (IsDirectBinding) {
Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust);
} else {
Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust);
}
}
}
}```
Fix MonoMac/MonoTouch (for MonoMac builds) | ```c#
// Copyright 2013 Xamarin Inc.
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSUrlCredential {
public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty)
{
if (IsDirectBinding) {
Handle = Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust);
} else {
Handle = Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust);
}
}
}
}``` |
4750b8e3-0482-4fae-ac6d-58e66c20729b | {
"language": "C#"
} | ```c#
using System;
namespace DesktopWidgets.Helpers
{
public static class DateTimeSyncHelper
{
public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay,
bool syncHour, bool syncMinute, bool syncSecond)
{
var endDateTime = dateTime;
endDateTime = new DateTime(
syncYear
? DateTime.Now.Year
: endDateTime.Year,
syncMonth
? DateTime.Now.Month
: endDateTime.Month,
syncDay
? DateTime.Now.Day
: endDateTime.Day,
syncHour
? DateTime.Now.Hour
: endDateTime.Hour,
syncMinute
? DateTime.Now.Minute
: endDateTime.Minute,
syncSecond
? DateTime.Now.Second
: endDateTime.Second,
endDateTime.Kind);
if (syncYear && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddYears(1);
if (syncMonth && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMonths(1);
if (syncDay && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddDays(1);
if (syncHour && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddHours(1);
if (syncMinute && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMinutes(1);
if (syncSecond && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddSeconds(1);
return endDateTime;
}
}
}```
Change "Countdown" syncing priority order | ```c#
using System;
namespace DesktopWidgets.Helpers
{
public static class DateTimeSyncHelper
{
public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay,
bool syncHour, bool syncMinute, bool syncSecond)
{
var endDateTime = dateTime;
endDateTime = new DateTime(
syncYear
? DateTime.Now.Year
: endDateTime.Year,
syncMonth
? DateTime.Now.Month
: endDateTime.Month,
syncDay
? DateTime.Now.Day
: endDateTime.Day,
syncHour
? DateTime.Now.Hour
: endDateTime.Hour,
syncMinute
? DateTime.Now.Minute
: endDateTime.Minute,
syncSecond
? DateTime.Now.Second
: endDateTime.Second,
endDateTime.Kind);
if (syncSecond && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddSeconds(1);
if (syncMinute && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMinutes(1);
if (syncHour && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddHours(1);
if (syncDay && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddDays(1);
if (syncMonth && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMonths(1);
if (syncYear && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddYears(1);
return endDateTime;
}
}
}``` |
b0c76e73-5bd0-43d4-938d-45048a0a1e00 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class PostsService: IPostService
{
private readonly IRepository<Post> postsRepository;
private readonly IUnitOfWork unitOfWork;
public PostsService(
IRepository<Post> postsRepository,
IUnitOfWork unitOfWork)
{
if (postsRepository == null)
{
throw new ArgumentNullException("postsRepository");
}
if (unitOfWork == null)
{
throw new ArgumentNullException("unitOfWorks");
}
this.postsRepository = postsRepository;
this.unitOfWork = unitOfWork;
}
public Post GetPostById(string id)
{
return this.postsRepository.GetById(id);
}
}
}
```
Add get top to service | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class PostsService : IPostService
{
private readonly IRepository<Post> postsRepository;
private readonly IUnitOfWork unitOfWork;
public PostsService(
IRepository<Post> postsRepository,
IUnitOfWork unitOfWork)
{
if (postsRepository == null)
{
throw new ArgumentNullException("postsRepository");
}
if (unitOfWork == null)
{
throw new ArgumentNullException("unitOfWorks");
}
this.postsRepository = postsRepository;
this.unitOfWork = unitOfWork;
}
public Post GetPostById(string id)
{
return this.postsRepository.GetById(id);
}
public IEnumerable<Post> GetTopPosts(int countOfPosts)
{
var res =
this.postsRepository.GetAll(
(Post post) => true,
(Post post) => post.Votes, true)
.Take(countOfPosts);
return res;
}
}
}
``` |
9d0bbe55-2701-4ade-84ed-53b08c71a691 | {
"language": "C#"
} | ```c#
namespace SilentHunter
{
public static class Encoding
{
/// <summary>
/// The default encoding to use for parsing Silent Hunter game files.
/// </summary>
public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding(1252);
}
}```
Use ISO encoding, for cross platform | ```c#
namespace SilentHunter
{
public static class Encoding
{
/// <summary>
/// The default encoding to use for parsing Silent Hunter game files.
/// </summary>
public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding("ISO-8859-1");
}
}``` |
31373911-2aa7-4f82-aa9e-50c9f856cf56 | {
"language": "C#"
} | ```c#
using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;
namespace MQTTnet.Adapter
{
public class MqttConnectingFailedException : MqttCommunicationException
{
public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode)
: base($"Connecting with MQTT server failed ({resultCode.ToString()}).")
{
Result = resultCode;
}
public MqttClientAuthenticateResult Result { get; }
public MqttClientConnectResultCode ResultCode => Result.ResultCode;
}
}
```
Correct to print right result | ```c#
using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;
namespace MQTTnet.Adapter
{
public class MqttConnectingFailedException : MqttCommunicationException
{
public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode)
: base($"Connecting with MQTT server failed ({resultCode.ResultCode.ToString()}).")
{
Result = resultCode;
}
public MqttClientAuthenticateResult Result { get; }
public MqttClientConnectResultCode ResultCode => Result.ResultCode;
}
}
``` |
1becac2c-c0c3-4847-ab6a-732a63d1c6ec | {
"language": "C#"
} | ```c#
using System;
using Xunit;
namespace CSharpInternals.ExceptionHandling
{
public class Basics
{
[Fact]
public void Test()
{
Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException());
}
// Fact - ToString allocates a lot, especially with AggregateException
// http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448
private static void ThrowsNullReferenceException() => throw null;
}
}```
Use more proper name for test | ```c#
using System;
using Xunit;
namespace CSharpInternals.ExceptionHandling
{
public class Basics
{
[Fact]
public void ThrowsNull()
{
Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException());
}
// Fact - ToString allocates a lot, especially with AggregateException
// http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448
private static void ThrowsNullReferenceException() => throw null;
}
}``` |
614d1e39-bcfc-4cb2-bfe1-00b9b9776f7b | {
"language": "C#"
} | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using PELoaderLib;
namespace EOLib.Graphics
{
public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
{
public void PopulateCollectionWithStandardGFX()
{
var gfxTypes = Enum.GetValues(typeof(GFXTypes)).OfType<GFXTypes>();
var modules = gfxTypes.ToDictionary(type => type, CreateGFXFile);
foreach(var modulePair in modules)
Add(modulePair.Key, modulePair.Value);
}
private IPEFile CreateGFXFile(GFXTypes file)
{
var number = ((int)file).ToString("D3");
var fName = Path.Combine("gfx", "gfx" + number + ".egf");
return new PEFile(fName);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~PEFileCollection()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
foreach (var pair in this)
pair.Value.Dispose();
}
}
public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
{
void PopulateCollectionWithStandardGFX();
}
}
```
Fix resource leak that occurred when any GFX files were missing from GFX folder | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using System.IO;
using PELoaderLib;
namespace EOLib.Graphics
{
public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
{
public void PopulateCollectionWithStandardGFX()
{
var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes));
foreach (var type in gfxTypes)
Add(type, CreateGFXFile(type));
}
private IPEFile CreateGFXFile(GFXTypes file)
{
var number = ((int)file).ToString("D3");
var fName = Path.Combine("gfx", "gfx" + number + ".egf");
return new PEFile(fName);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~PEFileCollection()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
foreach (var pair in this)
pair.Value.Dispose();
}
}
public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
{
void PopulateCollectionWithStandardGFX();
}
}
``` |
35bf2b5c-38e6-4c2e-83af-42c9b3110ec5 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Localisation;
using osu.Game.Overlays.Settings.Sections.Maintenance;
namespace osu.Game.Overlays.Settings.Sections
{
public class MaintenanceSection : SettingsSection
{
public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader;
public override Drawable CreateIcon() => new SpriteIcon
{
Icon = FontAwesome.Solid.Wrench
};
public MaintenanceSection()
{
Children = new Drawable[]
{
new BeatmapSettings(),
new SkinSettings(),
new CollectionsSettings(),
new ScoreSettings()
};
}
}
}
```
Remove one more nullable disable | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Localisation;
using osu.Game.Overlays.Settings.Sections.Maintenance;
namespace osu.Game.Overlays.Settings.Sections
{
public class MaintenanceSection : SettingsSection
{
public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader;
public override Drawable CreateIcon() => new SpriteIcon
{
Icon = FontAwesome.Solid.Wrench
};
public MaintenanceSection()
{
Children = new Drawable[]
{
new BeatmapSettings(),
new SkinSettings(),
new CollectionsSettings(),
new ScoreSettings()
};
}
}
}
``` |
1bec4ccd-387a-459b-b27b-01d39169550a | {
"language": "C#"
} | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*
* Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">,
* Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC
* APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps,
* this leads to spurious errors in the Errors List pane, even though there aren't actually any
* errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy
* the design-time build.
*
* TODO: Track down what is triggering the unwanted design-time build and find out how to disable it.
* Then this file can be removed entirely.
*/
using System;
namespace Microsoft.AspNetCore.Mvc
{
public interface IUrlHelper { }
public interface IViewComponentHelper { }
}
namespace Microsoft.AspNetCore.Mvc.Razor
{
public class RazorPage<T> { }
namespace Internal
{
public class RazorInjectAttributeAttribute : Attribute { }
}
}
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public interface IJsonHelper { }
public interface IHtmlHelper<T> { }
}
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public interface IModelExpressionProvider { }
}
```
Stop spurious VS "cannot override ExecuteAsync" errors even if you don't specify a base class | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*
* Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">,
* Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC
* APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps,
* this leads to spurious errors in the Errors List pane, even though there aren't actually any
* errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy
* the design-time build.
*
* TODO: Track down what is triggering the unwanted design-time build and find out how to disable it.
* Then this file can be removed entirely.
*/
using System;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Mvc
{
public interface IUrlHelper { }
public interface IViewComponentHelper { }
}
namespace Microsoft.AspNetCore.Mvc.Razor
{
public class RazorPage<T> {
// This needs to be defined otherwise the VS tooling complains that there's no ExecuteAsync method to override.
public virtual Task ExecuteAsync()
=> throw new NotImplementedException($"Blazor components do not implement {nameof(ExecuteAsync)}.");
}
namespace Internal
{
public class RazorInjectAttributeAttribute : Attribute { }
}
}
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public interface IJsonHelper { }
public interface IHtmlHelper<T> { }
}
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public interface IModelExpressionProvider { }
}
``` |
c81ca550-9031-4b02-99e1-a359905f210c | {
"language": "C#"
} | ```c#
using System.Windows;
namespace OpenSage.DataViewer
{
public partial class App : Application
{
}
}
```
Set thread culture to InvariantCulture on startup | ```c#
using System.Windows;
using System.Globalization;
using System.Threading;
namespace OpenSage.DataViewer
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
base.OnStartup(e);
}
}
}
``` |
bd734bc1-c0c8-4250-9cfb-66fa895d53ae | {
"language": "C#"
} | ```c#
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Perspex;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using System;
using System.Collections.Generic;
namespace Core2D.Perspex.Presenters
{
public class CachedContentPresenter : ContentPresenter
{
private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();
private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();
public static void Register(Type type, Func<Control> create) => _factory[type] = create;
public CachedContentPresenter()
{
this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value));
}
public Control GetControl(Type type)
{
Control control;
_cache.TryGetValue(type, out control);
if (control == null)
{
Func<Control> createInstance;
_factory.TryGetValue(type, out createInstance);
control = createInstance?.Invoke();
if (control != null)
{
_cache[type] = control;
}
}
return control;
}
public void SetContent(object value)
{
Control control = null;
if (value != null)
{
control = GetControl(value.GetType());
}
this.Content = control;
}
}
}
```
Throw excpetion when type is not found | ```c#
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Perspex;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using System;
using System.Collections.Generic;
namespace Core2D.Perspex.Presenters
{
public class CachedContentPresenter : ContentPresenter
{
private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();
private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();
public static void Register(Type type, Func<Control> create) => _factory[type] = create;
public CachedContentPresenter()
{
this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value));
}
public Control GetControl(Type type)
{
Control control;
_cache.TryGetValue(type, out control);
if (control == null)
{
Func<Control> createInstance;
_factory.TryGetValue(type, out createInstance);
control = createInstance?.Invoke();
if (control != null)
{
_cache[type] = control;
}
else
{
throw new Exception($"Can not find factory method for type: {type}");
}
}
return control;
}
public void SetContent(object value)
{
Control control = null;
if (value != null)
{
control = GetControl(value.GetType());
}
this.Content = control;
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.