doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
5d4dae62-e0bb-4182-9155-ce9b790662c4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace NeedDotNet.Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Use camel case for JSON data.
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
```
Clean up Web Api Config Commit | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace NeedDotNet.Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
``` |
971fa17d-edc8-44a7-b3b5-74b78e1a742d | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
using System;
namespace Lockstep
{
public class Buff
{
protected int Duration;
protected int Timer;
protected LSAgent Target;
internal int ID {get; set;}
public bool Active {get; private set;}
public void Initialize (int duration, LSAgent target) {
Duration = duration;
Timer = 0;
Target = target;
Target.AddBuff(this);
Active = true;
}
protected virtual void OnInitialize () {
}
public void Simulate () {
Timer++;
OnSimulate ();
if (Timer > Duration) {
Deactivate ();
}
}
protected virtual void OnSimulate () {
}
public void Deactivate () {
Target.RemoveBuff(this);
Active = false;
}
protected virtual void OnDeactivate () {
}
}
}```
Fix functions not being called | ```c#
using UnityEngine;
using System.Collections;
using System;
namespace Lockstep
{
public class Buff
{
protected int Duration;
protected int Timer;
protected LSAgent Target;
internal int ID {get; set;}
public bool Active {get; private set;}
public void Initialize (int duration, LSAgent target) {
Duration = duration;
Timer = 0;
Target = target;
Target.AddBuff(this);
Active = true;
this.OnInitialize();
}
protected virtual void OnInitialize () {
}
public void Simulate () {
Timer++;
OnSimulate ();
if (Timer > Duration) {
Deactivate ();
}
}
protected virtual void OnSimulate () {
}
public void Deactivate () {
Target.RemoveBuff(this);
Active = false;
this.OnDeactivate();
}
protected virtual void OnDeactivate () {
}
}
}``` |
5b6567c0-aad1-4739-b2ef-8ced0fb00180 | {
"language": "C#"
} | ```c#
using EntityFrameworkCore.RawSQLExtensions.SqlQuery;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace EntityFrameworkCore.RawSQLExtensions.Extensions
{
public static class DatabaseFacadeExtensions
{
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, params SqlParameter[] parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters);
}
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, IEnumerable<SqlParameter> parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters.ToArray());
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, params SqlParameter[] parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters);
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, IEnumerable<SqlParameter> parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters.ToArray());
}
}
}
```
Add ISqlQuery<object> SqlQuery(this DatabaseFacade database, Type type, string sqlQuery, params SqlParameter[] parameters) | ```c#
using EntityFrameworkCore.RawSQLExtensions.SqlQuery;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace EntityFrameworkCore.RawSQLExtensions.Extensions
{
public static class DatabaseFacadeExtensions
{
public static ISqlQuery<object> SqlQuery(this DatabaseFacade database, Type type, string sqlQuery, params SqlParameter[] parameters)
{
var tsrq = typeof(SqlRawQuery<>).MakeGenericType(type);
return (ISqlQuery<object>)Activator.CreateInstance(tsrq, database, sqlQuery, parameters);
}
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, params SqlParameter[] parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters);
}
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, IEnumerable<SqlParameter> parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters.ToArray());
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, params SqlParameter[] parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters);
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, IEnumerable<SqlParameter> parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters.ToArray());
}
}
}``` |
abe3b3f4-c3fe-4947-a90b-a2f66d4642f2 | {
"language": "C#"
} | ```c#
using System;
namespace GUtils.IO
{
public static class FileSizes
{
public const UInt64 B = 1024;
public const UInt64 KiB = 1024 * B;
public const UInt64 MiB = 1024 * KiB;
public const UInt64 GiB = 1024 * MiB;
public const UInt64 TiB = 1024 * GiB;
public const UInt64 PiB = 1024 * TiB;
private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };
public static String Format ( UInt64 Size )
{
var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) );
return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}";
}
}
}
```
Add an option to set the number of decimal places that will be used in the formatting | ```c#
using System;
namespace GUtils.IO
{
public static class FileSizes
{
public const UInt64 B = 1024;
public const UInt64 KiB = 1024 * B;
public const UInt64 MiB = 1024 * KiB;
public const UInt64 GiB = 1024 * MiB;
public const UInt64 TiB = 1024 * GiB;
public const UInt64 PiB = 1024 * TiB;
private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };
public static String Format ( UInt64 Size )
{
var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) );
return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}";
}
public static String Format ( UInt64 Size, Int32 decimals )
{
var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) );
return $"{Math.Round ( Size / ( Math.Pow ( B, i ) ), decimals )} {_suffixes[i]}";
}
}
}
``` |
2628f4db-b789-43ac-8323-cc8308fc39bf | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Fixie.Execution;
namespace Fixie.VisualStudio.TestAdapter
{
[DefaultExecutorUri(Executor.Id)]
[FileExtension(".exe")]
[FileExtension(".dll")]
public class Discoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger log, ITestCaseDiscoverySink discoverySink)
{
RemotingUtility.CleanUpRegisteredChannels();
foreach (var source in sources)
{
log.Info("Processing " + source);
try
{
var assemblyFullPath = Path.GetFullPath(source);
using (var environment = new ExecutionEnvironment(assemblyFullPath))
{
var discovery = environment.Create<DiscoveryProxy>();
foreach (var methodGroup in discovery.TestMethodGroups(assemblyFullPath))
{
discoverySink.SendTestCase(new TestCase(methodGroup.FullName, Executor.Uri, source)
{
DisplayName = methodGroup.FullName
});
}
}
}
catch (Exception exception)
{
log.Error(exception);
}
}
}
}
}
```
Remove population of Visual Studio's TestCase.DisplayName property during test discovery. This has no effect and is misleading. TestCase.FullyQualifiedName is set to the method group of a test method, but TestCase.DisplayName should only be set during execution time to the full name of a test case including input parameters. Setting TestCase.DisplayName at discovery time is meaningless. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Fixie.Execution;
namespace Fixie.VisualStudio.TestAdapter
{
[DefaultExecutorUri(Executor.Id)]
[FileExtension(".exe")]
[FileExtension(".dll")]
public class Discoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger log, ITestCaseDiscoverySink discoverySink)
{
RemotingUtility.CleanUpRegisteredChannels();
foreach (var source in sources)
{
log.Info("Processing " + source);
try
{
var assemblyFullPath = Path.GetFullPath(source);
using (var environment = new ExecutionEnvironment(assemblyFullPath))
{
var discovery = environment.Create<DiscoveryProxy>();
foreach (var methodGroup in discovery.TestMethodGroups(assemblyFullPath))
discoverySink.SendTestCase(new TestCase(methodGroup.FullName, Executor.Uri, source));
}
}
catch (Exception exception)
{
log.Error(exception);
}
}
}
}
}
``` |
7178f8bb-070f-4d0f-9a61-9a73a94ed89c | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners
{
public class SpinnerPlacementBlueprint : PlacementBlueprint
{
public new Spinner HitObject => (Spinner)base.HitObject;
private readonly SpinnerPiece piece;
private bool isPlacingEnd;
public SpinnerPlacementBlueprint()
: base(new Spinner { Position = OsuPlayfield.BASE_SIZE / 2 })
{
InternalChild = piece = new SpinnerPiece(HitObject) { Alpha = 0.5f };
}
protected override bool OnClick(ClickEvent e)
{
if (isPlacingEnd)
{
HitObject.EndTime = EditorClock.CurrentTime;
EndPlacement();
}
else
{
HitObject.StartTime = EditorClock.CurrentTime;
isPlacingEnd = true;
piece.FadeTo(1f, 150, Easing.OutQuint);
}
return true;
}
}
}
```
Fix spinners not starting placement with the first click | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners
{
public class SpinnerPlacementBlueprint : PlacementBlueprint
{
public new Spinner HitObject => (Spinner)base.HitObject;
private readonly SpinnerPiece piece;
private bool isPlacingEnd;
public SpinnerPlacementBlueprint()
: base(new Spinner { Position = OsuPlayfield.BASE_SIZE / 2 })
{
InternalChild = piece = new SpinnerPiece(HitObject) { Alpha = 0.5f };
}
protected override bool OnClick(ClickEvent e)
{
if (isPlacingEnd)
{
HitObject.EndTime = EditorClock.CurrentTime;
EndPlacement();
}
else
{
HitObject.StartTime = EditorClock.CurrentTime;
isPlacingEnd = true;
piece.FadeTo(1f, 150, Easing.OutQuint);
BeginPlacement();
}
return true;
}
}
}
``` |
86839d92-eb3d-458c-89b2-06c7c7e175b3 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
namespace NuGetConsole.Implementation.PowerConsole {
/// <summary>
/// Represents a host with extra info.
/// </summary>
class HostInfo : ObjectWithFactory<PowerConsoleWindow> {
Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; }
public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider)
: base(factory) {
UtilityMethods.ThrowIfArgumentNull(hostProvider);
this.HostProvider = hostProvider;
}
/// <summary>
/// Get the HostName attribute value of this host.
/// </summary>
public string HostName {
get { return HostProvider.Metadata.HostName; }
}
IWpfConsole _wpfConsole;
/// <summary>
/// Get/create the console for this host. If not already created, this
/// actually creates the (console, host) pair.
///
/// Note: Creating the console is handled by this package and mostly will
/// succeed. However, creating the host could be from other packages and
/// fail. In that case, this console is already created and can be used
/// subsequently in limited ways, such as displaying an error message.
/// </summary>
public IWpfConsole WpfConsole {
get {
if (_wpfConsole == null) {
_wpfConsole = Factory.WpfConsoleService.CreateConsole(
Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName);
_wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: false);
}
return _wpfConsole;
}
}
}
}```
Revert accidental change to @async flag. | ```c#
using System;
using System.Diagnostics;
namespace NuGetConsole.Implementation.PowerConsole {
/// <summary>
/// Represents a host with extra info.
/// </summary>
class HostInfo : ObjectWithFactory<PowerConsoleWindow> {
Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; }
public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider)
: base(factory) {
UtilityMethods.ThrowIfArgumentNull(hostProvider);
this.HostProvider = hostProvider;
}
/// <summary>
/// Get the HostName attribute value of this host.
/// </summary>
public string HostName {
get { return HostProvider.Metadata.HostName; }
}
IWpfConsole _wpfConsole;
/// <summary>
/// Get/create the console for this host. If not already created, this
/// actually creates the (console, host) pair.
///
/// Note: Creating the console is handled by this package and mostly will
/// succeed. However, creating the host could be from other packages and
/// fail. In that case, this console is already created and can be used
/// subsequently in limited ways, such as displaying an error message.
/// </summary>
public IWpfConsole WpfConsole {
get {
if (_wpfConsole == null) {
_wpfConsole = Factory.WpfConsoleService.CreateConsole(
Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName);
_wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: true);
}
return _wpfConsole;
}
}
}
}``` |
50425c65-c584-425e-8b24-3b6658b766e0 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. Any value 0 or less denotes a missing ID.
/// </summary>
/// <remarks>
/// Generally we use -1 when specifying "missing" in code, but values of 0 are also considered missing as the online source
/// is generally a MySQL autoincrement value, which can never be 0.
/// </remarks>
int OnlineID { get; }
}
}
```
Add a note about `OnlineID` potentially being zero in non-autoincrement cases | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. Any value 0 or less denotes a missing ID (except in special cases where autoincrement is not used, like rulesets).
/// </summary>
/// <remarks>
/// Generally we use -1 when specifying "missing" in code, but values of 0 are also considered missing as the online source
/// is generally a MySQL autoincrement value, which can never be 0.
/// </remarks>
int OnlineID { get; }
}
}
``` |
88dced53-d6a3-4ee4-bbea-fa26601b5ff0 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Globalization;
using Newtonsoft.Json;
using osu.Framework.Extensions;
namespace osu.Game.Online.API
{
[Serializable]
internal class OAuthToken
{
/// <summary>
/// OAuth 2.0 access token.
/// </summary>
[JsonProperty(@"access_token")]
public string AccessToken;
[JsonProperty(@"expires_in")]
public long ExpiresIn
{
get
{
return AccessTokenExpiry - DateTime.Now.ToUnixTimestamp();
}
set
{
AccessTokenExpiry = DateTime.Now.AddSeconds(value).ToUnixTimestamp();
}
}
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && ExpiresIn > 30;
public long AccessTokenExpiry;
/// <summary>
/// OAuth 2.0 refresh token.
/// </summary>
[JsonProperty(@"refresh_token")]
public string RefreshToken;
public override string ToString() => $@"{AccessToken}/{AccessTokenExpiry.ToString(NumberFormatInfo.InvariantInfo)}/{RefreshToken}";
public static OAuthToken Parse(string value)
{
try
{
string[] parts = value.Split('/');
return new OAuthToken
{
AccessToken = parts[0],
AccessTokenExpiry = long.Parse(parts[1], NumberFormatInfo.InvariantInfo),
RefreshToken = parts[2]
};
}
catch
{
}
return null;
}
}
}
```
Fix refresh tokens not working correctly | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Globalization;
using Newtonsoft.Json;
using osu.Framework.Extensions;
namespace osu.Game.Online.API
{
[Serializable]
internal class OAuthToken
{
/// <summary>
/// OAuth 2.0 access token.
/// </summary>
[JsonProperty(@"access_token")]
public string AccessToken;
[JsonProperty(@"expires_in")]
public long ExpiresIn
{
get
{
return AccessTokenExpiry - DateTime.Now.ToUnixTimestamp();
}
set
{
AccessTokenExpiry = DateTime.Now.AddSeconds(value).ToUnixTimestamp();
}
}
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && ExpiresIn > 30;
public long AccessTokenExpiry;
/// <summary>
/// OAuth 2.0 refresh token.
/// </summary>
[JsonProperty(@"refresh_token")]
public string RefreshToken;
public override string ToString() => $@"{AccessToken}|{AccessTokenExpiry.ToString(NumberFormatInfo.InvariantInfo)}|{RefreshToken}";
public static OAuthToken Parse(string value)
{
try
{
string[] parts = value.Split('|');
return new OAuthToken
{
AccessToken = parts[0],
AccessTokenExpiry = long.Parse(parts[1], NumberFormatInfo.InvariantInfo),
RefreshToken = parts[2]
};
}
catch
{
}
return null;
}
}
}
``` |
c2cba6e4-e220-4979-b20e-2bec9a2e3066 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NProcessPipe.DependencyAnalysis
{
public class Node<T>
{
public Node(T data)
{
//Index = -1;
Data = data;
}
public T Data { get; private set; }
public bool Equals(Node<T> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Data, Data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Node<T>)) return false;
return Equals((Node<T>)obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public override string ToString()
{
return Data.ToString();
}
//public void SetIndex(int index)
//{
// Index = index;
//}
//public void SetLowLink(int lowlink)
//{
// LowLink = lowlink;
//}
//public int Index { get; private set; }
//public int LowLink { get; private set; }
}
}
```
Clean up dependency node class | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NProcessPipe.DependencyAnalysis
{
public class Node<T>
{
public Node(T data)
{
Data = data;
}
public T Data { get; private set; }
public bool Equals(Node<T> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Data, Data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Node<T>)) return false;
return Equals((Node<T>)obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public override string ToString()
{
return Data.ToString();
}
}
}
``` |
db0bd608-33d6-4900-a5c1-9bd4f2633c9c | {
"language": "C#"
} | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CourseExerciseFiles.cs" company="CodeBlueDev">
// All rights reserved.
// </copyright>
// <summary>
// Represents a PluralSight Course's exercise files information.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CodeBlueDev.PluralSight.Core.Models
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// Represents a PluralSight Course's exercise files information.
/// </summary>
/// <example>
/// {
/// "exerciseFilesUrl": "http://s.pluralsight.com/course-materials/windows-forms-best-practices/866AB96258/20140926213054/windows-forms-best-practices.zip?userHandle=aaf74aa9-49b7-415b-ba2d-bdc49b285671"
/// }
/// </example>
[DataContract]
[Serializable]
public class CourseExerciseFiles
{
/// <summary>
/// Gets or sets the Exercise Files Url for a PluralSight Course.
/// </summary>
[DataMember(Name = "exerciseFilesUrl")]
public string ExerciseFilesUrl { get; set; }
}
}
```
Update userHandle to be consistent in all examples instead of random | ```c#
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CourseExerciseFiles.cs" company="CodeBlueDev">
// All rights reserved.
// </copyright>
// <summary>
// Represents a PluralSight Course's exercise files information.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CodeBlueDev.PluralSight.Core.Models
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// Represents a PluralSight Course's exercise files information.
/// </summary>
/// <example>
/// {
/// "exerciseFilesUrl": "http://s.pluralsight.com/course-materials/windows-forms-best-practices/866AB96258/20140926213054/windows-forms-best-practices.zip?userHandle=03b9fd64-819c-4def-a610-52457b0479ec"
/// }
/// </example>
[DataContract]
[Serializable]
public class CourseExerciseFiles
{
/// <summary>
/// Gets or sets the Exercise Files Url for a PluralSight Course.
/// </summary>
[DataMember(Name = "exerciseFilesUrl")]
public string ExerciseFilesUrl { get; set; }
}
}
``` |
a79aefb1-8ac9-47e8-b99e-d9417ae1a08e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
var lines = new List<string>();
using (var stringReader = new StringReader(text))
{
string line;
line = stringReader.ReadLine();
while (line != null)
{
yield return line;
line = stringReader.ReadLine();
}
}
}
}
}
```
Add extension method to translate text coordinates | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
var lines = new List<string>();
using (var stringReader = new StringReader(text))
{
string line;
line = stringReader.ReadLine();
while (line != null)
{
yield return line;
line = stringReader.ReadLine();
}
}
}
public static IScriptExtent Translate(this IScriptExtent extent, int lineDelta, int columnDelta)
{
var newStartLineNumber = extent.StartLineNumber + lineDelta;
if (newStartLineNumber < 1)
{
throw new ArgumentException(
"Invalid line delta. Resulting start line number must be greather than 1.");
}
var newStartColumnNumber = extent.StartColumnNumber + columnDelta;
var newEndColumnNumber = extent.EndColumnNumber + columnDelta;
if (newStartColumnNumber < 1 || newEndColumnNumber < 1)
{
throw new ArgumentException(@"Invalid column delta.
Resulting start column and end column number must be greather than 1.");
}
return new ScriptExtent(
new ScriptPosition(
extent.File,
newStartLineNumber,
newStartColumnNumber,
extent.StartScriptPosition.Line),
new ScriptPosition(
extent.File,
extent.EndLineNumber + lineDelta,
newEndColumnNumber,
extent.EndScriptPosition.Line));
}
}
}
``` |
3c734977-102f-4b26-b3d6-549fcc2e02a7 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net.Sockets.Tests;
using System.Net.Test.Common;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Performance.Tests
{
[Trait("Perf", "true")]
public class SocketPerformanceAsyncTests
{
private readonly ITestOutputHelper _log;
private readonly int _iterations = 1;
public SocketPerformanceAsyncTests(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
string env = Environment.GetEnvironmentVariable("SOCKETSTRESS_ITERATIONS");
if (env != null)
{
_iterations = int.Parse(env);
}
}
[ActiveIssue(13349, TestPlatforms.OSX)]
[OuterLoop]
[Fact]
public void SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync()
{
SocketImplementationType serverType = SocketImplementationType.Async;
SocketImplementationType clientType = SocketImplementationType.Async;
int iterations = 200 * _iterations;
int bufferSize = 256;
int socket_instances = 200;
var test = new SocketPerformanceTests(_log);
// Run in Stress mode no expected time to complete.
test.ClientServerTest(
serverType,
clientType,
iterations,
bufferSize,
socket_instances);
}
}
}
```
Decrease number of socket instances in SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net.Sockets.Tests;
using System.Net.Test.Common;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Performance.Tests
{
[Trait("Perf", "true")]
public class SocketPerformanceAsyncTests
{
private readonly ITestOutputHelper _log;
private readonly int _iterations = 1;
public SocketPerformanceAsyncTests(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
string env = Environment.GetEnvironmentVariable("SOCKETSTRESS_ITERATIONS");
if (env != null)
{
_iterations = int.Parse(env);
}
}
[ActiveIssue(13349, TestPlatforms.OSX)]
[OuterLoop]
[Fact]
public void SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync()
{
SocketImplementationType serverType = SocketImplementationType.Async;
SocketImplementationType clientType = SocketImplementationType.Async;
int iterations = 200 * _iterations;
int bufferSize = 256;
int socket_instances = 20;
var test = new SocketPerformanceTests(_log);
// Run in Stress mode no expected time to complete.
test.ClientServerTest(
serverType,
clientType,
iterations,
bufferSize,
socket_instances);
}
}
}
``` |
50f6d0b3-9911-48e4-b35b-85c6fe841a1b | {
"language": "C#"
} | ```c#
using System;
namespace ClosedXML.Excel
{
internal class XLWorksheetInternals : IDisposable
{
public XLWorksheetInternals(
XLCellsCollection cellsCollection,
XLColumnsCollection columnsCollection,
XLRowsCollection rowsCollection,
XLRanges mergedRanges
)
{
CellsCollection = cellsCollection;
ColumnsCollection = columnsCollection;
RowsCollection = rowsCollection;
MergedRanges = mergedRanges;
}
public XLCellsCollection CellsCollection { get; private set; }
public XLColumnsCollection ColumnsCollection { get; private set; }
public XLRowsCollection RowsCollection { get; private set; }
public XLRanges MergedRanges { get; internal set; }
public void Dispose()
{
ColumnsCollection.Clear();
RowsCollection.Clear();
MergedRanges.RemoveAll();
}
}
}
```
Clear CellsCollection on WorksheetInternals disposal to make it easier to GC to collect unused references | ```c#
using System;
namespace ClosedXML.Excel
{
internal class XLWorksheetInternals : IDisposable
{
public XLWorksheetInternals(
XLCellsCollection cellsCollection,
XLColumnsCollection columnsCollection,
XLRowsCollection rowsCollection,
XLRanges mergedRanges
)
{
CellsCollection = cellsCollection;
ColumnsCollection = columnsCollection;
RowsCollection = rowsCollection;
MergedRanges = mergedRanges;
}
public XLCellsCollection CellsCollection { get; private set; }
public XLColumnsCollection ColumnsCollection { get; private set; }
public XLRowsCollection RowsCollection { get; private set; }
public XLRanges MergedRanges { get; internal set; }
public void Dispose()
{
CellsCollection.Clear();
ColumnsCollection.Clear();
RowsCollection.Clear();
MergedRanges.RemoveAll();
}
}
}
``` |
3a937a64-7ccf-4f7f-b854-eee1e71b2782 | {
"language": "C#"
} | ```c#
---
Title: HTML
Description: Report format to create reports in any text based format (HTML, Markdown, ...).
---
<p>@Html.Raw(Model.String(DocsKeys.Description))</p>
<p>
Support for creating reports in any text based format like HTML or Markdown is implemented in the
<a href="https://www.nuget.org/packages/Cake.Issues.Reporting.Generic" target="_blank">Cake.Issues.Reporting.Generic addin</a>.
</p>
@Html.Partial("_ChildPages")```
Fix title for generic report format | ```c#
---
Title: Generic
Description: Report format to create reports in any text based format (HTML, Markdown, ...).
---
<p>@Html.Raw(Model.String(DocsKeys.Description))</p>
<p>
Support for creating reports in any text based format like HTML or Markdown is implemented in the
<a href="https://www.nuget.org/packages/Cake.Issues.Reporting.Generic" target="_blank">Cake.Issues.Reporting.Generic addin</a>.
</p>
@Html.Partial("_ChildPages")``` |
619c5655-f8f8-4dc6-a586-ba733ae90878 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// The head of a <see cref="DrawableHoldNote"/>.
/// </summary>
public class DrawableHoldNoteHead : DrawableNote
{
protected override ManiaSkinComponents Component => ManiaSkinComponents.HoldNoteHead;
public DrawableHoldNoteHead(DrawableHoldNote holdNote)
: base(holdNote.HitObject.Head)
{
}
public void UpdateResult() => base.UpdateResult(true);
protected override void UpdateInitialTransforms()
{
base.UpdateInitialTransforms();
// This hitobject should never expire, so this is just a safe maximum.
LifetimeEnd = LifetimeStart + 30000;
}
public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note
public override void OnReleased(ManiaAction action)
{
}
}
}
```
Fix mania hold note heads hiding when frozen | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// The head of a <see cref="DrawableHoldNote"/>.
/// </summary>
public class DrawableHoldNoteHead : DrawableNote
{
protected override ManiaSkinComponents Component => ManiaSkinComponents.HoldNoteHead;
public DrawableHoldNoteHead(DrawableHoldNote holdNote)
: base(holdNote.HitObject.Head)
{
}
public void UpdateResult() => base.UpdateResult(true);
protected override void UpdateInitialTransforms()
{
base.UpdateInitialTransforms();
// This hitobject should never expire, so this is just a safe maximum.
LifetimeEnd = LifetimeStart + 30000;
}
protected override void UpdateHitStateTransforms(ArmedState state)
{
// suppress the base call explicitly.
// the hold note head should never change its visual state on its own due to the "freezing" mechanic
// (when hit, it remains visible in place at the judgement line; when dropped, it will scroll past the line).
// it will be hidden along with its parenting hold note when required.
}
public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note
public override void OnReleased(ManiaAction action)
{
}
}
}
``` |
9914ea53-549c-4ab5-b730-cb8c67aca4b5 | {
"language": "C#"
} | ```c#
using System.IO;
using Htc.Vita.Core.Runtime;
namespace Htc.Vita.Core.Util
{
public static partial class Extract
{
public static bool FromFileToIcon(FileInfo fromFile, FileInfo toIcon)
{
if (!Platform.IsWindows)
{
return false;
}
return Windows.FromFileToIconInPlatform(fromFile, toIcon);
}
}
}
```
Add API to extract resource from assembly | ```c#
using System;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using Htc.Vita.Core.Log;
using Htc.Vita.Core.Runtime;
namespace Htc.Vita.Core.Util
{
public static partial class Extract
{
public static bool FromFileToIcon(
FileInfo fromFile,
FileInfo toIcon)
{
if (!Platform.IsWindows)
{
return false;
}
return Windows.FromFileToIconInPlatform(fromFile, toIcon);
}
public static bool FromAssemblyToFileByResourceName(
string byResourceName,
FileInfo toFile,
CompressionType compressionType)
{
if (string.IsNullOrWhiteSpace(byResourceName))
{
return false;
}
if (toFile == null)
{
return false;
}
try
{
var binaryDirectory = toFile.Directory;
if (binaryDirectory != null && !binaryDirectory.Exists)
{
binaryDirectory.Create();
}
var assembly = Assembly.GetCallingAssembly();
var doesResourceExist = false;
foreach (var name in assembly.GetManifestResourceNames())
{
if (byResourceName.Equals(name))
{
doesResourceExist = true;
}
}
if (!doesResourceExist)
{
return false;
}
using (var stream = assembly.GetManifestResourceStream(byResourceName))
{
if (stream == null)
{
return false;
}
if (compressionType == CompressionType.Gzip)
{
using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
{
using (var fileStream = toFile.OpenWrite())
{
gZipStream.CopyTo(fileStream);
}
}
}
else
{
using (var fileStream = toFile.OpenWrite())
{
stream.CopyTo(fileStream);
}
}
}
return true;
}
catch (Exception e)
{
Logger.GetInstance(typeof(Extract)).Error("Can not extract resource \"" + byResourceName + "\" to \"" + toFile + "\": " + e.Message);
}
return false;
}
public enum CompressionType
{
None,
Gzip
}
}
}
``` |
2d49e6aa-aa6b-487c-bd8b-63ffb95f1fa9 | {
"language": "C#"
} | ```c#
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamMusic.Interfaces;
using XamMusic.ViewModels;
namespace XamMusic.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CreatePlaylistPopup : PopupPage
{
public CreatePlaylistPopup()
{
InitializeComponent();
}
private async void CreatePlaylist(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(PlaylistNameEntry.Text))
{
DependencyService.Get<IPlaylistManager>().CreatePlaylist("Untitled Playlist");
}
else
{
DependencyService.Get<IPlaylistManager>().CreatePlaylist(PlaylistNameEntry.Text);
}
MenuViewModel.Instance.Refresh();
await Navigation.PopAllPopupAsync(true);
}
}
}
```
Append numbers to created playlist names if taken | ```c#
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamMusic.Interfaces;
using XamMusic.ViewModels;
namespace XamMusic.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CreatePlaylistPopup : PopupPage
{
public CreatePlaylistPopup()
{
InitializeComponent();
}
private async void CreatePlaylist(object sender, EventArgs e)
{
string title;
if (String.IsNullOrWhiteSpace(PlaylistNameEntry.Text))
{
title = "Untitled Playlist";
}
else
{
title = PlaylistNameEntry.Text;
}
if (MenuViewModel.Instance.PlaylistItems.Where(r => r.Playlist?.Title == title).Count() > 0)
{
int i = 1;
while (MenuViewModel.Instance.PlaylistItems.Where(q => q.Playlist?.Title == $"{title}{i}").Count() > 0)
{
i++;
}
title = $"{title}{i}";
}
DependencyService.Get<IPlaylistManager>().CreatePlaylist(title);
MenuViewModel.Instance.Refresh();
await Navigation.PopAllPopupAsync(true);
}
}
}
``` |
546a4937-5a51-4288-9174-e913058c9c80 | {
"language": "C#"
} | ```c#
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NpmTests {
[TestClass]
public class NpmExecuteCommandTests {
// https://nodejstools.codeplex.com/workitem/1575
[TestMethod, Priority(0), Timeout(180000)]
public async Task TestNpmCommandProcessExitSucceeds() {
var npmPath = NpmHelpers.GetPathToNpm();
var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));
for (int j = 0; j < 200; j++) {
await NpmHelpers.ExecuteNpmCommandAsync(
redirector,
npmPath,
null,
new[] {"config", "get", "registry"},
null);
}
}
}
}
```
Disable locally failiny npm command test | ```c#
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NpmTests {
[TestClass]
public class NpmExecuteCommandTests {
// https://nodejstools.codeplex.com/workitem/1575
[Ignore]
[TestMethod, Priority(0), Timeout(180000)]
public async Task TestNpmCommandProcessExitSucceeds() {
var npmPath = NpmHelpers.GetPathToNpm();
var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));
for (int j = 0; j < 200; j++) {
await NpmHelpers.ExecuteNpmCommandAsync(
redirector,
npmPath,
null,
new[] {"config", "get", "registry"},
null);
}
}
}
}
``` |
aea23439-ad47-4af9-96f6-c196bb585778 | {
"language": "C#"
} | ```c#
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
// ReSharper disable UnusedType.Global
namespace Content.Server.Database;
public sealed class DesignTimeContextFactoryPostgres : IDesignTimeDbContextFactory<PostgresServerDbContext>
{
public PostgresServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<PostgresServerDbContext>();
optionsBuilder.UseNpgsql(args[0]);
return new PostgresServerDbContext(optionsBuilder.Options);
}
}
public sealed class DesignTimeContextFactorySqlite : IDesignTimeDbContextFactory<SqliteServerDbContext>
{
public SqliteServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<SqliteServerDbContext>();
optionsBuilder.UseSqlite(args[0]);
return new SqliteServerDbContext(optionsBuilder.Options);
}
}
```
Fix arg parsing for design time db contexts. | ```c#
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
// ReSharper disable UnusedType.Global
namespace Content.Server.Database;
public sealed class DesignTimeContextFactoryPostgres : IDesignTimeDbContextFactory<PostgresServerDbContext>
{
public PostgresServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<PostgresServerDbContext>();
optionsBuilder.UseNpgsql("Server=localhost");
return new PostgresServerDbContext(optionsBuilder.Options);
}
}
public sealed class DesignTimeContextFactorySqlite : IDesignTimeDbContextFactory<SqliteServerDbContext>
{
public SqliteServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<SqliteServerDbContext>();
optionsBuilder.UseSqlite("Data Source=:memory:");
return new SqliteServerDbContext(optionsBuilder.Options);
}
}
``` |
f8523455-2495-43d3-b3fd-cb706310659a | {
"language": "C#"
} | ```c#
using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MusicPickerService.Models;
using StackExchange.Redis;
namespace MusicPickerService.Hubs
{
public class MusicHub
{
private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
private ApplicationDbContext dbContext = new ApplicationDbContext();
private IDatabase Store
{
get
{
return redis.GetDatabase();
}
}
public void Queue(int deviceId, int[] trackIds)
{
string queue = String.Format("musichub.device.{0}.queue", deviceId);
string deviceQueue = String.Format("musichub.device.{0}.queue.device", deviceId);
Store.KeyDelete(queue);
Store.KeyDelete(deviceQueue);
foreach (int trackId in trackIds)
{
Store.ListRightPush(queue, trackId);
string trackDeviceId = (from dt in this.dbContext.DeviceTracks
where dt.DeviceId == deviceId && dt.TrackId == trackId
select dt.DeviceTrackId).First();
Store.ListRightPush(deviceQueue, trackDeviceId);
}
}
public void Play(int deviceId)
{
}
public void Pause(int deviceId)
{
}
public void Stop(int deviceId)
{
}
}
}```
Add inherit from Hub and Next | ```c#
using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MusicPickerService.Models;
using StackExchange.Redis;
using Microsoft.AspNet.SignalR;
namespace MusicPickerService.Hubs
{
public class MusicHub: Hub
{
private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
private ApplicationDbContext dbContext = new ApplicationDbContext();
private IDatabase Store
{
get
{
return redis.GetDatabase();
}
}
public void Queue(int deviceId, int[] trackIds)
{
string queue = String.Format("musichub.device.{0}.queue", deviceId);
string deviceQueue = String.Format("musichub.device.{0}.queue.device", deviceId);
Store.KeyDelete(queue);
Store.KeyDelete(deviceQueue);
foreach (int trackId in trackIds)
{
Store.ListRightPush(queue, trackId);
string trackDeviceId = (from dt in this.dbContext.DeviceTracks
where dt.DeviceId == deviceId && dt.TrackId == trackId
select dt.DeviceTrackId).First();
Store.ListRightPush(deviceQueue, trackDeviceId);
}
}
public void Play(int deviceId)
{
}
public void Pause(int deviceId)
{
}
public void Next(int deviceId)
{
}
}
}``` |
b2f9ae01-461c-43e1-be95-557d3af3493a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Web.Compilation;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharp;
using WizardCentralServer.Model.Dtos;
using WizardWebApi.Models.Objects;
namespace WizardWebApi.Controllers
{
public class TweetsController : ApiController
{
//
// GET: api/Tweets
public IHttpActionResult Get()
{
//
var tokenRequest = new RestRequest("https://api.twitter.com/oauth2/token")
{
Method = Method.POST
};
tokenRequest.AddHeader("Authorization",
ConfigurationManager.AppSettings["TwitterAuthKey"]);
tokenRequest.AddParameter("grant_type", "client_credentials");
var tokenResult = new RestClient().Execute(tokenRequest);
var accessToken = JsonConvert.DeserializeObject<AccessToken>(tokenResult.Content);
var request = new RestRequest(@"https://api.twitter.com/1.1/search/tweets.json?q=%23shrek&lang=en&result_type=recent&count=20")
{
Method = Method.GET
};
request.AddHeader("Authorization", "Bearer " + accessToken.token);
var result = new RestClient().Execute(request);
var tweets = JsonConvert.DeserializeObject<TwitterStatusResults>(result.Content);
return Ok(tweets.Statuses);
}
}
}
```
Change tweet query to include fictional wizards | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Web.Compilation;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharp;
using WizardCentralServer.Model.Dtos;
using WizardWebApi.Models.Objects;
namespace WizardWebApi.Controllers
{
public class TweetsController : ApiController
{
//
// GET: api/Tweets
public IHttpActionResult Get()
{
//
var tokenRequest = new RestRequest("https://api.twitter.com/oauth2/token")
{
Method = Method.POST
};
tokenRequest.AddHeader("Authorization",
ConfigurationManager.AppSettings["TwitterAuthKey"]);
tokenRequest.AddParameter("grant_type", "client_credentials");
var tokenResult = new RestClient().Execute(tokenRequest);
var accessToken = JsonConvert.DeserializeObject<AccessToken>(tokenResult.Content);
var request = new RestRequest(@"https://api.twitter.com/1.1/search/tweets.json?q=%23shrek%20OR%20%23dumbledore%20OR%20%23gandalf%20OR%20%23snape&lang=en&result_type=recent&count=20")
{
Method = Method.GET
};
request.AddHeader("Authorization", "Bearer " + accessToken.token);
var result = new RestClient().Execute(request);
var tweets = JsonConvert.DeserializeObject<TwitterStatusResults>(result.Content);
return Ok(tweets.Statuses);
}
}
}
``` |
b1949188-9525-405f-91cc-f6c51d5e139f | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
namespace Atata.Tests
{
[TestFixture]
public class AtataContextBuilderTests
{
[Test]
public void AtataContextBuilder_Build_WithoutDriver()
{
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
AtataContext.Configure().Build());
Assert.That(exception.Message, Does.Contain("no driver is specified"));
}
}
}
```
Add AtataContextBuilder_OnDriverCreated and AtataContextBuilder_OnDriverCreated_RestartDriver tests | ```c#
using System;
using NUnit.Framework;
namespace Atata.Tests
{
public class AtataContextBuilderTests : UITestFixtureBase
{
[Test]
public void AtataContextBuilder_Build_WithoutDriver()
{
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
AtataContext.Configure().Build());
Assert.That(exception.Message, Does.Contain("no driver is specified"));
}
[Test]
public void AtataContextBuilder_OnDriverCreated()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(driver =>
{
executionsCount++;
}).
Build();
Assert.That(executionsCount, Is.EqualTo(1));
}
[Test]
public void AtataContextBuilder_OnDriverCreated_RestartDriver()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(() =>
{
executionsCount++;
}).
Build();
AtataContext.Current.RestartDriver();
Assert.That(executionsCount, Is.EqualTo(2));
}
}
}
``` |
585f7401-0b37-4540-a237-60deac5033e3 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace Treenumerable
{
internal static class EnumerableExtensions
{
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
VirtualTree<T> virtualTree)
{
foreach (T node in source)
{
yield return virtualTree.ShallowCopy(node);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker,
IEqualityComparer<T> comparer)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root, comparer);
}
}
}
}
```
Change EnumerableExtensions to partial class | ```c#
using System.Collections.Generic;
namespace Treenumerable
{
internal static partial class EnumerableExtensions
{
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
VirtualTree<T> virtualTree)
{
foreach (T node in source)
{
yield return virtualTree.ShallowCopy(node);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker,
IEqualityComparer<T> comparer)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root, comparer);
}
}
}
}
``` |
80441c12-4c5f-40d2-adf3-dd5b6796a8b0 | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
namespace ActivatorWebSite
{
public class RegularController : Controller
{
public void Index()
{
// This verifies that ModelState and Context are activated.
if (ModelState.IsValid)
{
Context.Response.WriteAsync("Hello world").Wait();
}
}
}
}```
Fix an inadvertent 204 in activator tests | ```c#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
namespace ActivatorWebSite
{
public class RegularController : Controller
{
public async Task<EmptyResult> Index()
{
// This verifies that ModelState and Context are activated.
if (ModelState.IsValid)
{
await Context.Response.WriteAsync("Hello world");
}
return new EmptyResult();
}
}
}``` |
ff90735b-53b8-45a7-b5cc-38dc8b8e8306 | {
"language": "C#"
} | ```c#
using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
namespace StackExchange.DataExplorer.Controllers
{
public class TutorialController : StackOverflowController
{
[StackRoute("tutorial")]
public ActionResult Index()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/intro-to-databases")]
public ActionResult DatabasePrimer()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/intro-to-queries")]
public ActionResult Queries()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-basics")]
public ActionResult QueryBasics()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-joins")]
public ActionResult QueryJoins()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-parameters")]
public ActionResult QueryParameters()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-computations")]
public ActionResult QueryComputations()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/next-steps")]
public ActionResult NextSteps()
{
SetHeader("Tutorial");
return View();
}
}
}```
Add titles to tutorial pages | ```c#
using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
namespace StackExchange.DataExplorer.Controllers
{
public class TutorialController : StackOverflowController
{
[StackRoute("tutorial")]
public ActionResult Index()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Tutorial - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/intro-to-databases")]
public ActionResult DatabasePrimer()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Introduction to Databases - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/intro-to-queries")]
public ActionResult Queries()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Introduction to Queries - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-basics")]
public ActionResult QueryBasics()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Basics - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-joins")]
public ActionResult QueryJoins()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Joins - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-parameters")]
public ActionResult QueryParameters()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Parameters - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-computations")]
public ActionResult QueryComputations()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Computations - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/next-steps")]
public ActionResult NextSteps()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Next Steps - Stack Exchange Data Explorer";
return View();
}
}
}
``` |
d4b1673d-5f1c-4f8f-8f60-e7ee172e7f80 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace KafkaNet
{
public interface IKafkaTcpSocket : IDisposable
{
Uri ClientUri { get; }
Task<byte[]> ReadAsync(int readSize);
Task<byte[]> ReadAsync(int readSize, CancellationToken cancellationToken);
Task WriteAsync(byte[] buffer, int offset, int count);
Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
}
}
```
Add documentation and convenience func to interface | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
namespace KafkaNet
{
public interface IKafkaTcpSocket : IDisposable
{
/// <summary>
/// The Uri to the connected server.
/// </summary>
Uri ClientUri { get; }
/// <summary>
/// Read a certain byte array size return only when all bytes received.
/// </summary>
/// <param name="readSize">The size in bytes to receive from server.</param>
/// <returns>Returns a byte[] array with the size of readSize.</returns>
Task<byte[]> ReadAsync(int readSize);
/// <summary>
/// Read a certain byte array size return only when all bytes received.
/// </summary>
/// <param name="readSize">The size in bytes to receive from server.</param>
/// <param name="cancellationToken">A cancellation token which will cancel the request.</param>
/// <returns>Returns a byte[] array with the size of readSize.</returns>
Task<byte[]> ReadAsync(int readSize, CancellationToken cancellationToken);
/// <summary>
/// Convenience function to write full buffer data to the server.
/// </summary>
/// <param name="buffer">The buffer data to send.</param>
/// <returns>Returns Task handle to the write operation.</returns>
Task WriteAsync(byte[] buffer);
/// <summary>
/// Write the buffer data to the server.
/// </summary>
/// <param name="buffer">The buffer data to send.</param>
/// <param name="offset">The offset to start the read from the buffer.</param>
/// <param name="count">The length of data to read off the buffer.</param>
/// <returns>Returns Task handle to the write operation.</returns>
Task WriteAsync(byte[] buffer, int offset, int count);
/// <summary>
/// Write the buffer data to the server.
/// </summary>
/// <param name="buffer">The buffer data to send.</param>
/// <param name="offset">The offset to start the read from the buffer.</param>
/// <param name="count">The length of data to read off the buffer.</param>
/// <param name="cancellationToken">A cancellation token which will cancel the request.</param>
/// <returns>Returns Task handle to the write operation.</returns>
Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
}
}
``` |
607ec540-a5a8-4ca1-a741-ac6935da285a | {
"language": "C#"
} | ```c#
using BenchmarkDotNet.Running;
namespace Benchmark.NetCore
{
internal class Program
{
private static void Main(string[] args)
{
//BenchmarkRunner.Run<MetricCreationBenchmarks>();
//BenchmarkRunner.Run<SerializationBenchmarks>();
//BenchmarkRunner.Run<LabelBenchmarks>();
//BenchmarkRunner.Run<HttpExporterBenchmarks>();
//BenchmarkRunner.Run<SummaryBenchmarks>();
BenchmarkRunner.Run<MetricPusherBenchmarks>();
}
}
}
```
Add commandline switch to benchmark to avoid need for rebuilds | ```c#
using BenchmarkDotNet.Running;
namespace Benchmark.NetCore
{
internal class Program
{
private static void Main(string[] args)
{
// Give user possibility to choose which benchmark to run.
// Can be overridden from the command line with the --filter option.
new BenchmarkSwitcher(typeof(Program).Assembly).Run(args);
}
}
}
``` |
a4f5e32d-c20a-4e00-b3a8-bdca0d5c0d59 | {
"language": "C#"
} | ```c#
namespace Rackspace.VisualStudio.CloudExplorer.Files
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VSDesigner.ServerExplorer;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
public class CloudFilesEndpointNode : EndpointNode
{
public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
: base(identity, serviceCatalog, endpoint)
{
}
protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
{
Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
}
private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
{
return new CloudFilesContainerNode(provider, container, containerCdn);
}
private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
{
CloudFilesProvider provider = CreateProvider();
List<Container> containers = new List<Container>();
containers.AddRange(await Task.Run(() => provider.ListContainers()));
return Tuple.Create(provider, containers.ToArray());
}
private CloudFilesProvider CreateProvider()
{
return new CloudFilesProvider(Identity, Endpoint.Region, null, null);
}
}
}
```
Increase the default Cloud Files connection limit | ```c#
namespace Rackspace.VisualStudio.CloudExplorer.Files
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VSDesigner.ServerExplorer;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
public class CloudFilesEndpointNode : EndpointNode
{
public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
: base(identity, serviceCatalog, endpoint)
{
}
protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
{
Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
}
private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
{
return new CloudFilesContainerNode(provider, container, containerCdn);
}
private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
{
CloudFilesProvider provider = CreateProvider();
List<Container> containers = new List<Container>();
containers.AddRange(await Task.Run(() => provider.ListContainers()));
return Tuple.Create(provider, containers.ToArray());
}
private CloudFilesProvider CreateProvider()
{
CloudFilesProvider provider = new CloudFilesProvider(Identity, Endpoint.Region, null, null);
provider.ConnectionLimit = 50;
return provider;
}
}
}
``` |
d2232d92-c481-408f-8c7a-485bc4eed3b2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace Geode.Geometry
{
public class Polygon<T> : IGeoType
{
public string Type => "Polygon";
public IEnumerable<IEnumerable<T>> Coordinates { get; set; }
public Polygon(IEnumerable<IEnumerable<T>> coordinates)
{
Coordinates = coordinates;
}
}
}
```
Add non-generic polygon type that uses double type by default. | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace Geode.Geometry
{
public class Polygon: IGeoType
{
public string Type => "Polygon";
public IEnumerable<IEnumerable<double>> Coordinates { get; set; }
public Polygon(IEnumerable<IEnumerable<double>> coordinates)
{
Coordinates = coordinates;
}
}
public class Polygon<T> : IGeoType
{
public string Type => "Polygon";
public IEnumerable<IEnumerable<T>> Coordinates { get; set; }
public Polygon(IEnumerable<IEnumerable<T>> coordinates)
{
Coordinates = coordinates;
}
}
}
``` |
5271e4c6-1ca6-460f-803f-d413607be9c6 | {
"language": "C#"
} | ```c#
using System;
using System.Security.Cryptography.Pkcs;
namespace AuthenticodeLint.Rules
{
public class PublisherInformationPresentRule : IAuthenticodeRule
{
public int RuleId { get; } = 10004;
public string RuleName { get; } = "Publisher Information Rule";
public string ShortDescription { get; } = "Checks that the signature provided publisher information.";
public RuleResult Validate(Graph<SignerInfo> graph, SignatureLoggerBase verboseWriter)
{
var signatures = graph.VisitAll();
var result = RuleResult.Pass;
foreach(var signature in signatures)
{
PublisherInformation info = null;
foreach(var attribute in signature.SignedAttributes)
{
if (attribute.Oid.Value == KnownOids.OpusInfo)
{
info = new PublisherInformation(attribute.Values[0]);
break;
}
}
if (info == null)
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have any publisher information.");
}
if (string.IsNullOrWhiteSpace(info.Description))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying description.");
}
if (string.IsNullOrWhiteSpace(info.UrlLink))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying URL.");
}
}
return result;
}
}
}
```
Check for valid URI in publisher information. | ```c#
using System;
using System.Security.Cryptography.Pkcs;
namespace AuthenticodeLint.Rules
{
public class PublisherInformationPresentRule : IAuthenticodeRule
{
public int RuleId { get; } = 10004;
public string RuleName { get; } = "Publisher Information Rule";
public string ShortDescription { get; } = "Checks that the signature provided publisher information.";
public RuleResult Validate(Graph<SignerInfo> graph, SignatureLoggerBase verboseWriter)
{
var signatures = graph.VisitAll();
var result = RuleResult.Pass;
foreach(var signature in signatures)
{
PublisherInformation info = null;
foreach(var attribute in signature.SignedAttributes)
{
if (attribute.Oid.Value == KnownOids.OpusInfo)
{
info = new PublisherInformation(attribute.Values[0]);
break;
}
}
if (info == null)
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have any publisher information.");
}
if (string.IsNullOrWhiteSpace(info.Description))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying description.");
}
if (string.IsNullOrWhiteSpace(info.UrlLink))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying URL.");
}
Uri uri;
if (!Uri.TryCreate(info.UrlLink, UriKind.Absolute, out uri))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature's accompanying URL is not a valid URI.");
}
}
return result;
}
}
}
``` |
a9440d85-f353-46b1-b8ad-763ca4835f34 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceProvider
{
public static class SettingsManager
{
internal static void CheckForXmlFileDirectory(Func<string> getXmlFilePath, Action<string, string> messageForUser)
{
if (string.IsNullOrEmpty(DataStorage.Default.xmlFileDirectory))
{
messageForUser.Invoke("Please press OK and choose a folder to store your expenditure in", "Setup");
DataStorage.Default.xmlFileDirectory = getXmlFilePath.Invoke();
DataStorage.Default.Save();
}
}
}
}
```
Remove code involving MessageBox that did not belong in this class | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceProvider
{
public static class SettingsManager
{
internal static void CheckForXmlFileDirectory(Func<string> getXmlFilePath, Action<string, string> messageForUser)
{
if (string.IsNullOrEmpty(DataStorage.Default.xmlFileDirectory))
{
DataStorage.Default.xmlFileDirectory = getXmlFilePath.Invoke();
DataStorage.Default.Save();
}
}
}
}
``` |
2c00c584-f185-4aa2-bfcc-ab8ae4f566fb | {
"language": "C#"
} | ```c#
using System;
namespace NQuery.Language
{
public sealed class SyntaxTree
{
private readonly CompilationUnitSyntax _root;
private readonly TextBuffer _textBuffer;
private SyntaxTree(CompilationUnitSyntax root, TextBuffer textBuffer)
{
_root = root;
_textBuffer = textBuffer;
}
public static SyntaxTree ParseQuery(string source)
{
var parser = new Parser(source);
var query = parser.ParseRootQuery();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(query, textBuffer);
}
public static SyntaxTree ParseExpression(string source)
{
var parser = new Parser(source);
var expression = parser.ParseRootQuery();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(expression, textBuffer);
}
public CompilationUnitSyntax Root
{
get { return _root; }
}
public TextBuffer TextBuffer
{
get { return _textBuffer; }
}
}
}```
Fix bug where ParseExpression doesn't parse an expression but a query | ```c#
using System;
namespace NQuery.Language
{
public sealed class SyntaxTree
{
private readonly CompilationUnitSyntax _root;
private readonly TextBuffer _textBuffer;
private SyntaxTree(CompilationUnitSyntax root, TextBuffer textBuffer)
{
_root = root;
_textBuffer = textBuffer;
}
public static SyntaxTree ParseQuery(string source)
{
var parser = new Parser(source);
var query = parser.ParseRootQuery();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(query, textBuffer);
}
public static SyntaxTree ParseExpression(string source)
{
var parser = new Parser(source);
var expression = parser.ParseRootExpression();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(expression, textBuffer);
}
public CompilationUnitSyntax Root
{
get { return _root; }
}
public TextBuffer TextBuffer
{
get { return _textBuffer; }
}
}
}``` |
45a20374-cb18-49be-8ae7-6ca7f2bdbd49 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using UniProgramGen;
namespace UniProgramGen.Data
{
public class Requirements
{
public readonly double weight;
public readonly List<Helpers.TimeSlot> availableTimeSlots;
public readonly List<Room> requiredRooms;
public Requirements(double weight, List<Helpers.TimeSlot> availableTimeSlots, List<Room> requiredRooms)
{
this.weight = weight;
this.availableTimeSlots = availableTimeSlots;
this.requiredRooms = requiredRooms;
}
}
}
```
Add internal weight calculation for requirements | ```c#
using System.Collections.Generic;
using UniProgramGen;
using System.Linq;
namespace UniProgramGen.Data
{
public class Requirements
{
public const uint TOTAL_HOURS = 15;
public const uint TOTAL_WEEK_HOURS = 5 * TOTAL_HOURS;
public readonly double weight;
public readonly List<Helpers.TimeSlot> availableTimeSlots;
public readonly List<Room> requiredRooms;
private double internalWeight;
public Requirements(double weight, List<Helpers.TimeSlot> availableTimeSlots, List<Room> requiredRooms)
{
this.weight = weight;
this.availableTimeSlots = availableTimeSlots;
this.requiredRooms = requiredRooms;
}
internal void CalculateInternalWeight(int roomsLength)
{
var availableTime = availableTimeSlots.Aggregate((uint) 0, (total, timeSlot) => total + timeSlot.EndHour - timeSlot.StartHour);
internalWeight = ((availableTime / TOTAL_WEEK_HOURS) + (requiredRooms.Count / roomsLength)) / 2;
}
}
}
``` |
70e29bc1-9403-4920-80e8-52b1cec7206b | {
"language": "C#"
} | ```c#
using System.IO;
using Stranne.VasttrafikNET.Tests.Json;
namespace Stranne.VasttrafikNET.Tests.Helpers
{
public static class JsonHelper
{
public static string GetJson(JsonFile jsonFile)
{
var fileName = $"{jsonFile}.json";
var json = File.ReadAllText($@"Json\{fileName}");
return json;
}
}
}
```
Fix test json file path on unix systems | ```c#
using System.IO;
using Stranne.VasttrafikNET.Tests.Json;
namespace Stranne.VasttrafikNET.Tests.Helpers
{
public static class JsonHelper
{
public static string GetJson(JsonFile jsonFile)
{
var fileName = $"{jsonFile}.json";
var json = File.ReadAllText($@"Json/{fileName}");
return json;
}
}
}
``` |
76da2402-f4cf-451d-900f-fea8268d6b8d | {
"language": "C#"
} | ```c#
using AutoMapper;
namespace Caelan.Frameworks.Common.Classes
{
public static class GenericBuilder
{
public static BaseBuilder<TSource, TDestination> Create<TSource, TDestination>()
where TDestination : class, new()
where TSource : class, new()
{
var builder = new BaseBuilder<TSource, TDestination>();
if (Mapper.FindTypeMapFor<TSource, TDestination>() == null) Mapper.AddProfile(builder);
return builder;
}
}
}
```
Fix for searching for basebuilder already defined on all assemblies | ```c#
using System;
using System.Linq;
using System.Reflection;
using AutoMapper;
namespace Caelan.Frameworks.Common.Classes
{
public static class GenericBuilder
{
public static BaseBuilder<TSource, TDestination> Create<TSource, TDestination>()
where TDestination : class, new()
where TSource : class, new()
{
var builder = new BaseBuilder<TSource, TDestination>();
var customBuilder = Assembly.GetExecutingAssembly().GetReferencedAssemblies().OrderBy(t => t.Name).Select(Assembly.Load).SelectMany(assembly => assembly.GetTypes().Where(t => t.BaseType == builder.GetType())).SingleOrDefault();
if (customBuilder != null) builder = Activator.CreateInstance(customBuilder) as BaseBuilder<TSource, TDestination>;
if (Mapper.FindTypeMapFor<TSource, TDestination>() == null) Mapper.AddProfile(builder);
return builder;
}
}
}
``` |
e15d2f9f-9b94-4e2d-be3b-3da8fac24d8d | {
"language": "C#"
} | ```c#
/*
* Programmed by Umut Celenli umut@celenli.com
*/
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private const int maxBufferSize = 256;
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[maxBufferSize];
}
public FileHeader GetFileHeader(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, maxBufferSize);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer));
}
}
}```
Add stream variant of GetFileHeader() | ```c#
/*
* Programmed by Umut Celenli umut@celenli.com
*/
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private const int maxBufferSize = 256;
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[maxBufferSize];
}
public FileHeader GetFileHeader(Stream stream)
{
stream.Read(Buffer, 0, maxBufferSize);
return this.List.FirstOrDefault(mime => mime.Check(Buffer));
}
public FileHeader GetFileHeader(string file)
{
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
return GetFileHeader(stream);
}
}
}
}``` |
03369650-9c6a-439d-8f66-17d54b04b64c | {
"language": "C#"
} | ```c#
using Ensconce.Database;
using Ensconce.Helpers;
using System.Data.SqlClient;
namespace Ensconce.Cli
{
internal static class DatabaseInteraction
{
internal static void DoDeployment()
{
SqlConnectionStringBuilder connStr = null;
if (!string.IsNullOrEmpty(Arguments.ConnectionString))
{
connStr = new SqlConnectionStringBuilder(Arguments.ConnectionString.Render());
}
else if (!string.IsNullOrEmpty(Arguments.DatabaseName))
{
connStr = Database.Database.GetLocalConnectionStringFromDatabaseName(Arguments.DatabaseName.Render());
}
Logging.Log("Deploying scripts from {0} using connection string {1}", Arguments.DeployFrom, connStr.ConnectionString);
var database = new Database.Database(connStr, Arguments.WarnOnOneTimeScriptChanges)
{
WithTransaction = Arguments.WithTransaction,
OutputPath = Arguments.RoundhouseOutputPath
};
database.Deploy(Arguments.DeployFrom, Arguments.DatabaseRepository.Render(), Arguments.DropDatabase, Arguments.DatabaseCommandTimeout);
}
}
}
```
Redact DB password in logging | ```c#
using Ensconce.Database;
using Ensconce.Helpers;
using System.Data.SqlClient;
namespace Ensconce.Cli
{
internal static class DatabaseInteraction
{
internal static void DoDeployment()
{
SqlConnectionStringBuilder connStr = null;
if (!string.IsNullOrEmpty(Arguments.ConnectionString))
{
connStr = new SqlConnectionStringBuilder(Arguments.ConnectionString.Render());
}
else if (!string.IsNullOrEmpty(Arguments.DatabaseName))
{
connStr = Database.Database.GetLocalConnectionStringFromDatabaseName(Arguments.DatabaseName.Render());
}
Logging.Log("Deploying scripts from {0} using connection string {1}", Arguments.DeployFrom, RedactPassword(connStr));
var database = new Database.Database(connStr, Arguments.WarnOnOneTimeScriptChanges)
{
WithTransaction = Arguments.WithTransaction,
OutputPath = Arguments.RoundhouseOutputPath
};
database.Deploy(Arguments.DeployFrom, Arguments.DatabaseRepository.Render(), Arguments.DropDatabase, Arguments.DatabaseCommandTimeout);
}
private static SqlConnectionStringBuilder RedactPassword(SqlConnectionStringBuilder connStr)
{
return string.IsNullOrEmpty(connStr.Password) ?
connStr :
new SqlConnectionStringBuilder(connStr.ConnectionString)
{
Password = new string('*', connStr.Password.Length)
};
}
}
}
``` |
6345e034-9d7e-469e-bade-7d583c64468e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace TechProFantasySoccer
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
}
```
Disable the master mobile site. | ```c#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace TechProFantasySoccer
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
/*var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);*/
//Commenting the above code and using the below line gets rid of the master mobile site.
routes.EnableFriendlyUrls();
}
}
}
``` |
da0c2524-25d7-4f2d-a2be-963f566660e0 | {
"language": "C#"
} | ```c#
/*
* Copyright (c) 2013, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Future non-SteamKit stuff should go in this file.
*/
using System;
using System.Threading;
namespace PICSUpdater
{
class Program
{
static void Main(string[] args)
{
new Thread(new ThreadStart(Steam.Run)).Start();
//Steam.GetPICSChanges();
}
}
}
```
Make sure config exists by checking steam credentials | ```c#
/*
* Copyright (c) 2013, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Future non-SteamKit stuff should go in this file.
*/
using System;
using System.Configuration;
using System.Threading;
namespace PICSUpdater
{
class Program
{
static void Main(string[] args)
{
if (ConfigurationManager.AppSettings["steam-username"] == null || ConfigurationManager.AppSettings["steam-password"] == null)
{
Console.WriteLine("Is config missing? It should be in " + ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
return;
}
//new Thread(new ThreadStart(Steam.Run)).Start();
Steam.Run();
}
}
}
``` |
490a8e8d-6039-4466-9251-02ede1d2c1a2 | {
"language": "C#"
} | ```c#
<p>Welcome! Codingteam is an open community of engineers and programmers.</p>
<p>And here're today's conference logs:</p>
<iframe class="logs" src="@ViewData["LogUrl"]"></iframe>
<a href="/old-logs/codingteam@conference.jabber.ru/">Older logs (mostly actual in period 2008-08-22 — 2016-12-09)</a>
```
Fix date 2008 -> 2009 | ```c#
<p>Welcome! Codingteam is an open community of engineers and programmers.</p>
<p>And here're today's conference logs:</p>
<iframe class="logs" src="@ViewData["LogUrl"]"></iframe>
<a href="/old-logs/codingteam@conference.jabber.ru/">Older logs (mostly actual in period 2009-08-22 — 2016-12-09)</a>
``` |
c52b100c-3a90-4d32-b0fd-8563ee338275 | {
"language": "C#"
} | ```c#
namespace Bakery.Logging
{
using System;
using Time;
public class ConsoleLog
: ILog
{
private readonly IClock clock;
public ConsoleLog(IClock clock)
{
this.clock = clock;
}
public void Write(Level logLevel, String message)
{
const String FORMAT = "{0}: [{1}] {2}";
var textWriter = logLevel >= Level.Warning
? Console.Error
: Console.Out;
textWriter.WriteLine(
String.Format(
FORMAT,
clock.GetUniversalTime().ToString(),
logLevel,
message));
}
}
}
```
Enforce single responsibility principle -- decorators can implement additional functionality. | ```c#
namespace Bakery.Logging
{
using System;
public class ConsoleLog
: ILog
{
public void Write(Level logLevel, String message)
{
var textWriter = logLevel >= Level.Warning
? Console.Error
: Console.Out;
textWriter.WriteLine(message);
}
}
}
``` |
79c529d4-2d96-4d37-8935-f852071b7eaa | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]
[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.net")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.net/LICENSE")]
// NOTE: When updating the version, you also need to update the Identity/@Version
// attribtute in src\NuProj.ProjectSystem.12\source.extension.vsixmanifest.
[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
```
Add note to change the version number for both VSIX files | ```c#
using System.Reflection;
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]
[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.net")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.net/LICENSE")]
// NOTE: When updating the version, you also need to update the Identity/@Version
// attribtute in:
//
// src\NuProj.ProjectSystem.12\source.extension.vsixmanifest
// src\NuProj.ProjectSystem.14\source.extension.vsixmanifest
[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
``` |
67e020bc-6b43-4460-aab7-4b6b3139e0c7 | {
"language": "C#"
} | ```c#
namespace Parsley.Tests;
class ParsedTests
{
public void HasAParsedValue()
{
new Parsed<string>("parsed", new(1, 1)).Value.ShouldBe("parsed");
}
public void HasNoErrorMessageByDefault()
{
new Parsed<string>("x", new(1, 1)).ErrorMessages.ShouldBe(ErrorMessageList.Empty);
}
public void CanIndicatePotentialErrors()
{
var potentialErrors = ErrorMessageList.Empty
.With(ErrorMessage.Expected("A"))
.With(ErrorMessage.Expected("B"));
new Parsed<object>("x", new(1, 1), potentialErrors).ErrorMessages.ShouldBe(potentialErrors);
}
public void HasRemainingUnparsedInput()
{
var parsed = new Parsed<string>("parsed", new(12, 34));
parsed.Position.ShouldBe(new (12, 34));
}
public void ReportsNonerrorState()
{
new Parsed<string>("parsed", new(1, 1)).Success.ShouldBeTrue();
}
}
```
Improve test coverage for Parsed<T> by mirroring the test coverage for Error<T>. | ```c#
namespace Parsley.Tests;
class ParsedTests
{
public void CanIndicateSuccessfullyParsedValueAtTheCurrentPosition()
{
var parsed = new Parsed<string>("parsed", new(12, 34));
parsed.Success.ShouldBe(true);
parsed.Value.ShouldBe("parsed");
parsed.ErrorMessages.ShouldBe(ErrorMessageList.Empty);
parsed.Position.ShouldBe(new(12, 34));
}
public void CanIndicatePotentialErrorMessagesAtTheCurrentPosition()
{
var potentialErrors = ErrorMessageList.Empty
.With(ErrorMessage.Expected("A"))
.With(ErrorMessage.Expected("B"));
var parsed = new Parsed<object>("parsed", new(12, 34), potentialErrors);
parsed.Success.ShouldBe(true);
parsed.Value.ShouldBe("parsed");
parsed.ErrorMessages.ShouldBe(potentialErrors);
parsed.Position.ShouldBe(new(12, 34));
}
}
``` |
75dbb1e6-666c-4c81-a803-4f45b07ca072 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
namespace clipr.Utils
{
/// <summary>
/// <para>
/// A TypeConverter that allows conversion of any object to System.Object.
/// Does not actually perform a conversion, just passes the value on
/// through.
/// </para>
/// <para>
/// Must be registered before parsing.
/// </para>
/// </summary>
internal class ObjectTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(String) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value is string
? value
: base.ConvertFrom(context, culture, value);
}
public override bool IsValid(ITypeDescriptorContext context, object value)
{
return value is string || base.IsValid(context, value);
}
public static void Register()
{
var attr = new Attribute[]
{
new TypeConverterAttribute(typeof(ObjectTypeConverter))
};
TypeDescriptor.AddAttributes(typeof(object), attr);
}
}
}
```
Fix accidental type conversion breakage. | ```c#
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
namespace clipr.Utils
{
/// <summary>
/// <para>
/// A TypeConverter that allows conversion of any object to System.Object.
/// Does not actually perform a conversion, just passes the value on
/// through.
/// </para>
/// <para>
/// Must be registered before parsing.
/// </para>
/// </summary>
internal class ObjectTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(String) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value is string
? value
: base.ConvertFrom(context, culture, value);
}
public override bool IsValid(ITypeDescriptorContext context, object value)
{
return value is string || base.IsValid(context, value);
}
public static void Register()
{
var attr = new Attribute[]
{
new TypeConverterAttribute(typeof(ObjectTypeConverter))
};
//TypeDescriptor.AddAttributes(typeof(object), attr); //TODO this breaks most type conversion since we override object...
}
}
}
``` |
c6342346-8169-4524-8fa1-f93085f0cc37 | {
"language": "C#"
} | ```c#
namespace clipr.Core
{
/// <summary>
/// Parsing config for a verb, includes a way to "set" the resulting
/// verb on the original options object.
/// </summary>
public interface IVerbParserConfig: IParserConfig
{
/// <summary>
/// Store the verb on the options objcet.
/// </summary>
IValueStoreDefinition Store { get; }
}
internal class VerbParserConfig<TVerb> : ParserConfig<TVerb>, IVerbParserConfig where TVerb : class
{
public VerbParserConfig(IParserConfig internalParserConfig, IValueStoreDefinition store, ParserOptions options)
: base(options, null)
{
InternalParserConfig = internalParserConfig;
Store = store;
LongNameArguments = InternalParserConfig.LongNameArguments;
ShortNameArguments = InternalParserConfig.ShortNameArguments;
PositionalArguments = InternalParserConfig.PositionalArguments;
Verbs = InternalParserConfig.Verbs;
PostParseMethods = InternalParserConfig.PostParseMethods;
RequiredMutuallyExclusiveArguments = InternalParserConfig.RequiredMutuallyExclusiveArguments;
RequiredNamedArguments = InternalParserConfig.RequiredNamedArguments;
}
public IValueStoreDefinition Store { get; set; }
public IParserConfig InternalParserConfig { get; set; }
}
}
```
Hide InternalParserConfig because it shouldn't be public. | ```c#
namespace clipr.Core
{
/// <summary>
/// Parsing config for a verb, includes a way to "set" the resulting
/// verb on the original options object.
/// </summary>
public interface IVerbParserConfig: IParserConfig
{
/// <summary>
/// Store the verb on the options objcet.
/// </summary>
IValueStoreDefinition Store { get; }
}
internal class VerbParserConfig<TVerb> : ParserConfig<TVerb>, IVerbParserConfig where TVerb : class
{
public VerbParserConfig(IParserConfig internalParserConfig, IValueStoreDefinition store, ParserOptions options)
: base(options, null)
{
InternalParserConfig = internalParserConfig;
Store = store;
LongNameArguments = InternalParserConfig.LongNameArguments;
ShortNameArguments = InternalParserConfig.ShortNameArguments;
PositionalArguments = InternalParserConfig.PositionalArguments;
Verbs = InternalParserConfig.Verbs;
PostParseMethods = InternalParserConfig.PostParseMethods;
RequiredMutuallyExclusiveArguments = InternalParserConfig.RequiredMutuallyExclusiveArguments;
RequiredNamedArguments = InternalParserConfig.RequiredNamedArguments;
}
public IValueStoreDefinition Store { get; set; }
private IParserConfig InternalParserConfig { get; set; }
}
}
``` |
519c7d39-fab9-4600-8570-4e664ad9dcfb | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using Umbraco.Core;
using UmbracoVault.Comparers;
using UmbracoVault.Extensions;
namespace UmbracoVault.Collections
{
public class TypeAliasSet : ReadOnlySet<string>
{
private TypeAliasSet()
: base(new HashSet<string>(new InvariantCultureCamelCaseStringComparer()))
{
}
public static TypeAliasSet GetAliasesForUmbracoEntityType<T>()
{
return GetAliasesForUmbracoEntityType(typeof(T));
}
public static TypeAliasSet GetAliasesForUmbracoEntityType(Type type)
{
var set = new TypeAliasSet();
var attributes = type.GetUmbracoEntityAttributes();
foreach (var attribute in attributes)
{
var alias = attribute.Alias;
if (string.IsNullOrWhiteSpace(alias))
{
// account for doc type models use naming convention of [DocumentTypeAlias]ViewModel
alias = type.Name.TrimEnd("ViewModel");
}
set.BackingSet.Add(alias.ToCamelCase(CultureInfo.InvariantCulture));
}
return set;
}
}
}
```
Correct grammar error in comment. | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using Umbraco.Core;
using UmbracoVault.Comparers;
using UmbracoVault.Extensions;
namespace UmbracoVault.Collections
{
public class TypeAliasSet : ReadOnlySet<string>
{
private TypeAliasSet()
: base(new HashSet<string>(new InvariantCultureCamelCaseStringComparer()))
{
}
public static TypeAliasSet GetAliasesForUmbracoEntityType<T>()
{
return GetAliasesForUmbracoEntityType(typeof(T));
}
public static TypeAliasSet GetAliasesForUmbracoEntityType(Type type)
{
var set = new TypeAliasSet();
var attributes = type.GetUmbracoEntityAttributes();
foreach (var attribute in attributes)
{
var alias = attribute.Alias;
if (string.IsNullOrWhiteSpace(alias))
{
// account for doc type models using naming convention of [DocumentTypeAlias]ViewModel
alias = type.Name.TrimEnd("ViewModel");
}
set.BackingSet.Add(alias.ToCamelCase(CultureInfo.InvariantCulture));
}
return set;
}
}
}
``` |
fe4919ca-dd65-4f8b-814b-98cf54fbde0d | {
"language": "C#"
} | ```c#
using System;
namespace Renci.SshNet.Abstractions
{
internal static class ThreadAbstraction
{
/// <summary>
/// Suspends the current thread for the specified number of milliseconds.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds for which the thread is suspended.</param>
public static void Sleep(int millisecondsTimeout)
{
#if FEATURE_THREAD_SLEEP
System.Threading.Thread.Sleep(millisecondsTimeout);
#elif FEATURE_THREAD_TAP
System.Threading.Tasks.Task.Delay(millisecondsTimeout).Wait();
#else
#error Suspend of the current thread is not implemented.
#endif
}
public static void ExecuteThreadLongRunning(Action action)
{
#if FEATURE_THREAD_TAP
var taskCreationOptions = System.Threading.Tasks.TaskCreationOptions.LongRunning;
System.Threading.Tasks.Task.Factory.StartNew(action, taskCreationOptions);
#else
var thread = new System.Threading.Thread(() => action());
thread.Start();
#endif
}
/// <summary>
/// Executes the specified action in a separate thread.
/// </summary>
/// <param name="action">The action to execute.</param>
public static void ExecuteThread(Action action)
{
if (action == null)
throw new ArgumentNullException("action");
#if FEATURE_THREAD_THREADPOOL
System.Threading.ThreadPool.QueueUserWorkItem(o => action());
#elif FEATURE_THREAD_TAP
System.Threading.Tasks.Task.Run(action);
#else
#error Execution of action in a separate thread is not implemented.
#endif
}
}
}
```
Move null check into FEATURE_THREAD_THREADPOOL section. | ```c#
using System;
namespace Renci.SshNet.Abstractions
{
internal static class ThreadAbstraction
{
/// <summary>
/// Suspends the current thread for the specified number of milliseconds.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds for which the thread is suspended.</param>
public static void Sleep(int millisecondsTimeout)
{
#if FEATURE_THREAD_SLEEP
System.Threading.Thread.Sleep(millisecondsTimeout);
#elif FEATURE_THREAD_TAP
System.Threading.Tasks.Task.Delay(millisecondsTimeout).Wait();
#else
#error Suspend of the current thread is not implemented.
#endif
}
public static void ExecuteThreadLongRunning(Action action)
{
#if FEATURE_THREAD_TAP
var taskCreationOptions = System.Threading.Tasks.TaskCreationOptions.LongRunning;
System.Threading.Tasks.Task.Factory.StartNew(action, taskCreationOptions);
#else
var thread = new System.Threading.Thread(() => action());
thread.Start();
#endif
}
/// <summary>
/// Executes the specified action in a separate thread.
/// </summary>
/// <param name="action">The action to execute.</param>
public static void ExecuteThread(Action action)
{
#if FEATURE_THREAD_THREADPOOL
if (action == null)
throw new ArgumentNullException("action");
System.Threading.ThreadPool.QueueUserWorkItem(o => action());
#elif FEATURE_THREAD_TAP
System.Threading.Tasks.Task.Run(action);
#else
#error Execution of action in a separate thread is not implemented.
#endif
}
}
}
``` |
a551603a-30dc-436f-ba7a-3b8fad1aa531 | {
"language": "C#"
} | ```c#
using System;
using SourceSafeTypeLib;
namespace vsslib
{
public static class VssItemExtensions
{
/// <summary>
/// If VSS conatins $/Project1 but requested $/project1, then case will not be fixed and $/project1 will be retuned.
/// This methor return case to normal -> $/Project1
/// </summary>
/// <param name="item">Item for normalize</param>
/// <returns>Normalized item</returns>
public static IVSSItem Normalize(this IVSSItem item, IVSSDatabase db)
{
IVSSItem current = db.VSSItem["$/"];
foreach (var pathPart in item.Spec.Replace('\\', '/').TrimStart("$/".ToCharArray()).TrimEnd('/').Split('/'))
{
IVSSItem next = null;
foreach (IVSSItem child in current.Items)
{
var parts = child.Spec.TrimEnd('/').Split('/');
var lastPart = parts[parts.Length - 1];
if(String.Compare(pathPart, lastPart, StringComparison.OrdinalIgnoreCase) == 0)
{
next = child;
break;
}
}
if(next == null)
throw new ApplicationException("Can't normalize: " + item.Spec);
current = next;
}
return current;
}
}
}
```
Allow $ as import root | ```c#
using System;
using SourceSafeTypeLib;
namespace vsslib
{
public static class VssItemExtensions
{
/// <summary>
/// If VSS conatins $/Project1 but requested $/project1, then case will not be fixed and $/project1 will be retuned.
/// This methor return case to normal -> $/Project1
/// </summary>
/// <param name="item">Item for normalize</param>
/// <returns>Normalized item</returns>
public static IVSSItem Normalize(this IVSSItem item, IVSSDatabase db)
{
IVSSItem current = db.VSSItem["$/"];
if (item.Spec.Replace('\\', '/').TrimEnd("/".ToCharArray()) == "$")
return current;
foreach (var pathPart in item.Spec.Replace('\\', '/').TrimStart("$/".ToCharArray()).TrimEnd('/').Split('/'))
{
IVSSItem next = null;
foreach (IVSSItem child in current.Items)
{
var parts = child.Spec.TrimEnd('/').Split('/');
var lastPart = parts[parts.Length - 1];
if(String.Compare(pathPart, lastPart, StringComparison.OrdinalIgnoreCase) == 0)
{
next = child;
break;
}
}
if(next == null)
throw new ApplicationException("Can't normalize: " + item.Spec);
current = next;
}
return current;
}
}
}
``` |
493535c7-7abb-47a5-b768-fc82b36ec5e2 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace DemoWcfRest
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DemoService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "hi/{name}")]
public string Hello(string name)
{
return string.Format("Hello, {0}", name);
}
// Add more operations here and mark them with [OperationContract]
[OperationContract]
[WebInvoke(Method = "POST")]
public void PostSample(string postBody)
{
// DO NOTHING
}
}
}
```
Use json in WCF REST response. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace DemoWcfRest
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DemoService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "hi/{name}", ResponseFormat = WebMessageFormat.Json)]
public string Hello(string name)
{
return string.Format("Hello, {0}", name);
}
// Add more operations here and mark them with [OperationContract]
[OperationContract]
[WebInvoke(Method = "POST")]
public void PostSample(string postBody)
{
// DO NOTHING
}
}
}
``` |
85824d42-41e6-47c1-bbb9-58e2c2d41109 | {
"language": "C#"
} | ```c#
#region
using System.Windows;
#endregion
namespace SteamAccountSwitcher
{
internal class Popup
{
public static MessageBoxResult Show(string text, MessageBoxButton btn = MessageBoxButton.OK,
MessageBoxImage img = MessageBoxImage.Information, MessageBoxResult defaultbtn = MessageBoxResult.OK)
{
return MessageBox.Show(text, "SteamAccountSwitcher", btn, img, defaultbtn);
}
}
}```
Change default popup title text | ```c#
#region
using System.Windows;
#endregion
namespace SteamAccountSwitcher
{
internal class Popup
{
public static MessageBoxResult Show(string text, MessageBoxButton btn = MessageBoxButton.OK,
MessageBoxImage img = MessageBoxImage.Information, MessageBoxResult defaultbtn = MessageBoxResult.OK)
{
return MessageBox.Show(text, "Steam Account Switcher", btn, img, defaultbtn);
}
}
}``` |
e27b6ab1-3357-453a-8012-78503787cfbb | {
"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.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Profile.Header.Components
{
public class ProfileRulesetTabItem : OverlayRulesetTabItem
{
private bool isDefault;
public bool IsDefault
{
get => isDefault;
set
{
if (isDefault == value)
return;
isDefault = value;
icon.FadeTo(isDefault ? 1 : 0, 200, Easing.OutQuint);
}
}
protected override Color4 AccentColour
{
get => base.AccentColour;
set
{
base.AccentColour = value;
icon.FadeColour(value, 120, Easing.OutQuint);
}
}
private readonly SpriteIcon icon;
public ProfileRulesetTabItem(RulesetInfo value)
: base(value)
{
Add(icon = new SpriteIcon
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Alpha = 0,
AlwaysPresent = true,
Icon = FontAwesome.Solid.Star,
Size = new Vector2(12),
});
}
}
}
```
Adjust profile ruleset selector to new design | ```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.Game.Rulesets;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Profile.Header.Components
{
public class ProfileRulesetTabItem : OverlayRulesetTabItem
{
private bool isDefault;
public bool IsDefault
{
get => isDefault;
set
{
if (isDefault == value)
return;
isDefault = value;
icon.Alpha = isDefault ? 1 : 0;
}
}
protected override Color4 AccentColour
{
get => base.AccentColour;
set
{
base.AccentColour = value;
icon.FadeColour(value, 120, Easing.OutQuint);
}
}
private readonly SpriteIcon icon;
public ProfileRulesetTabItem(RulesetInfo value)
: base(value)
{
Add(icon = new SpriteIcon
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Alpha = 0,
Icon = FontAwesome.Solid.Star,
Size = new Vector2(12),
});
}
}
}
``` |
33c3b25d-1bfa-45cd-9eb7-271f393b5866 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Reflection;
// ReSharper disable once CheckNamespace
internal class Program
{
private static void Main(string[] args)
{
var mainAsm = Assembly.Load("citizenmp_server_updater");
mainAsm.GetType("Costura.AssemblyLoader")
.GetMethod("Attach")
.Invoke(null, null);
mainAsm.GetType("CitizenMP.Server.Installer.Program")
.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
.Invoke(null, new object[] {args});
}
}```
Return exit values through wrapper. | ```c#
using System;
using System.IO;
using System.Reflection;
// ReSharper disable once CheckNamespace
internal static class Program
{
private static int Main(string[] args)
{
// Mono's XBuild uses assembly redirects to make sure it uses .NET 4.5 target binaries.
// We emulate it using our own assembly redirector.
AppDomain.CurrentDomain.AssemblyLoad += (sender, e) =>
{
var assemblyName = e.LoadedAssembly.GetName();
Console.WriteLine("Assembly load: {0}", assemblyName);
};
var mainAsm = Assembly.Load("citizenmp_server_updater");
mainAsm.GetType("Costura.AssemblyLoader")
.GetMethod("Attach")
.Invoke(null, null);
return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program")
.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
.Invoke(null, new object[] {args});
}
}``` |
b321e5b0-9cab-41fb-81a8-80cbb2d58c1f | {
"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.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests
{
internal class VisualTestGame : TestGame
{
[BackgroundDependencyLoader]
private void load()
{
Child = new SafeAreaSnappingContainer
{
SafeEdges = Edges.Left | Edges.Top | Edges.Right,
Child = new DrawSizePreservingFillContainer
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
},
}
};
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
host.Window.CursorState |= CursorState.Hidden;
}
}
}
```
Fix zero size parent container in visual tests | ```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.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests
{
internal class VisualTestGame : TestGame
{
[BackgroundDependencyLoader]
private void load()
{
Child = new SafeAreaSnappingContainer
{
RelativeSizeAxes = Axes.Both,
SafeEdges = Edges.Left | Edges.Top | Edges.Right,
Child = new DrawSizePreservingFillContainer
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
},
}
};
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
host.Window.CursorState |= CursorState.Hidden;
}
}
}
``` |
bbcda6fb-fdec-467d-a4a5-edc19e6ad067 | {
"language": "C#"
} | ```c#
using Ninject;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject.Extensions.Conventions;
namespace FunWithNinject.Conventions
{
[TestFixture]
public class ConventionsTests
{
[Test]
public void Bind_OneClassWithMultipleInterfaces_BindsOneInstanceToAll()
{
// Assemble
using (var kernel = new StandardKernel())
{
kernel.Bind(k => k.FromThisAssembly()
.SelectAllClasses()
.InNamespaceOf<ConventionsTests>()
.BindAllInterfaces()
.Configure(b => b.InSingletonScope()));
// Act
var face1 = kernel.Get<IFace1>();
var face2 = kernel.Get<IFace2>();
// Assemble
Assert.AreSame(face1, face2);
}
}
}
public interface IFace1 { }
public interface IFace2 { }
public class AllFaces : IFace1, IFace2 { }
}
```
Add test case for open generics | ```c#
using Ninject;
using Ninject.Extensions.Conventions;
using NUnit.Framework;
namespace FunWithNinject.Conventions
{
[TestFixture]
public class ConventionsTests
{
[Test]
public void Bind_OneClassWithMultipleInterfaces_BindsOneInstanceToAll()
{
// Assemble
using (var kernel = new StandardKernel())
{
kernel.Bind(k => k.FromThisAssembly()
.SelectAllClasses()
.InNamespaceOf<ConventionsTests>()
.BindAllInterfaces()
.Configure(b => b.InSingletonScope()));
// Act
var face1 = kernel.Get<IFace1>();
var face2 = kernel.Get<IFace2>();
// Assemble
Assert.AreSame(face1, face2);
}
}
[Test]
public void Bind_ResolveGenericType_Works()
{
// Assemble
using (var kernel = new StandardKernel())
{
kernel.Bind(k => k.FromThisAssembly()
.SelectAllClasses()
.InNamespaceOf<ConventionsTests>()
.BindAllInterfaces()
.Configure(b => b.InSingletonScope()));
kernel.Bind<int>().ToConstant(27);
kernel.Bind<string>().ToConstant("twenty seven");
// Act
var generic = kernel.Get<IGeneric<int, string>>();
// Assemble
Assert.AreEqual(27, generic.FirstProp);
Assert.AreEqual("twenty seven", generic.SecondProp);
}
}
#region Helper Classes/Interfaces
public interface IFace1 { }
public interface IFace2 { }
public interface IGeneric<T1, T2>
{
T1 FirstProp { get; set; }
T2 SecondProp { get; set; }
}
public class AllFaces : IFace1, IFace2 { }
public class Generic<T1, T2> : IGeneric<T1, T2>
{
public Generic(T1 first, T2 second)
{
FirstProp = first;
SecondProp = second;
}
public T1 FirstProp { get; set; }
public T2 SecondProp { get; set; }
}
#endregion Helper Classes/Interfaces
}
}``` |
7e088bc8-e72a-4c4e-a1cc-881f356ad2f3 | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.DomainServices 3.0.0")]
```
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.DomainServices 3.0.0")]
``` |
1f827458-bc79-4df7-9d85-17a8c1e03783 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Cogito.Web.Razor.Tests
{
[TestClass]
public class RazorTemplateBuilderTests
{
TextReader LoadTemplateText(string name)
{
return new StreamReader(typeof(RazorTemplateBuilderTests).Assembly
.GetManifestResourceStream(typeof(RazorTemplateBuilderTests).Namespace + ".Templates." + name));
}
[TestMethod]
public void Test_simple_code_generation()
{
var t = RazorTemplateBuilder.ToCode(() => LoadTemplateText("Simple.cshtml"));
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
[TestMethod]
public void Test_simple_helper_code_generation()
{
var t = RazorTemplateBuilder.ToCode(() => LoadTemplateText("SimpleWithHelper.cshtml"));
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
}
}
```
Fix Razor tests broken by change to full string passing. | ```c#
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Cogito.Web.Razor.Tests
{
[TestClass]
public class RazorTemplateBuilderTests
{
TextReader LoadTemplateText(string name)
{
return new StreamReader(typeof(RazorTemplateBuilderTests).Assembly
.GetManifestResourceStream(typeof(RazorTemplateBuilderTests).Namespace + ".Templates." + name));
}
[TestMethod]
public void Test_simple_code_generation()
{
var t = RazorTemplateBuilder.ToCode(LoadTemplateText("Simple.cshtml").ReadToEnd());
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
[TestMethod]
public void Test_simple_helper_code_generation()
{
var t = RazorTemplateBuilder.ToCode(LoadTemplateText("SimpleWithHelper.cshtml").ReadToEnd());
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
}
}
``` |
2b1e3ecb-6389-4fab-8e2d-8a395b56b21a | {
"language": "C#"
} | ```c#
@model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "List";
}
<h2>List</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id })
</td>
</tr>
}
</table>
```
Fix list view template for soldiers | ```c#
@model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "List";
}
<h2>@ViewBag.Title</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Rank)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Status)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rank)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { soldierId = item.Id })
</td>
</tr>
}
</table>
``` |
4e80f93a-3a38-4abd-b267-ac82d03342e7 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class TypeSymbol
{
/// <summary>
/// Represents the method by which this type implements a given interface type
/// and/or the corresponding diagnostics.
/// </summary>
protected class SymbolAndDiagnostics
{
public static readonly SymbolAndDiagnostics Empty = new SymbolAndDiagnostics(null, ImmutableArray<Diagnostic>.Empty);
public readonly Symbol Symbol;
public readonly ImmutableArray<Diagnostic> Diagnostics;
public SymbolAndDiagnostics(Symbol symbol, ImmutableArray<Diagnostic> diagnostics)
{
this.Symbol = symbol;
this.Diagnostics = diagnostics;
}
}
}
}
```
Disable CS0660 where Full Solution Analysis produces a different result | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
#pragma warning disable CS0660 // Warning is reported only for Full Solution Analysis
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class TypeSymbol
{
/// <summary>
/// Represents the method by which this type implements a given interface type
/// and/or the corresponding diagnostics.
/// </summary>
protected class SymbolAndDiagnostics
{
public static readonly SymbolAndDiagnostics Empty = new SymbolAndDiagnostics(null, ImmutableArray<Diagnostic>.Empty);
public readonly Symbol Symbol;
public readonly ImmutableArray<Diagnostic> Diagnostics;
public SymbolAndDiagnostics(Symbol symbol, ImmutableArray<Diagnostic> diagnostics)
{
this.Symbol = symbol;
this.Diagnostics = diagnostics;
}
}
}
}
``` |
d6aa2009-c016-4e0f-bb81-2663097c2b55 | {
"language": "C#"
} | ```c#
using System;
namespace ChamberLib.Content
{
public delegate IModel ModelProcessor(ModelContent asset, IContentProcessor processor);
public delegate ITexture2D TextureProcessor(TextureContent asset, IContentProcessor processor);
public delegate IShaderStage ShaderStageProcessor(ShaderContent asset, IContentProcessor processor, object bindattrs=null);
public delegate IFont FontProcessor(FontContent asset, IContentProcessor processor);
public delegate ISong SongProcessor(SongContent asset, IContentProcessor processor);
public delegate ISoundEffect SoundEffectProcessor(SoundEffectContent asset, IContentProcessor processor);
}
```
Remove the unused bindattrs parameter from the ShaderStageProcessor delegate. | ```c#
using System;
namespace ChamberLib.Content
{
public delegate IModel ModelProcessor(ModelContent asset, IContentProcessor processor);
public delegate ITexture2D TextureProcessor(TextureContent asset, IContentProcessor processor);
public delegate IShaderStage ShaderStageProcessor(ShaderContent asset, IContentProcessor processor);
public delegate IFont FontProcessor(FontContent asset, IContentProcessor processor);
public delegate ISong SongProcessor(SongContent asset, IContentProcessor processor);
public delegate ISoundEffect SoundEffectProcessor(SoundEffectContent asset, IContentProcessor processor);
}
``` |
9d45cfab-5ea4-4818-890d-c1792b57118d | {
"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.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
namespace osu.Game.Tournament.Components
{
public class DateTextBox : SettingsTextBox
{
public new Bindable<DateTimeOffset> Bindable
{
get => bindable;
set
{
bindable = value.GetBoundCopy();
bindable.BindValueChanged(dto =>
base.Bindable.Value = dto.NewValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"), true);
}
}
// hold a reference to the provided bindable so we don't have to in every settings section.
private Bindable<DateTimeOffset> bindable;
public DateTextBox()
{
base.Bindable = new Bindable<string>();
((OsuTextBox)Control).OnCommit = (sender, newText) =>
{
try
{
bindable.Value = DateTimeOffset.Parse(sender.Text);
}
catch
{
// reset textbox content to its last valid state on a parse failure.
bindable.TriggerChange();
}
};
}
}
}
```
Fix nullref in date text box | ```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.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
namespace osu.Game.Tournament.Components
{
public class DateTextBox : SettingsTextBox
{
public new Bindable<DateTimeOffset> Bindable
{
get => bindable;
set
{
bindable = value.GetBoundCopy();
bindable.BindValueChanged(dto =>
base.Bindable.Value = dto.NewValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"), true);
}
}
// hold a reference to the provided bindable so we don't have to in every settings section.
private Bindable<DateTimeOffset> bindable = new Bindable<DateTimeOffset>();
public DateTextBox()
{
base.Bindable = new Bindable<string>();
((OsuTextBox)Control).OnCommit = (sender, newText) =>
{
try
{
bindable.Value = DateTimeOffset.Parse(sender.Text);
}
catch
{
// reset textbox content to its last valid state on a parse failure.
bindable.TriggerChange();
}
};
}
}
}
``` |
72524a35-7eba-45a7-a135-d4956f6070d7 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w.](?<functionName>[\w.]*)$");
if (match.Success)
{
functionName = match.Groups["functionName"].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
```
Extend character set of function names (including ".") (again) | ```c#
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
// TODO: What's the Unicode situation?
public static string forbiddenNameCharacters = @"\ /\-:;!@\#\$%\^&\*\(\)\+=,<>\[\]{}|'\""";
public static string functionNameRegex = "[" + forbiddenNameCharacters + "](?<functionName>[^" + forbiddenNameCharacters + "]*)$";
public static string functionNameGroupName = "functionName";
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), functionNameRegex);
if (match.Success)
{
functionName = match.Groups[functionNameGroupName].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
``` |
b00876c4-7289-418c-b0c7-0cd5b035feaa | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Collections;
public class ColliderFriction : GameObjectBehavior {
public float frictionValue=0;
// Use this for initialization
void Start () {
collider.material.staticFriction = frictionValue;
collider.material.staticFriction2 = frictionValue;
collider.material.dynamicFriction = frictionValue;
collider.material.dynamicFriction2 = frictionValue;
}
}
```
Update to Unity 5.2 cleanup. | ```c#
using UnityEngine;
using System.Collections;
public class ColliderFriction : GameObjectBehavior {
public float frictionValue=0;
// Use this for initialization
void Start () {
collider.material.staticFriction = frictionValue;
//collider.material.staticFriction2 = frictionValue;
collider.material.dynamicFriction = frictionValue;
//collider.material.dynamicFriction2 = frictionValue;
}
}
``` |
adca0ea1-397c-4f55-8421-e6c38d1e955e | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using AshMind.Extensions;
using System;
using SharpLab.Server.Common.Internal;
namespace SharpLab.Server.Owin.Platform {
public class Net48AssemblyDocumentationResolver : IAssemblyDocumentationResolver {
private static readonly string ReferenceAssemblyRootPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
+ @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7";
public DocumentationProvider? GetDocumentation([NotNull] Assembly assembly) {
foreach (var xmlPath in GetCandidatePaths(assembly)) {
if (File.Exists(xmlPath))
return XmlDocumentationProvider.CreateFromFile(xmlPath);
}
return null;
}
private IEnumerable<string> GetCandidatePaths(Assembly assembly) {
var file = assembly.GetAssemblyFileFromCodeBase();
yield return Path.ChangeExtension(file.FullName, ".xml");
yield return Path.Combine(ReferenceAssemblyRootPath, Path.ChangeExtension(file.Name, ".xml"));
}
}
}
```
Fix version of .NET Framework used to look up XML documentation | ```c#
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using AshMind.Extensions;
using System;
using SharpLab.Server.Common.Internal;
namespace SharpLab.Server.Owin.Platform {
public class Net48AssemblyDocumentationResolver : IAssemblyDocumentationResolver {
private static readonly string ReferenceAssemblyRootPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
+ @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8";
public DocumentationProvider? GetDocumentation([NotNull] Assembly assembly) {
foreach (var xmlPath in GetCandidatePaths(assembly)) {
if (File.Exists(xmlPath))
return XmlDocumentationProvider.CreateFromFile(xmlPath);
}
return null;
}
private IEnumerable<string> GetCandidatePaths(Assembly assembly) {
var file = assembly.GetAssemblyFileFromCodeBase();
yield return Path.ChangeExtension(file.FullName, ".xml");
yield return Path.Combine(ReferenceAssemblyRootPath, Path.ChangeExtension(file.Name, ".xml"));
}
}
}
``` |
bca08664-4dc8-4609-8582-63a5e459d996 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
namespace PublicApiGenerator
{
internal static class CSharpOperatorKeyword
{
static readonly IDictionary<string, string> OperatorNameMap = new Dictionary<string, string>
{
{ "op_Addition", "+" },
{ "op_UnaryPlus", "+" },
{ "op_Subtraction", "-" },
{ "op_UnaryNegation", "-" },
{ "op_Multiply", "*" },
{ "op_Division", "/" },
{ "op_Modulus", "%" },
{ "op_Increment", "++" },
{ "op_Decrement", "--" },
{ "op_OnesComplement", "~" },
{ "op_LogicalNot", "!" },
{ "op_BitwiseAnd", "&" },
{ "op_BitwiseOr", "|" },
{ "op_ExclusiveOr", "^" },
{ "op_LeftShift", "<<" },
{ "op_RightShift", ">>" },
{ "op_Equality", "==" },
{ "op_Inequality", "!=" },
{ "op_GreaterThan", ">" },
{ "op_GreaterThanOrEqual", ">=" },
{ "op_LessThan", "<" },
{ "op_LessThanOrEqual", "<=" }
};
public static string Get(string memberName)
{
return OperatorNameMap.TryGetValue(memberName, out string mappedMemberName) ? mappedMemberName : memberName;
}
}
}
```
Fix output for overloaded operators | ```c#
using System.Collections.Generic;
namespace PublicApiGenerator
{
internal static class CSharpOperatorKeyword
{
static readonly IDictionary<string, string> OperatorNameMap = new Dictionary<string, string>
{
{ "op_False", "false" },
{ "op_True", "true" },
{ "op_Addition", "+" },
{ "op_UnaryPlus", "+" },
{ "op_Subtraction", "-" },
{ "op_UnaryNegation", "-" },
{ "op_Multiply", "*" },
{ "op_Division", "/" },
{ "op_Modulus", "%" },
{ "op_Increment", "++" },
{ "op_Decrement", "--" },
{ "op_OnesComplement", "~" },
{ "op_LogicalNot", "!" },
{ "op_BitwiseAnd", "&" },
{ "op_BitwiseOr", "|" },
{ "op_ExclusiveOr", "^" },
{ "op_LeftShift", "<<" },
{ "op_RightShift", ">>" },
{ "op_Equality", "==" },
{ "op_Inequality", "!=" },
{ "op_GreaterThan", ">" },
{ "op_GreaterThanOrEqual", ">=" },
{ "op_LessThan", "<" },
{ "op_LessThanOrEqual", "<=" }
};
public static string Get(string memberName)
{
return OperatorNameMap.TryGetValue(memberName, out string mappedMemberName) ? "operator " + mappedMemberName : memberName;
}
}
}
``` |
86cbec07-b609-48e1-8061-3492e01e3ed4 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class PointsMotor_Pulse : PointsMotor
{
public override byte motorTypeId { get { return 1; } }
public byte ThrowLeftOutput { get; set; }
public byte ThrowRightOutput { get; set; }
public byte positionPin { get; set; }
public bool reverseStatus { get; set; }
public bool lowToThrow { get; set; }
public override List<byte> Serialize()
{
var vector = new List<byte>();
vector.Add(motorTypeId);
vector.Add(this.ThrowLeftOutput);
vector.Add(this.ThrowRightOutput);
vector.Add(positionPin);
vector.Add((byte)(reverseStatus ? 1 : 0));
vector.Add((byte)(lowToThrow ? 1 : 0));
return vector;
}
}
}
```
Make it possible to configure time to pulse | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class PointsMotor_Pulse : PointsMotor
{
public override byte motorTypeId { get { return 1; } }
public byte ThrowLeftOutput { get; set; }
public byte ThrowRightOutput { get; set; }
public byte positionPin { get; set; }
public bool reverseStatus { get; set; }
public bool lowToThrow { get; set; }
public byte timeToPulse { get; set; }
public override List<byte> Serialize()
{
var vector = new List<byte>();
vector.Add(motorTypeId);
vector.Add(this.ThrowLeftOutput);
vector.Add(this.ThrowRightOutput);
vector.Add(positionPin);
vector.Add((byte)(reverseStatus ? 1 : 0));
vector.Add((byte)(lowToThrow ? 1 : 0));
vector.Add(this.timeToPulse);
return vector;
}
}
}
``` |
fd3ecb35-5928-478e-8ecd-e173a7906c25 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Graphics;
using Repository.EditorServices.SyntaxHighlighting;
namespace Repository.Internal.EditorServices.SyntaxHighlighting
{
internal class MonokaiColorTheme : IColorTheme
{
public Color BackgroundColor => Color.Black;
public Color GetForegroundColor(SyntaxKind kind)
{
// TODO: Based off VSCode's Monokai theme
switch (kind)
{
case SyntaxKind.Annotation: return Color.SkyBlue;
case SyntaxKind.BooleanLiteral: return Color.Purple;
case SyntaxKind.Comment: return Color.Gray;
case SyntaxKind.ConstructorDeclaration: return Color.LightGreen;
case SyntaxKind.Eof: return default(Color);
case SyntaxKind.Identifier: return Color.White;
case SyntaxKind.Keyword: return Color.HotPink;
case SyntaxKind.MethodDeclaration: return Color.LightGreen;
case SyntaxKind.MethodIdentifier: return Color.LightGreen;
case SyntaxKind.NullLiteral: return Color.Purple;
case SyntaxKind.NumericLiteral: return Color.Purple;
case SyntaxKind.ParameterDeclaration: return Color.Orange;
case SyntaxKind.Parenthesis: return Color.White;
case SyntaxKind.StringLiteral: return Color.Beige;
case SyntaxKind.TypeDeclaration: return Color.LightGreen;
case SyntaxKind.TypeIdentifier: return Color.LightGreen;
default: throw new NotSupportedException();
}
}
}
}```
Tweak the Monokai color theme | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Graphics;
using Repository.EditorServices.SyntaxHighlighting;
namespace Repository.Internal.EditorServices.SyntaxHighlighting
{
internal class MonokaiColorTheme : IColorTheme
{
public Color BackgroundColor => Color.Black;
public Color GetForegroundColor(SyntaxKind kind)
{
// TODO: Based off VSCode's Monokai theme
switch (kind)
{
case SyntaxKind.Annotation: return Color.SkyBlue;
case SyntaxKind.BooleanLiteral: return Color.MediumPurple;
case SyntaxKind.Comment: return Color.Gray;
case SyntaxKind.ConstructorDeclaration: return Color.LightGreen;
case SyntaxKind.Eof: return default(Color);
case SyntaxKind.Identifier: return Color.White;
case SyntaxKind.Keyword: return Color.HotPink;
case SyntaxKind.MethodDeclaration: return Color.LightGreen;
case SyntaxKind.MethodIdentifier: return Color.LightGreen;
case SyntaxKind.NullLiteral: return Color.MediumPurple;
case SyntaxKind.NumericLiteral: return Color.MediumPurple;
case SyntaxKind.ParameterDeclaration: return Color.Orange;
case SyntaxKind.Parenthesis: return Color.White;
case SyntaxKind.StringLiteral: return Color.SandyBrown;
case SyntaxKind.TypeDeclaration: return Color.LightGreen;
case SyntaxKind.TypeIdentifier: return Color.SkyBlue;
default: throw new NotSupportedException();
}
}
}
}``` |
9f976789-e9d1-436f-97ad-506e50553e0e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Mapsui.Geometries;
using Mapsui.Layers;
using Mapsui.Providers;
using NUnit.Framework;
namespace Mapsui.Tests.Fetcher
{
[TestFixture]
public class FeatureFetcherTests
{
[Test]
public void TestFeatureFetcherDelay()
{
// arrange
var extent = new BoundingBox(0, 0, 10, 10);
var layer = new Layer
{
DataSource = new MemoryProvider(GenerateRandomPoints(extent, 25)),
FetchingPostponedInMilliseconds = 0
};
// act
layer.RefreshData(extent, 1, true);
var notifications = new List<bool>();
layer.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == nameof(Layer.Busy))
{
notifications.Add(layer.Busy);
}
};
// assert
Task.Run(() =>
{
while (notifications.Count < 2)
{
// just wait until we have two
}
}).GetAwaiter().GetResult();
Assert.IsTrue(notifications[0]);
Assert.IsFalse(notifications[1]);
}
private static IEnumerable<IGeometry> GenerateRandomPoints(BoundingBox envelope, int count)
{
var random = new Random();
var result = new List<IGeometry>();
for (var i = 0; i < count; i++)
{
result.Add(new Point(
random.NextDouble() * envelope.Width + envelope.Left,
random.NextDouble() * envelope.Height + envelope.Bottom));
}
return result;
}
}
}
```
Fix a unit test for new Delayer logic (immediate if possible) | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Mapsui.Geometries;
using Mapsui.Layers;
using Mapsui.Providers;
using NUnit.Framework;
namespace Mapsui.Tests.Fetcher
{
[TestFixture]
public class FeatureFetcherTests
{
[Test]
public void TestFeatureFetcherDelay()
{
// arrange
var extent = new BoundingBox(0, 0, 10, 10);
var layer = new Layer
{
DataSource = new MemoryProvider(GenerateRandomPoints(extent, 25)),
FetchingPostponedInMilliseconds = 0
};
var notifications = new List<bool>();
layer.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == nameof(Layer.Busy))
{
notifications.Add(layer.Busy);
}
};
// act
layer.RefreshData(extent, 1, true);
// assert
Task.Run(() =>
{
while (notifications.Count < 2)
{
// just wait until we have two
}
}).GetAwaiter().GetResult();
Assert.IsTrue(notifications[0]);
Assert.IsFalse(notifications[1]);
}
private static IEnumerable<IGeometry> GenerateRandomPoints(BoundingBox envelope, int count)
{
var random = new Random();
var result = new List<IGeometry>();
for (var i = 0; i < count; i++)
{
result.Add(new Point(
random.NextDouble() * envelope.Width + envelope.Left,
random.NextDouble() * envelope.Height + envelope.Bottom));
}
return result;
}
}
}
``` |
73a239c7-10a1-4557-b5f8-7124155faafd | {
"language": "C#"
} | ```c#
// Copyright (c) 2016 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
namespace LfMerge.LanguageForge.Model
{
public class LfOptionListItem
{
public Guid? Guid { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string Abbreviation { get; set; }
}
}
```
Fix binary GUIDs showing up in Mongo optionlists | ```c#
// Copyright (c) 2016 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using System;
namespace LfMerge.LanguageForge.Model
{
public class LfOptionListItem
{
[BsonRepresentation(BsonType.String)]
public Guid? Guid { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string Abbreviation { get; set; }
}
}
``` |
e1085818-7248-4da6-a8b0-a15b5b430dbb | {
"language": "C#"
} | ```c#
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Tournament.IO;
namespace osu.Game.Tournament.Screens.Setup
{
internal class TournamentSwitcher : ActionableInfo
{
private OsuDropdown<string> dropdown;
private string startupTournament;
[Resolved]
private TournamentGameBase game { get; set; }
[BackgroundDependencyLoader]
private void load(TournamentStorage storage)
{
startupTournament = storage.CurrentTournament.Value;
dropdown.Current = storage.CurrentTournament;
dropdown.Items = storage.ListTournaments();
dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);
Action = () => game.GracefullyExit();
ButtonText = "Close osu!";
}
protected override Drawable CreateComponent()
{
var drawable = base.CreateComponent();
FlowContainer.Insert(-1, dropdown = new OsuDropdown<string>
{
Width = 510
});
return drawable;
}
}
}```
Change field to local variable | ```c#
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Tournament.IO;
namespace osu.Game.Tournament.Screens.Setup
{
internal class TournamentSwitcher : ActionableInfo
{
private OsuDropdown<string> dropdown;
[Resolved]
private TournamentGameBase game { get; set; }
[BackgroundDependencyLoader]
private void load(TournamentStorage storage)
{
string startupTournament = storage.CurrentTournament.Value;
dropdown.Current = storage.CurrentTournament;
dropdown.Items = storage.ListTournaments();
dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);
Action = () => game.GracefullyExit();
ButtonText = "Close osu!";
}
protected override Drawable CreateComponent()
{
var drawable = base.CreateComponent();
FlowContainer.Insert(-1, dropdown = new OsuDropdown<string>
{
Width = 510
});
return drawable;
}
}
}
``` |
07aba7a1-c039-4cd1-8d29-556696c5aa2d | {
"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.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;
namespace osu.Game.Overlays.OSD
{
public class Toast : Container
{
private readonly Container content;
protected override Container<Drawable> Content => content;
public Toast()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Width = 240;
RelativeSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
Alpha = 0.7f
},
content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
}
};
}
}
}
```
Add note about toast height | ```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.Containers;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;
namespace osu.Game.Overlays.OSD
{
public class Toast : Container
{
private readonly Container content;
protected override Container<Drawable> Content => content;
public Toast()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Width = 240;
// A toast's height is decided (and transformed) by the containing OnScreenDisplay.
RelativeSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
Alpha = 0.7f
},
content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
}
};
}
}
}
``` |
8a75708d-32bf-4a2b-925b-c62e1dc6f17e | {
"language": "C#"
} | ```c#
// Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace PPWCode.Vernacular.Wcf.I.Config
{
public static class WcfConstants
{
/// <summary>
/// Duplicates Castle.Facilities.WcfIntegration.WcfConstants.ExtensionScopeKey because it is internal defined.
/// </summary>
public const string ExtensionScopeKey = "scope";
}
}```
Use references in the documentation (this also removes the spelling warning). | ```c#
// Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace PPWCode.Vernacular.Wcf.I.Config
{
public static class WcfConstants
{
/// <summary>
/// Duplicates the <see cref="ExtensionScopeKey" /> property on
/// <see cref="Castle.Facilities.WcfIntegration.WcfConstants" /> because it is internal defined.
/// </summary>
public const string ExtensionScopeKey = "scope";
}
}``` |
c1a37442-555a-4d61-8324-d097ff8a280d | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Tournament.Screens.Ladder.Components
{
public class DrawableTournamentGrouping : CompositeDrawable
{
public DrawableTournamentGrouping(TournamentGrouping grouping, bool losers = false)
{
AutoSizeAxes = Axes.Both;
InternalChild = new FillFlowContainer
{
Direction = FillDirection.Vertical,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new OsuSpriteText
{
Text = grouping.Description.Value.ToUpper(),
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre
},
new OsuSpriteText
{
Text = ((losers ? "Losers " : "") + grouping.Name).ToUpper(),
Font = "Exo2.0-Bold",
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre
},
}
};
}
}
}
```
Change grouping title colours to match white background | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using OpenTK.Graphics;
namespace osu.Game.Tournament.Screens.Ladder.Components
{
public class DrawableTournamentGrouping : CompositeDrawable
{
public DrawableTournamentGrouping(TournamentGrouping grouping, bool losers = false)
{
AutoSizeAxes = Axes.Both;
InternalChild = new FillFlowContainer
{
Direction = FillDirection.Vertical,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new OsuSpriteText
{
Text = grouping.Description.Value.ToUpper(),
Colour = Color4.Black,
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre
},
new OsuSpriteText
{
Text = ((losers ? "Losers " : "") + grouping.Name).ToUpper(),
Font = "Exo2.0-Bold",
Colour = Color4.Black,
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre
},
}
};
}
}
}
``` |
ce887b0e-86f0-4744-92de-4313b347fb56 | {
"language": "C#"
} | ```c#
<div class="user-display">
@if (!User.Identity.IsAuthenticated)
{
string returnUrl = ViewData.ContainsKey(Constants.ReturnUrlViewDataKey) ? (string)ViewData[Constants.ReturnUrlViewDataKey] : Request.RawUrl;
<span class="welcome">
<a href="@Url.LogOn(returnUrl)" title="Register for an account or sign in with an existing account">Register / Sign in</a>
</span>
}
else
{
<span class="welcome"><a href="@Url.Action(actionName: "Account", controllerName: "Users")">@(User.Identity.Name)</a></span>
<text>/</text>
<span class="user-actions">
<a href="@Url.LogOff()">Sign out</a>
</span>
}
</div>```
Fix link to account page while in admin area | ```c#
<div class="user-display">
@if (!User.Identity.IsAuthenticated)
{
string returnUrl = ViewData.ContainsKey(Constants.ReturnUrlViewDataKey) ? (string)ViewData[Constants.ReturnUrlViewDataKey] : Request.RawUrl;
<span class="welcome">
<a href="@Url.LogOn(returnUrl)" title="Register for an account or sign in with an existing account">Register / Sign in</a>
</span>
}
else
{
<span class="welcome"><a href="@Url.Action("Account", "Users", new { area = "" })">@(User.Identity.Name)</a></span>
<text>/</text>
<span class="user-actions">
<a href="@Url.LogOff()">Sign out</a>
</span>
}
</div>``` |
d3b0a3e9-5621-4eee-beaf-8ca61a3c72af | {
"language": "C#"
} | ```c#
using Stylet;
using SyncTrayzor.Localization;
using SyncTrayzor.SyncThing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace SyncTrayzor.Utils
{
public static class SafeSyncthingExtensions
{
public static async Task StartWithErrorDialogAsync(this ISyncThingManager syncThingManager, IWindowManager windowManager)
{
try
{
await syncThingManager.StartAsync();
}
catch (Win32Exception e)
{
if (e.ErrorCode != -2147467259)
throw;
// Possibly "This program is blocked by group policy. For more information, contact your system administrator" caused
// by e.g. CryptoLocker?
windowManager.ShowMessageBox(
Localizer.Translate("Dialog_SyncthingBlockedByGroupPolicy_Message", e.Message, syncThingManager.ExecutablePath),
Localizer.Translate("Dialog_SyncthingBlockedByGroupPolicy_Title"),
MessageBoxButton.OK, icon: MessageBoxImage.Error);
}
catch (SyncThingDidNotStartCorrectlyException)
{
// Haven't translated yet - still debugging
windowManager.ShowMessageBox(
"Syncthing didn't start correctly",
"Syncthing started running, but we were enable to connect to it. Please report this as a bug",
MessageBoxButton.OK, icon: MessageBoxImage.Error);
}
}
}
}
```
Fix order of title/message in dialog | ```c#
using Stylet;
using SyncTrayzor.Localization;
using SyncTrayzor.SyncThing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace SyncTrayzor.Utils
{
public static class SafeSyncthingExtensions
{
public static async Task StartWithErrorDialogAsync(this ISyncThingManager syncThingManager, IWindowManager windowManager)
{
try
{
await syncThingManager.StartAsync();
}
catch (Win32Exception e)
{
if (e.ErrorCode != -2147467259)
throw;
// Possibly "This program is blocked by group policy. For more information, contact your system administrator" caused
// by e.g. CryptoLocker?
windowManager.ShowMessageBox(
Localizer.Translate("Dialog_SyncthingBlockedByGroupPolicy_Message", e.Message, syncThingManager.ExecutablePath),
Localizer.Translate("Dialog_SyncthingBlockedByGroupPolicy_Title"),
MessageBoxButton.OK, icon: MessageBoxImage.Error);
}
catch (SyncThingDidNotStartCorrectlyException)
{
// Haven't translated yet - still debugging
windowManager.ShowMessageBox(
"Syncthing started running, but we were enable to connect to it. Please report this as a bug",
"Syncthing didn't start correctly",
MessageBoxButton.OK, icon: MessageBoxImage.Error);
}
}
}
}
``` |
3101212d-c52d-4635-86a4-a1ccf00379bb | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using FeralTic.DX11;
using FeralTic.DX11.Resources;
namespace VVVV.DX11
{
[Obsolete("This does access IPluginIO, which fails in case of multi core access, this will be removed in next release, use RenderTaskDelegate instead")]
public delegate void RenderDelegate<T>(IPluginIO pin, DX11RenderContext context, T settings);
public delegate void RenderTaskDelegate<T>(IPluginIO pin, DX11RenderContext context, T settings);
public class DX11BaseLayer<T> : IDX11Resource
{
public RenderDelegate<T> Render;
public bool PostUpdate
{
get { return true; }
}
public void Dispose()
{
}
}
/// <summary>
/// DX11 Layer provide simple interface to tell which pin they need
/// </summary>
public class DX11Layer : DX11BaseLayer<DX11RenderSettings>
{
}
}
```
Add DX11Layout and DX11Shader as dx resources | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using FeralTic.DX11;
using FeralTic.DX11.Resources;
namespace VVVV.DX11
{
[Obsolete("This does access IPluginIO, which fails in case of multi core access, this will be removed in next release, use RenderTaskDelegate instead")]
public delegate void RenderDelegate<T>(IPluginIO pin, DX11RenderContext context, T settings);
public delegate void RenderTaskDelegate<T>(IPluginIO pin, DX11RenderContext context, T settings);
public class DX11BaseLayer<T> : IDX11Resource
{
public RenderDelegate<T> Render;
public bool PostUpdate
{
get { return true; }
}
public void Dispose()
{
}
}
/// <summary>
/// DX11 Layer provide simple interface to tell which pin they need
/// </summary>
public class DX11Layer : DX11BaseLayer<DX11RenderSettings>
{
}
public class DX11Shader: IDX11Resource
{
public DX11ShaderInstance Shader
{
get;
private set;
}
public DX11Shader(DX11ShaderInstance instance)
{
this.Shader = instance;
}
public void Dispose()
{
//Owned, do nothing
}
}
public class DX11Layout : IDX11Resource
{
public InputLayout Layout
{
get;
private set;
}
public DX11Layout(InputLayout layout)
{
this.Layout = layout;
}
public void Dispose()
{
if (this.Layout != null)
{
this.Layout.Dispose();
this.Layout = null;
}
}
}
}
``` |
9549488c-084d-48ed-b7a1-337fff21f4f6 | {
"language": "C#"
} | ```c#
using AVFoundation;
using Plugin.MediaManager.Abstractions;
using UIKit;
namespace Plugin.MediaManager.iOS
{
public class VideoSurface : UIView, IVideoSurface
{
public override void LayoutSubviews()
{
foreach (var layer in Layer.Sublayers)
{
var avPlayerLayer = layer as AVPlayerLayer;
if (avPlayerLayer != null)
avPlayerLayer.Frame = Bounds;
}
base.LayoutSubviews();
}
}
}
```
Add sanity checking for AVPlayerLayer | ```c#
using System;
using AVFoundation;
using CoreGraphics;
using Foundation;
using Plugin.MediaManager.Abstractions;
using UIKit;
namespace Plugin.MediaManager.iOS
{
public class VideoSurface : UIView, IVideoSurface
{
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (Layer.Sublayers == null || Layer.Sublayers.Length == 0)
return;
foreach (var layer in Layer.Sublayers)
{
var avPlayerLayer = layer as AVPlayerLayer;
if (avPlayerLayer != null)
avPlayerLayer.Frame = Bounds;
}
}
}
}
``` |
e4dc7a79-6e85-40d2-a414-84af2bd8cf4b | {
"language": "C#"
} | ```c#
// Copyright (c) Gothos
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Tera.Game.Messages
{
public class LoginServerMessage : ParsedMessage
{
public EntityId Id { get; private set; }
public uint PlayerId { get; private set; }
public string Name { get; private set; }
public string GuildName { get; private set; }
public PlayerClass Class { get { return RaceGenderClass.Class; } }
public RaceGenderClass RaceGenderClass { get; private set; }
internal LoginServerMessage(TeraMessageReader reader)
: base(reader)
{
reader.Skip(10);
RaceGenderClass = new RaceGenderClass(reader.ReadInt32());
Id = reader.ReadEntityId();
reader.Skip(4);
PlayerId = reader.ReadUInt32();
reader.Skip(260);
Name = reader.ReadTeraString();
}
}
}
```
Fix user name detection for some regions | ```c#
// Copyright (c) Gothos
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Tera.Game.Messages
{
public class LoginServerMessage : ParsedMessage
{
public EntityId Id { get; private set; }
public uint PlayerId { get; private set; }
public string Name { get; private set; }
public string GuildName { get; private set; }
public PlayerClass Class { get { return RaceGenderClass.Class; } }
public RaceGenderClass RaceGenderClass { get; private set; }
internal LoginServerMessage(TeraMessageReader reader)
: base(reader)
{
reader.Skip(10);
RaceGenderClass = new RaceGenderClass(reader.ReadInt32());
Id = reader.ReadEntityId();
reader.Skip(4);
PlayerId = reader.ReadUInt32();
//reader.Skip(260);
//This network message doesn't have a fixed size between different region
reader.Skip(220);
var nameFirstBit = false;
while (true)
{
var b = reader.ReadByte();
if (b == 0x80)
{
nameFirstBit = true;
continue;
}
if (b == 0x3F && nameFirstBit)
{
break;
}
nameFirstBit = false;
}
reader.Skip(9);
Name = reader.ReadTeraString();
}
}
}
``` |
18cbc939-1041-464e-8045-eb064d19aea8 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Game.Input.Bindings;
namespace osu.Game.Overlays.Volume
{
public class VolumeControlReceptor : Container, IScrollBindingHandler<GlobalAction>, IHandleGlobalKeyboardInput
{
public Func<GlobalAction, bool> ActionRequested;
public Func<GlobalAction, float, bool, bool> ScrollActionRequested;
public bool OnPressed(GlobalAction action)
{
// if nothing else handles selection actions in the game, it's safe to let volume be adjusted.
switch (action)
{
case GlobalAction.SelectPrevious:
action = GlobalAction.IncreaseVolume;
break;
case GlobalAction.SelectNext:
action = GlobalAction.DecreaseVolume;
break;
}
return ActionRequested?.Invoke(action) ?? false;
}
public bool OnScroll(GlobalAction action, float amount, bool isPrecise) =>
ScrollActionRequested?.Invoke(action, amount, isPrecise) ?? false;
public void OnReleased(GlobalAction action)
{
}
}
}
```
Disable adjusting volume via "select next" and "select previous" as fallbacks | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Game.Input.Bindings;
namespace osu.Game.Overlays.Volume
{
public class VolumeControlReceptor : Container, IScrollBindingHandler<GlobalAction>, IHandleGlobalKeyboardInput
{
public Func<GlobalAction, bool> ActionRequested;
public Func<GlobalAction, float, bool, bool> ScrollActionRequested;
public bool OnPressed(GlobalAction action) =>
ActionRequested?.Invoke(action) ?? false;
public bool OnScroll(GlobalAction action, float amount, bool isPrecise) =>
ScrollActionRequested?.Invoke(action, amount, isPrecise) ?? false;
public void OnReleased(GlobalAction action)
{
}
}
}
``` |
a2408105-aa3b-48c3-bdb4-33c4edbe3a07 | {
"language": "C#"
} | ```c#
using System.DoubleNumerics;
namespace SolidworksAddinFramework.Geometry
{
public static class Matrix4x4Extensions
{
public static Matrix4x4 CreateFromAxisAngleOrigin(PointDirection3 p, double angle)
{
return
Matrix4x4.CreateTranslation(-p.Point)
*Matrix4x4.CreateFromAxisAngle(p.Direction.Unit(), angle)
*Matrix4x4.CreateTranslation(p.Point);
}
public static Matrix4x4 CreateFromEdgeAngleOrigin(Edge3 p, double angle)
{
return CreateFromAxisAngleOrigin(new PointDirection3(p.A,p.Delta),angle);
}
}
}```
Add method to extract rotation part of matrix | ```c#
using System.DoubleNumerics;
using System.Text;
namespace SolidworksAddinFramework.Geometry
{
public static class Matrix4x4Extensions
{
public static Matrix4x4 CreateFromAxisAngleOrigin(PointDirection3 p, double angle)
{
return
Matrix4x4.CreateTranslation(-p.Point)
*Matrix4x4.CreateFromAxisAngle(p.Direction.Unit(), angle)
*Matrix4x4.CreateTranslation(p.Point);
}
public static Matrix4x4 CreateFromEdgeAngleOrigin(Edge3 p, double angle)
{
return CreateFromAxisAngleOrigin(new PointDirection3(p.A,p.Delta),angle);
}
public static Matrix4x4 ExtractRotationPart(this Matrix4x4 m)
{
Vector3 dScale;
Quaternion dRotation;
Vector3 dTranslation;
Matrix4x4.Decompose(m, out dScale, out dRotation, out dTranslation);
return Matrix4x4.CreateFromQuaternion(dRotation);
}
}
}``` |
a825f01d-20cb-4b88-8cba-dacef8185be4 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Giles.Core.Configuration
{
public class Filter
{
public Filter() { }
public Filter(string convertToFilter)
{
foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(entry.Key)))
{
Type = entry.Value;
Name = convertToFilter.Replace(entry.Key, string.Empty);
break;
}
}
public string Name { get; set; }
public FilterType Type { get; set; }
public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType>
{
{"-i", FilterType.Inclusive},
{"-e", FilterType.Exclusive}
};
}
public enum FilterType
{
Inclusive,
Exclusive
}
}```
Create filter when -* is not included | ```c#
using System.Collections.Generic;
using System.Linq;
namespace Giles.Core.Configuration
{
public class Filter
{
public Filter() { }
public Filter(string convertToFilter)
{
foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(entry.Key)))
{
Type = entry.Value;
Name = convertToFilter.Replace(entry.Key, string.Empty);
break;
}
if (!string.IsNullOrWhiteSpace(Name)) return;
Name = convertToFilter;
Type = FilterType.Inclusive;
}
public string Name { get; set; }
public FilterType Type { get; set; }
public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType>
{
{"-i", FilterType.Inclusive},
{"-e", FilterType.Exclusive}
};
}
public enum FilterType
{
Inclusive,
Exclusive
}
}``` |
8ed7b5c4-86f9-4be2-ad89-2c1e590a025a | {
"language": "C#"
} | ```c#
using System.ComponentModel;
namespace JoinRpg.Web.Models.Schedules
{
public enum ScheduleConfigProblemsViewModel
{
//TODO поменять сообщение, когда сделаем настроечный экран
[Description("Расписание не настроено для этого проекта, обратитесь в техподдержку")]
FieldsNotSet,
[Description("У полей, привязанных к расписанию, разная видимость. Измените настройки видимости полей (публичные/игрокам/мастерам) на одинаковые")]
InconsistentVisibility,
[Description("У вас нет доступа к расписанию данного проекта")]
NoAccess,
[Description("Не настроено ни одного помещения")]
NoRooms,
[Description("Не настроено ни одного тайм-слота")]
NoTimeSlots,
}
}
```
Fix message on project schedule not configured | ```c#
using System.ComponentModel;
namespace JoinRpg.Web.Models.Schedules
{
public enum ScheduleConfigProblemsViewModel
{
[Description("Расписание не настроено для этого проекта. Вам необходимо добавить поля для помещения и расписания.")]
FieldsNotSet,
[Description("У полей, привязанных к расписанию, разная видимость. Измените настройки видимости полей (публичные/игрокам/мастерам) на одинаковые.")]
InconsistentVisibility,
[Description("У вас нет доступа к расписанию данного проекта")]
NoAccess,
[Description("Не настроено ни одного помещения")]
NoRooms,
[Description("Не настроено ни одного тайм-слота")]
NoTimeSlots,
}
}
``` |
edef84a2-a0e5-4080-a3e3-7f61da462a5b | {
"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.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class CommentDeleteRequest : APIRequest<CommentBundle>
{
private readonly long id;
public CommentDeleteRequest(long id)
{
this.id = id;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Delete;
return req;
}
protected override string Target => $@"comments/{id}";
}
}
```
Make comment ID public for 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.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class CommentDeleteRequest : APIRequest<CommentBundle>
{
public readonly long ID;
public CommentDeleteRequest(long id)
{
this.ID = id;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Delete;
return req;
}
protected override string Target => $@"comments/{ID}";
}
}
``` |
a6d97396-229c-44bd-8daa-73b8112ccd26 | {
"language": "C#"
} | ```c#
using System;
using AutomaticTypeMapper;
using EOLib.Domain.Chat;
using EOLib.Domain.Login;
using EOLib.Net;
namespace EOLib.PacketHandlers.Chat
{
[AutoMappedType]
public class PrivateMessageHandler : PlayerChatByNameBase
{
private readonly IChatRepository _chatRepository;
public override PacketAction Action => PacketAction.Tell;
public PrivateMessageHandler(IPlayerInfoProvider playerInfoProvider,
IChatRepository chatRepository)
: base(playerInfoProvider)
{
_chatRepository = chatRepository;
}
protected override void PostChat(string name, string message)
{
var localData = new ChatData(name, message, ChatIcon.Note, ChatColor.PM);
var pmData = new ChatData(name, message, ChatIcon.Note);
var whichPMTab = _chatRepository.PMTarget1.Equals(name, StringComparison.InvariantCultureIgnoreCase)
? ChatTab.Private1
: _chatRepository.PMTarget2.Equals(name, StringComparison.InvariantCultureIgnoreCase)
? ChatTab.Private2
: ChatTab.Local;
_chatRepository.AllChat[ChatTab.Local].Add(localData);
if (whichPMTab != ChatTab.Local)
_chatRepository.AllChat[whichPMTab].Add(pmData);
}
}
}```
Fix bug in PMs where incoming PM would cause a crash | ```c#
using System;
using AutomaticTypeMapper;
using EOLib.Domain.Chat;
using EOLib.Domain.Login;
using EOLib.Net;
namespace EOLib.PacketHandlers.Chat
{
[AutoMappedType]
public class PrivateMessageHandler : PlayerChatByNameBase
{
private readonly IChatRepository _chatRepository;
public override PacketAction Action => PacketAction.Tell;
public PrivateMessageHandler(IPlayerInfoProvider playerInfoProvider,
IChatRepository chatRepository)
: base(playerInfoProvider)
{
_chatRepository = chatRepository;
}
protected override void PostChat(string name, string message)
{
var localData = new ChatData(name, message, ChatIcon.Note, ChatColor.PM);
var pmData = new ChatData(name, message, ChatIcon.Note);
ChatTab whichPmTab;
if (_chatRepository.PMTarget1 == null && _chatRepository.PMTarget2 == null)
whichPmTab = ChatTab.Local;
else
whichPmTab = _chatRepository.PMTarget1.Equals(name, StringComparison.InvariantCultureIgnoreCase)
? ChatTab.Private1
: _chatRepository.PMTarget2.Equals(name, StringComparison.InvariantCultureIgnoreCase)
? ChatTab.Private2
: ChatTab.Local;
_chatRepository.AllChat[ChatTab.Local].Add(localData);
if (whichPmTab != ChatTab.Local)
_chatRepository.AllChat[whichPmTab].Add(pmData);
}
}
}``` |
61c13f3a-f869-4cb6-81c7-bef7222d22a3 | {
"language": "C#"
} | ```c#
using System;
using compiler.frontend;
namespace Program
{
class Program
{
//TODO: adjust main to use the parser when it is complete
static void Main(string[] args)
{
// using (Lexer l = new Lexer(@"../../testdata/big.txt"))
// {
// Token t;
// do
// {
// t = l.GetNextToken();
// Console.WriteLine(TokenHelper.PrintToken(t));
//
// } while (t != Token.EOF);
//
// // necessary when testing on windows with visual studio
// //Console.WriteLine("Press 'enter' to exit ....");
// //Console.ReadLine();
// }
using (Parser p = new Parser(@"../../testdata/test002.txt"))
{
p.Parse();
p.FlowCfg.GenerateDOTOutput();
using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt"))
{
file.WriteLine( p.FlowCfg.DOTOutput);
}
}
}
}
}
```
Change main to use test003 | ```c#
using System;
using compiler.frontend;
namespace Program
{
class Program
{
//TODO: adjust main to use the parser when it is complete
static void Main(string[] args)
{
// using (Lexer l = new Lexer(@"../../testdata/big.txt"))
// {
// Token t;
// do
// {
// t = l.GetNextToken();
// Console.WriteLine(TokenHelper.PrintToken(t));
//
// } while (t != Token.EOF);
//
// // necessary when testing on windows with visual studio
// //Console.WriteLine("Press 'enter' to exit ....");
// //Console.ReadLine();
// }
using (Parser p = new Parser(@"../../testdata/test003.txt"))
{
p.Parse();
p.FlowCfg.GenerateDOTOutput();
using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt"))
{
file.WriteLine( p.FlowCfg.DOTOutput);
}
}
}
}
}
``` |
e0d3687c-3791-4fb1-91be-55636cb54bee | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Vipr.Core;
using Vipr.Core.CodeModel;
namespace CSharpWriter
{
public class CollectionGetByIdIndexer : Indexer
{
public Dictionary<Parameter, OdcmProperty> ParameterToPropertyMap { get; private set; }
public CollectionGetByIdIndexer(OdcmEntityClass odcmClass)
{
var keyProperties = odcmClass.Key;
ParameterToPropertyMap = keyProperties.ToDictionary(Parameter.FromProperty, p => p);
Parameters = ParameterToPropertyMap.Keys;
ReturnType = new Type(NamesService.GetFetcherInterfaceName(odcmClass));
OdcmClass = odcmClass;
IsSettable = false;
IsGettable = true;
}
public OdcmClass OdcmClass { get; private set; }
}
}
```
Move GetByIdIndexer to centralized GetKeyParameters implementation | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Vipr.Core;
using Vipr.Core.CodeModel;
namespace CSharpWriter
{
public class CollectionGetByIdIndexer : Indexer
{
public Dictionary<Parameter, OdcmProperty> ParameterToPropertyMap { get; private set; }
public CollectionGetByIdIndexer(OdcmEntityClass odcmClass)
{
Parameters = global::CSharpWriter.Parameters.GetKeyParameters(odcmClass);
ReturnType = new Type(NamesService.GetFetcherInterfaceName(odcmClass));
OdcmClass = odcmClass;
IsSettable = false;
IsGettable = true;
}
public OdcmClass OdcmClass { get; private set; }
}
}
``` |
c41cad0b-9767-4d52-8be2-7d15a4f002a6 | {
"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 osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Effects;
namespace osu.Game.Graphics.UserInterface
{
public class OsuContextMenu : OsuMenu
{
private const int fade_duration = 250;
public OsuContextMenu()
: base(Direction.Vertical)
{
MaskingContainer.CornerRadius = 5;
MaskingContainer.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Colour = Color4.Black.Opacity(0.1f),
Radius = 4,
};
ItemsContainer.Padding = new MarginPadding { Vertical = DrawableOsuMenuItem.MARGIN_VERTICAL };
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.ContextMenuGray;
}
protected override void AnimateOpen() => this.FadeIn(fade_duration, Easing.OutQuint);
protected override void AnimateClose() => this.FadeOut(fade_duration, Easing.OutQuint);
}
}
```
Fix context menu sub-menu display | ```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 osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Graphics.UserInterface
{
public class OsuContextMenu : OsuMenu
{
private const int fade_duration = 250;
public OsuContextMenu()
: base(Direction.Vertical)
{
MaskingContainer.CornerRadius = 5;
MaskingContainer.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Colour = Color4.Black.Opacity(0.1f),
Radius = 4,
};
ItemsContainer.Padding = new MarginPadding { Vertical = DrawableOsuMenuItem.MARGIN_VERTICAL };
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.ContextMenuGray;
}
protected override void AnimateOpen() => this.FadeIn(fade_duration, Easing.OutQuint);
protected override void AnimateClose() => this.FadeOut(fade_duration, Easing.OutQuint);
protected override Menu CreateSubMenu() => new OsuContextMenu();
}
}
``` |
7bbc74ce-5501-4b0c-8f4c-dcc01bda18d8 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.OData.Extensions;
using WebStack.QA.Test.OData.SxS2.ODataV3.Extensions;
namespace WebStack.QA.Test.OData.SxS2.ODataV3
{
public static class ODataV3WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var odataRoute = config.Routes.MapODataServiceRoute(
routeName: "SxSODataV3",
routePrefix: "SxSOData",
model: WebStack.QA.Test.OData.SxS2.ODataV3.Models.ModelBuilder.GetEdmModel())
.SetODataVersionConstraint(true);
var contraint = new ODataVersionRouteConstraint(new List<string>() { "OData-Version" });
odataRoute.Constraints.Add("VersionContraintV1", contraint);
}
}
}
```
Fix e2e faild because api change | ```c#
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.OData.Extensions;
using WebStack.QA.Test.OData.SxS2.ODataV3.Extensions;
namespace WebStack.QA.Test.OData.SxS2.ODataV3
{
public static class ODataV3WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var odataRoute = config.Routes.MapODataServiceRoute(
routeName: "SxSODataV3",
routePrefix: "SxSOData",
model: WebStack.QA.Test.OData.SxS2.ODataV3.Models.ModelBuilder.GetEdmModel());
var contraint = new ODataVersionRouteConstraint(new List<string>() { "OData-Version" });
odataRoute.Constraints.Add("VersionContraintV1", contraint);
}
}
}
``` |
f783dd76-8ac6-4562-81f2-1b0a788ffaad | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BadgerJaus.Services.Core;
using BadgerJaus.Messages.PrimitiveDriver;
using BadgerJaus.Util;
using BadgerControlModule.Models;
namespace BadgerControlModule.Utils
{
class RemotePrimitiveDriverService : RemoteDriverService
{
BadgerControlSubsystem badgerControlSubsystem;
public RemotePrimitiveDriverService(BadgerControlSubsystem badgerControlSubsystem)
{
this.badgerControlSubsystem = badgerControlSubsystem;
}
public void SendDriveCommand(long xJoystickValue, long yJoystickValue, long zJoystickValue, Component parentComponent)
{
SetWrenchEffort setWrenchEffort = new SetWrenchEffort();
setWrenchEffort.SetSource(badgerControlSubsystem.LocalAddress);
setWrenchEffort.SetDestination(parentComponent.JausAddress);
setWrenchEffort.SetPropulsiveLinearEffortX(yJoystickValue);
Transport.SendMessage(setWrenchEffort);
}
}
}
```
Modify primitive driver to send x, y, and z linear effort values. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BadgerJaus.Services.Core;
using BadgerJaus.Messages.PrimitiveDriver;
using BadgerJaus.Util;
using BadgerControlModule.Models;
namespace BadgerControlModule.Utils
{
class RemotePrimitiveDriverService : RemoteDriverService
{
BadgerControlSubsystem badgerControlSubsystem;
public RemotePrimitiveDriverService(BadgerControlSubsystem badgerControlSubsystem)
{
this.badgerControlSubsystem = badgerControlSubsystem;
}
public void SendDriveCommand(long xJoystickValue, long yJoystickValue, long zJoystickValue, Component parentComponent)
{
SetWrenchEffort setWrenchEffort = new SetWrenchEffort();
setWrenchEffort.SetSource(badgerControlSubsystem.LocalAddress);
setWrenchEffort.SetDestination(parentComponent.JausAddress);
// This is intentional, do not attempt to swap the X and Y values.
setWrenchEffort.SetPropulsiveLinearEffortX(yJoystickValue);
setWrenchEffort.SetPropulsiveLinearEffortY(xJoystickValue);
setWrenchEffort.SetPropulsiveLinearEffortZ(zJoystickValue);
Transport.SendMessage(setWrenchEffort);
}
}
}
``` |
7f2ff7e3-a2d9-42a5-af3d-888926236b1a | {
"language": "C#"
} | ```c#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Microsoft Reciprocal License (MS-RL). See LICENSE in the project root for license information.
namespace Tvl.VisualStudio.InheritanceMargin
{
using System;
using Microsoft.VisualStudio.Shell.Interop;
// Stolen from Microsoft.RestrictedUsage.CSharp.Utilities in Microsoft.VisualStudio.CSharp.Services.Language.dll
internal static class RoslynUtilities
{
private static bool? roslynInstalled;
public static bool IsRoslynInstalled(IServiceProvider serviceProvider)
{
if (roslynInstalled.HasValue)
return roslynInstalled.Value;
roslynInstalled = false;
if (serviceProvider == null)
return false;
IVsShell vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
if (vsShell == null)
return false;
Guid guid = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1");
int isInstalled;
if (vsShell.IsPackageInstalled(ref guid, out isInstalled) == 0 && isInstalled != 0)
roslynInstalled = true;
return roslynInstalled.Value;
}
}
}
```
Fix all violations of SX1309S | ```c#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Microsoft Reciprocal License (MS-RL). See LICENSE in the project root for license information.
namespace Tvl.VisualStudio.InheritanceMargin
{
using System;
using Microsoft.VisualStudio.Shell.Interop;
// Stolen from Microsoft.RestrictedUsage.CSharp.Utilities in Microsoft.VisualStudio.CSharp.Services.Language.dll
internal static class RoslynUtilities
{
private static bool? _roslynInstalled;
public static bool IsRoslynInstalled(IServiceProvider serviceProvider)
{
if (_roslynInstalled.HasValue)
return _roslynInstalled.Value;
_roslynInstalled = false;
if (serviceProvider == null)
return false;
IVsShell vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
if (vsShell == null)
return false;
Guid guid = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1");
int isInstalled;
if (vsShell.IsPackageInstalled(ref guid, out isInstalled) == 0 && isInstalled != 0)
_roslynInstalled = true;
return _roslynInstalled.Value;
}
}
}
``` |
7957349c-5985-4d6e-bc9b-592ca65ef1f9 | {
"language": "C#"
} | ```c#
using UniRx;
using UniRx.Triggers;
using UnityEngine;
using UnityEngine.UI;
public class CanvasWidthScalePresenter : MonoBehaviour
{
[SerializeField]
CanvasEvents canvasEvents;
[SerializeField]
Slider canvasWidthScaleController;
NotesEditorModel model;
void Awake()
{
model = NotesEditorModel.Instance;
model.OnLoadedMusicObservable.First().Subscribe(_ => Init());
}
void Init()
{
model.CanvasWidth = canvasEvents.MouseScrollWheelObservable
.Where(_ => KeyInput.CtrlKey())
.Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.UpArrow)).Select(_ => 0.1f))
.Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.DownArrow)).Select(_ => -0.1f))
.Select(delta => model.CanvasWidth.Value * (1 + delta))
.Select(x => x / (model.Audio.clip.samples / 100f))
.Select(x => Mathf.Clamp(x, 0.1f, 2f))
.Merge(canvasWidthScaleController.OnValueChangedAsObservable()
.DistinctUntilChanged())
.Select(x => model.Audio.clip.samples / 100f * x)
.ToReactiveProperty();
}
}
```
Fix the speed of the canvas width scaling by left/right arrow keys | ```c#
using UniRx;
using UniRx.Triggers;
using UnityEngine;
using UnityEngine.UI;
public class CanvasWidthScalePresenter : MonoBehaviour
{
[SerializeField]
CanvasEvents canvasEvents;
[SerializeField]
Slider canvasWidthScaleController;
NotesEditorModel model;
void Awake()
{
model = NotesEditorModel.Instance;
model.OnLoadedMusicObservable.First().Subscribe(_ => Init());
}
void Init()
{
model.CanvasWidth = canvasEvents.MouseScrollWheelObservable
.Where(_ => KeyInput.CtrlKey())
.Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.UpArrow)).Select(_ => 0.05f))
.Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.DownArrow)).Select(_ => -0.05f))
.Select(delta => model.CanvasWidth.Value * (1 + delta))
.Select(x => x / (model.Audio.clip.samples / 100f))
.Select(x => Mathf.Clamp(x, 0.1f, 2f))
.Merge(canvasWidthScaleController.OnValueChangedAsObservable()
.DistinctUntilChanged())
.Select(x => model.Audio.clip.samples / 100f * x)
.ToReactiveProperty();
}
}
``` |
58050af2-9e65-4adc-a36d-d1d639e33aa2 | {
"language": "C#"
} | ```c#
using System.Collections;
using Engine;
using Engine.Data;
using Engine.Networking;
using Engine.Utility;
using UnityEngine;
namespace Engine.Game.Controllers {
[RequireComponent(typeof(ThirdPersonController))]
public class ThirdPersonPushBodies : BaseEngineBehavior {
public float pushPower = 0.5f;
public LayerMask pushLayers = -1;
private BaseThirdPersonController controller;
private void Start() {
controller = GetComponent<BaseThirdPersonController>();
}
private void OnControllerColliderHit(ControllerColliderHit hit) {
Rigidbody body = hit.collider.attachedRigidbody;
// no rigidbody
if (body == null || body.isKinematic)
return;
// Ignore pushing those rigidbodies
int bodyLayerMask = 1 << body.gameObject.layer;
if ((bodyLayerMask & pushLayers.value) == 0)
return;
// We dont want to push objects below us
if (hit.moveDirection.y < -0.3)
return;
// Calculate push direction from move direction, we only push objects to the sides
// never up and down
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
// push with move speed but never more than walkspeed
body.velocity = pushDir * pushPower * Mathf.Min(controller.GetSpeed(), controller.walkSpeed);
}
}
}```
Update unity networking for NETWORK_PHOTON. Updates for iTunes 1.2 build update. Advertiser id to vendor id for game analytics and update textures/showing fireworks/camera sorting. | ```c#
using System.Collections;
using Engine;
using Engine.Data;
using Engine.Networking;
using Engine.Utility;
using UnityEngine;
namespace Engine.Game.Controllers {
#if NETWORK_PHOTON
[RequireComponent(typeof(ThirdPersonController))]
public class ThirdPersonPushBodies : BaseEngineBehavior {
public float pushPower = 0.5f;
public LayerMask pushLayers = -1;
private BaseThirdPersonController controller;
private void Start() {
controller = GetComponent<BaseThirdPersonController>();
}
private void OnControllerColliderHit(ControllerColliderHit hit) {
Rigidbody body = hit.collider.attachedRigidbody;
// no rigidbody
if (body == null || body.isKinematic)
return;
// Ignore pushing those rigidbodies
int bodyLayerMask = 1 << body.gameObject.layer;
if ((bodyLayerMask & pushLayers.value) == 0)
return;
// We dont want to push objects below us
if (hit.moveDirection.y < -0.3)
return;
// Calculate push direction from move direction, we only push objects to the sides
// never up and down
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
// push with move speed but never more than walkspeed
body.velocity = pushDir * pushPower * Mathf.Min(controller.GetSpeed(), controller.walkSpeed);
}
}
#endif
}``` |
b70233e5-f674-4b73-9f54-e82f451879ba | {
"language": "C#"
} | ```c#
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using TechTalk.SpecFlow;
using Xunit;
namespace Web.UI.Tests
{
[Binding]
public class WebBrowserWaitSteps : WebDriverStepsBase
{
[When("I wait for element with id (.*) to exist")]
public void IWaitForElementWithIdToExist(string id)
{
var wait = new WebDriverWait(Driver, TimeSpan.FromMinutes(1));
wait.Until<IWebElement>(x =>
{
return x.FindElement(By.Id(id));
});
}
[Then(@"I expect that the element with id (.*) exists")]
public void ThenIExpectThatTheElementWithIdExists(string id)
{
var element = Driver.FindElement(By.Id(id));
Assert.NotNull(element);
}
}
}
```
Use ExpectedConditions for element exists check | ```c#
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using TechTalk.SpecFlow;
using Xunit;
namespace Web.UI.Tests
{
[Binding]
public class WebBrowserWaitSteps : WebDriverStepsBase
{
[When("I wait for element with id (.*) to exist")]
public void IWaitForElementWithIdToExist(string id)
{
var wait = new WebDriverWait(Driver, TimeSpan.FromMinutes(1));
wait.Until<IWebElement>(ExpectedConditions.ElementExists(By.Id(id)));
}
[Then(@"I expect that the element with id (.*) exists")]
public void ThenIExpectThatTheElementWithIdExists(string id)
{
var element = Driver.FindElement(By.Id(id));
Assert.NotNull(element);
}
}
}
``` |
d260b457-0202-4d84-80a8-a6321c389420 | {
"language": "C#"
} | ```c#
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.Interfaces;
using WalletWasabi.Logging;
using WalletWasabi.WebClients.BlockchainInfo;
using WalletWasabi.WebClients.Coinbase;
using WalletWasabi.WebClients.Gemini;
using WalletWasabi.WebClients.ItBit;
using WalletWasabi.WebClients.SmartBit;
namespace WalletWasabi.WebClients
{
public class ExchangeRateProvider : IExchangeRateProvider
{
private readonly IExchangeRateProvider[] ExchangeRateProviders =
{
new SmartBitExchangeRateProvider(new SmartBitClient(Network.Main)),
new BlockchainInfoExchangeRateProvider(),
new CoinbaseExchangeRateProvider(),
new GeminiExchangeRateProvider(),
new ItBitExchangeRateProvider()
};
public async Task<List<ExchangeRate>> GetExchangeRateAsync()
{
List<ExchangeRate> exchangeRates = null;
foreach (var provider in ExchangeRateProviders)
{
try
{
exchangeRates = await provider.GetExchangeRateAsync();
break;
}
catch (Exception ex)
{
// Ignore it and try with the next one
Logger.LogTrace(ex);
}
}
return exchangeRates;
}
}
}
```
Use new price providers and degare SmartBit | ```c#
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.Interfaces;
using WalletWasabi.Logging;
using WalletWasabi.WebClients.BlockchainInfo;
using WalletWasabi.WebClients.Coinbase;
using WalletWasabi.WebClients.Gemini;
using WalletWasabi.WebClients.ItBit;
using WalletWasabi.WebClients.SmartBit;
namespace WalletWasabi.WebClients
{
public class ExchangeRateProvider : IExchangeRateProvider
{
private readonly IExchangeRateProvider[] ExchangeRateProviders =
{
new BlockchainInfoExchangeRateProvider(),
new CoinstampExchangeRateProvider(),
new CoinGeckoExchangeRateProvider(),
new CoinbaseExchangeRateProvider(),
new GeminiExchangeRateProvider(),
new ItBitExchangeRateProvider()
new SmartBitExchangeRateProvider(new SmartBitClient(Network.Main)),
};
public async Task<List<ExchangeRate>> GetExchangeRateAsync()
{
List<ExchangeRate> exchangeRates = null;
foreach (var provider in ExchangeRateProviders)
{
try
{
exchangeRates = await provider.GetExchangeRateAsync();
break;
}
catch (Exception ex)
{
// Ignore it and try with the next one
Logger.LogTrace(ex);
}
}
return exchangeRates;
}
}
}
``` |
37e5c8d3-d5da-4ec1-95df-f4d432e4a1be | {
"language": "C#"
} | ```c#
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address>```
Update Support's email address on contact page. Was breaking the world, so it had to be done. | ```c#
@{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
</address>``` |
ceac89c9-1536-4721-8a7f-a95c4366082a | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using FluentEmail.Core;
using FluentEmail.Core.Models;
using FluentScheduler;
using System.Collections.Generic;
using System.IO;
namespace BatteryCommander.Web.Jobs
{
public class PERSTATReportJob : IJob
{
private static IList<Address> Recipients => new List<Address>(new Address[]
{
Matt
// new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" }
});
internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" };
private readonly Database db;
private readonly IFluentEmail emailSvc;
public PERSTATReportJob(Database db, IFluentEmail emailSvc)
{
this.db = db;
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
foreach (var unit in UnitService.List(db).GetAwaiter().GetResult())
{
// HACK - Configure the recipients and units that this is going to be wired up for
emailSvc
.To(Recipients)
.SetFrom(Matt.EmailAddress, Matt.Name)
.Subject($"{unit.Name} | RED 1 PERSTAT")
.UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit)
.Send();
}
}
}
}```
Change from address on PERSTAT, OCD | ```c#
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using FluentEmail.Core;
using FluentEmail.Core.Models;
using FluentScheduler;
using System.Collections.Generic;
using System.IO;
namespace BatteryCommander.Web.Jobs
{
public class PERSTATReportJob : IJob
{
private static IList<Address> Recipients => new List<Address>(new Address[]
{
FROM
// new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" }
});
internal static Address FROM => new Address { Name = "C-2-116 FA", EmailAddress = "C-2-116FA@redleg.app" };
private readonly Database db;
private readonly IFluentEmail emailSvc;
public PERSTATReportJob(Database db, IFluentEmail emailSvc)
{
this.db = db;
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
foreach (var unit in UnitService.List(db).GetAwaiter().GetResult())
{
// HACK - Configure the recipients and units that this is going to be wired up for
emailSvc
.To(Recipients)
.SetFrom(FROM.EmailAddress, FROM.Name)
.Subject($"{unit.Name} | RED 1 PERSTAT")
.UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit)
.Send();
}
}
}
}``` |
98f3ee8e-12f2-4050-8eeb-dd38d69c6999 | {
"language": "C#"
} | ```c#
using System;
namespace DiceApi.Core
{
public class Die
{
/// <summary>
/// Instance of Random that we'll instantiate with the die
/// and use within the Roll() method.
/// </summary>
private readonly Random rng;
/// <summary>
/// Initializes a new instance of <see cref="Die" /> with a
/// specified number of sides.
/// </summary>
/// <param name="sides">Number of sides on the die.</param>
public Die(int sides)
{
if (sides < 1) {
throw new ArgumentOutOfRangeException(nameof(sides));
}
this.Sides = sides;
this.rng = new Random();
}
/// <summary>
/// Gets the number of sides on the die.
/// </summary>
/// <returns></returns>
public int Sides { get; }
/// <summary>
/// Rolls the die, returning its value.
/// </summary>
/// <returns>Result of die roll.</returns>
public int Roll()
{
// Range for Next() is inclusive on the minimum, exclusive on the maximum
return rng.Next(1, this.Sides + 1);
}
}
}
```
Use autogenerated prop for Random instance | ```c#
using System;
namespace DiceApi.Core
{
public class Die
{
/// <summary>
/// Initializes a new instance of <see cref="Die" /> with a
/// specified number of sides.
/// </summary>
/// <param name="sides">Number of sides on the die.</param>
public Die(int sides)
{
if (sides < 1) {
throw new ArgumentOutOfRangeException(nameof(sides));
}
this.Sides = sides;
this.RandomNumberGenerator = new Random();
}
/// <summary>
/// Gets the number of sides on the die.
/// </summary>
/// <returns></returns>
public int Sides { get; }
/// <summary>
/// Gets an instance of Random that we instantiate with the Die
/// constructor. This is used by Roll() to create a random value
/// for the die roll.
/// </summary>
private Random RandomNumberGenerator { get; }
/// <summary>
/// Rolls the die, returning its value.
/// </summary>
/// <returns>Result of die roll.</returns>
public int Roll()
{
// Range for Next() is inclusive on the minimum, exclusive on the maximum
return this.RandomNumberGenerator.Next(1, this.Sides + 1);
}
}
}
``` |
e6ca84fc-5e35-4658-b678-0fc3703c0ab6 | {
"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.Bindables;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Screens.Edit
{
internal class WaveformOpacityMenuItem : MenuItem
{
private readonly Bindable<float> waveformOpacity;
private readonly Dictionary<float, ToggleMenuItem> menuItemLookup = new Dictionary<float, ToggleMenuItem>();
public WaveformOpacityMenuItem(Bindable<float> waveformOpacity)
: base("Waveform opacity")
{
Items = new[]
{
createMenuItem(0.25f),
createMenuItem(0.5f),
createMenuItem(0.75f),
createMenuItem(1f),
};
this.waveformOpacity = waveformOpacity;
waveformOpacity.BindValueChanged(opacity =>
{
foreach (var kvp in menuItemLookup)
kvp.Value.State.Value = kvp.Key == opacity.NewValue;
}, true);
}
private ToggleMenuItem createMenuItem(float opacity)
{
var item = new ToggleMenuItem($"{opacity * 100}%", MenuItemType.Standard, _ => updateOpacity(opacity));
menuItemLookup[opacity] = item;
return item;
}
private void updateOpacity(float opacity) => waveformOpacity.Value = opacity;
}
}
```
Fix checkmark being hidden after clicking current waveform opacity setting | ```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.Bindables;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Screens.Edit
{
internal class WaveformOpacityMenuItem : MenuItem
{
private readonly Bindable<float> waveformOpacity;
private readonly Dictionary<float, TernaryStateRadioMenuItem> menuItemLookup = new Dictionary<float, TernaryStateRadioMenuItem>();
public WaveformOpacityMenuItem(Bindable<float> waveformOpacity)
: base("Waveform opacity")
{
Items = new[]
{
createMenuItem(0.25f),
createMenuItem(0.5f),
createMenuItem(0.75f),
createMenuItem(1f),
};
this.waveformOpacity = waveformOpacity;
waveformOpacity.BindValueChanged(opacity =>
{
foreach (var kvp in menuItemLookup)
kvp.Value.State.Value = kvp.Key == opacity.NewValue ? TernaryState.True : TernaryState.False;
}, true);
}
private TernaryStateRadioMenuItem createMenuItem(float opacity)
{
var item = new TernaryStateRadioMenuItem($"{opacity * 100}%", MenuItemType.Standard, _ => updateOpacity(opacity));
menuItemLookup[opacity] = item;
return item;
}
private void updateOpacity(float opacity) => waveformOpacity.Value = opacity;
}
}
``` |
d22b9e34-b88a-422c-83a7-56ca8693dc12 | {
"language": "C#"
} | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2017";
public const string Trademark = "";
public const string Version = "2.2.1.3";
}
}
```
Update file version to 2.2.1.4 | ```c#
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2017";
public const string Trademark = "";
public const string Version = "2.2.1.4";
}
}
``` |
146d4e0f-c808-4091-9b69-5ff4a326d1b9 | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
[Authorize, ApiExplorerSettings(IgnoreApi = true)]
public class SSDController : Controller
{
private readonly Database db;
public SSDController(Database db)
{
this.db = db;
}
public async Task<IActionResult> Index(SoldierSearchService.Query query)
{
// Ensure we're only displaying Soldiers we care about here
if (!query.Ranks.Any()) query.OnlyEnlisted = true;
return View("List", await SoldierSearchService.Filter(db, query));
}
[HttpPost]
public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion)
{
// Take the models and pull the updated data
var soldier = await SoldiersController.Get(db, soldierId);
soldier
.SSDSnapshots
.Add(new Soldier.SSDSnapshot
{
SSD = ssd,
PerecentComplete = completion / 100 // Convert to decimal percentage
});
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}```
Fix for search by rank | ```c#
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
[Authorize, ApiExplorerSettings(IgnoreApi = true)]
public class SSDController : Controller
{
private readonly Database db;
public SSDController(Database db)
{
this.db = db;
}
public async Task<IActionResult> Index(SoldierSearchService.Query query)
{
if (query?.Ranks?.Any() == true)
{
// Cool, we're searching for one or more specific ranks
}
else
{
query.OnlyEnlisted = true;
}
return View("List", await SoldierSearchService.Filter(db, query));
}
[HttpPost]
public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion)
{
// Take the models and pull the updated data
var soldier = await SoldiersController.Get(db, soldierId);
soldier
.SSDSnapshots
.Add(new Soldier.SSDSnapshot
{
SSD = ssd,
PerecentComplete = completion / 100 // Convert to decimal percentage
});
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.