Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Simplify view engine wrapping for MVC Core | using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;
namespace StackExchange.Profiling.Mvc
{
/// <summary>
/// Extension methods for configuring MiniProfiler for MVC
/// </summary>
public static class MvcExtensions
{
/// <summary>
/// Adds MiniProfiler timings for actions and views
/// </summary>
/// <param name="services">The services collection to configure</param>
public static IServiceCollection AddMiniProfiler(this IServiceCollection services) =>
services.AddTransient<IConfigureOptions<MvcOptions>, MiniPofilerSetup>()
.AddTransient<IConfigureOptions<MvcViewOptions>, MiniPofilerSetup>();
}
internal class MiniPofilerSetup : IConfigureOptions<MvcViewOptions>, IConfigureOptions<MvcOptions>
{
public void Configure(MvcViewOptions options)
{
var copy = options.ViewEngines.ToList();
options.ViewEngines.Clear();
foreach (var item in copy)
{
options.ViewEngines.Add(new ProfilingViewEngine(item));
}
}
public void Configure(MvcOptions options)
{
options.Filters.Add(new ProfilingActionFilter());
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;
namespace StackExchange.Profiling.Mvc
{
/// <summary>
/// Extension methods for configuring MiniProfiler for MVC
/// </summary>
public static class MvcExtensions
{
/// <summary>
/// Adds MiniProfiler timings for actions and views
/// </summary>
/// <param name="services">The services collection to configure</param>
public static IServiceCollection AddMiniProfiler(this IServiceCollection services) =>
services.AddTransient<IConfigureOptions<MvcOptions>, MiniPofilerSetup>()
.AddTransient<IConfigureOptions<MvcViewOptions>, MiniPofilerSetup>();
}
internal class MiniPofilerSetup : IConfigureOptions<MvcViewOptions>, IConfigureOptions<MvcOptions>
{
public void Configure(MvcViewOptions options)
{
for (var i = 0; i < options.ViewEngines.Count; i++)
{
options.ViewEngines[i] = new ProfilingViewEngine(options.ViewEngines[i]);
}
}
public void Configure(MvcOptions options)
{
options.Filters.Add(new ProfilingActionFilter());
}
}
}
|
Add some tests for string extension. | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Host.Client.Test {
[ExcludeFromCodeCoverage]
public class RStringExtensionsTest {
[Test]
[Category.Variable.Explorer]
public void ConvertCharacterCodesTest() {
string target = "<U+4E2D><U+570B><U+8A9E>";
target.ConvertCharacterCodes().Should().Be("中國語");
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Host.Client.Test {
[ExcludeFromCodeCoverage]
public class RStringExtensionsTest {
[Test]
[Category.Variable.Explorer]
public void ConvertCharacterCodesTest() {
string target = "<U+4E2D><U+570B><U+8A9E>";
target.ConvertCharacterCodes().Should().Be("中國語");
}
[CompositeTest]
[InlineData("\t\n", "\"\\t\\n\"")]
[InlineData("\\t\n", "\"\\\\t\\n\"")]
[InlineData("\n", "\"\\n\"")]
[InlineData("\\n", "\"\\\\n\"")]
public void EscapeCharacterTest(string source, string expectedLiteral) {
string actualLiteral = source.ToRStringLiteral();
actualLiteral.Should().Be(expectedLiteral);
string actualSource = actualLiteral.FromRStringLiteral();
actualSource.Should().Be(source);
}
}
}
|
Add handling for non breaking spaces | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Strike;
using Strike.Jint;
namespace PicklesDoc.Pickles
{
public class StrikeMarkdownProvider : IMarkdownProvider
{
private readonly Markdownify markdownify;
public StrikeMarkdownProvider()
{
this.markdownify = new Markdownify(
new Options { Xhtml = true },
new RenderMethods());
}
public string Transform(string text)
{
return this.markdownify.Transform(text);
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Strike;
using Strike.Jint;
namespace PicklesDoc.Pickles
{
public class StrikeMarkdownProvider : IMarkdownProvider
{
private readonly Markdownify markdownify;
public StrikeMarkdownProvider()
{
this.markdownify = new Markdownify(
new Options { Xhtml = true },
new RenderMethods());
}
public string Transform(string text)
{
return this.markdownify.Transform(text).Replace(" ", string.Empty);
}
}
} |
Fix bug spotted with Gendarme. Assign the value of 'successful'. | using System;
using System.Collections.Generic;
using MonoTorrent.BEncoding;
namespace MonoTorrent.Client.Tracker
{
public abstract class TrackerResponseEventArgs : EventArgs
{
private bool successful;
private Tracker tracker;
/// <summary>
/// True if the request completed successfully
/// </summary>
public bool Successful
{
get { return successful; }
set { successful = value; }
}
/// <summary>
/// The tracker which the request was sent to
/// </summary>
public Tracker Tracker
{
get { return tracker; }
protected set { tracker = value; }
}
protected TrackerResponseEventArgs(Tracker tracker, bool successful)
{
if (tracker == null)
throw new ArgumentNullException("tracker");
this.tracker = tracker;
}
}
}
| using System;
using System.Collections.Generic;
using MonoTorrent.BEncoding;
namespace MonoTorrent.Client.Tracker
{
public abstract class TrackerResponseEventArgs : EventArgs
{
private bool successful;
private Tracker tracker;
/// <summary>
/// True if the request completed successfully
/// </summary>
public bool Successful
{
get { return successful; }
set { successful = value; }
}
/// <summary>
/// The tracker which the request was sent to
/// </summary>
public Tracker Tracker
{
get { return tracker; }
protected set { tracker = value; }
}
protected TrackerResponseEventArgs(Tracker tracker, bool successful)
{
if (tracker == null)
throw new ArgumentNullException("tracker");
this.successful = successful;
this.tracker = tracker;
}
}
}
|
Add constrained and tail call methods, and remove virtual from method names, as constrained implies virtual | using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ILGeneratorExtensions
{
public static class MethodFlow
{
public static void JumpTo(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Jmp, method);
public static void Call(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Call, method);
public static void CallVirtual(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Callvirt, method);
public static void TailCall(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Call, method);
}
public static void TailCallVirtual(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Callvirt, method);
}
public static void ConstrainedCallVirtual<T>(this ILGenerator generator, MethodInfo method)
{
generator.ConstrainedCallVirtual(typeof (T), method);
}
public static void ConstrainedCallVirtual(this ILGenerator generator, Type constrainedType, MethodInfo method)
{
generator.Emit(OpCodes.Constrained, constrainedType);
generator.Emit(OpCodes.Callvirt, method);
}
public static void Return(this ILGenerator generator) => generator.Emit(OpCodes.Ret);
}
}
| using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ILGeneratorExtensions
{
public static class MethodFlow
{
public static void JumpTo(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Jmp, method);
public static void Call(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Call, method);
public static void CallVirtual(this ILGenerator generator, MethodInfo method) => generator.Emit(OpCodes.Callvirt, method);
public static void TailCall(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Call, method);
}
public static void TailCallVirtual(this ILGenerator generator, MethodInfo method)
{
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Callvirt, method);
}
public static void ConstrainedCall<T>(this ILGenerator generator, MethodInfo method)
{
generator.ConstrainedCall(typeof (T), method);
}
public static void ConstrainedCall(this ILGenerator generator, Type constrainedType, MethodInfo method)
{
generator.Emit(OpCodes.Constrained, constrainedType);
generator.Emit(OpCodes.Callvirt, method);
}
public static void ConstrainedTailCall<T>(this ILGenerator generator, MethodInfo method)
{
generator.ConstrainedTailCall(typeof(T), method);
}
public static void ConstrainedTailCall(this ILGenerator generator, Type constrainedType, MethodInfo method)
{
generator.Emit(OpCodes.Constrained, constrainedType);
generator.Emit(OpCodes.Tailcall);
generator.Emit(OpCodes.Callvirt, method);
}
public static void Return(this ILGenerator generator) => generator.Emit(OpCodes.Ret);
}
}
|
Add method to create client optimised for write | using System;
using Cake.Core;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Client.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
namespace Cake.DocumentDb.Factories
{
public class ClientFactory
{
private readonly ConnectionSettings settings;
private readonly ICakeContext context;
public ClientFactory(ConnectionSettings settings, ICakeContext context)
{
this.settings = settings;
this.context = context;
}
public IReliableReadWriteDocumentClient GetClient()
{
return new DocumentClient(
new Uri(settings.Endpoint),
settings.Key,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Gateway,
ConnectionProtocol = Protocol.Https
}).AsReliable(new FixedInterval(
15,
TimeSpan.FromSeconds(200)));
}
}
}
| using System;
using Cake.Core;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Client.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
namespace Cake.DocumentDb.Factories
{
public class ClientFactory
{
private readonly ConnectionSettings settings;
private readonly ICakeContext context;
public ClientFactory(ConnectionSettings settings, ICakeContext context)
{
this.settings = settings;
this.context = context;
}
public IReliableReadWriteDocumentClient GetClient()
{
return new DocumentClient(
new Uri(settings.Endpoint),
settings.Key,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Gateway,
ConnectionProtocol = Protocol.Https
})
.AsReliable(
new FixedInterval(
15,
TimeSpan.FromSeconds(200)));
}
// https://github.com/Azure/azure-cosmos-dotnet-v2/blob/master/samples/documentdb-benchmark/Program.cs
public IDocumentClient GetClientOptimistedForWrite()
{
return new DocumentClient(
new Uri(settings.Endpoint),
settings.Key,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp,
RequestTimeout = new TimeSpan(1, 0, 0),
MaxConnectionLimit = 1000,
RetryOptions = new RetryOptions
{
MaxRetryAttemptsOnThrottledRequests = 10,
MaxRetryWaitTimeInSeconds = 60
}
});
}
}
}
|
Make LINQ in playlist function fancier (because why not) | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace anime_downloader {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
String animeFolder;
public MainWindow() {
InitializeComponent();
animeFolder = @"D:\Output\anime downloader";
}
private void button_folder_Click(object sender, RoutedEventArgs e) {
Process.Start(animeFolder);
}
private void button_playlist_Click(object sender, RoutedEventArgs e) {
string[] folders = Directory.GetDirectories(animeFolder)
.Where(s => !s.EndsWith("torrents") && !s.EndsWith("Grace") && !s.EndsWith("Watched"))
.ToArray();
using (StreamWriter file = new StreamWriter(path: animeFolder + @"\playlist.m3u",
append: false)) {
foreach(String folder in folders)
file.WriteLine(String.Join("\n", Directory.GetFiles(folder)));
}
// MessageBox.Show(String.Join(", ", folders));
// System.Windows.MessageBox.Show(String.Join(", ", ));
// Directory.GetDirectories(animeFolder);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace anime_downloader {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
String animeFolder;
public MainWindow() {
InitializeComponent();
animeFolder = @"D:\Output\anime downloader";
}
private void button_folder_Click(object sender, RoutedEventArgs e) {
Process.Start(animeFolder);
}
private void button_playlist_Click(object sender, RoutedEventArgs e) {
string[] videos = Directory.GetDirectories(animeFolder)
.Where(s => !s.EndsWith("torrents") && !s.EndsWith("Grace") && !s.EndsWith("Watched"))
.SelectMany(f => Directory.GetFiles(f))
.ToArray();
using (StreamWriter file = new StreamWriter(path: animeFolder + @"\playlist.m3u",
append: false)) {
foreach(String video in videos)
file.WriteLine(video);
}
}
}
}
|
Set AssemblyVersion and AssemblyFileVersion to 1.0.0.0 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.*")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Change derived symbols type name to an internal const | using Microsoft.TemplateEngine.Abstractions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
public class DerivedSymbol : BaseValueSymbol
{
public const string TypeName = "derived";
public string ValueTransform { get; set; }
public string ValueSource { get; set; }
public static ISymbolModel FromJObject(JObject jObject, IParameterSymbolLocalizationModel localization, string defaultOverride)
{
DerivedSymbol symbol = FromJObject<DerivedSymbol>(jObject, localization, defaultOverride);
symbol.ValueTransform = jObject.ToString(nameof(ValueTransform));
symbol.ValueSource = jObject.ToString(nameof(ValueSource));
return symbol;
}
}
}
| using Microsoft.TemplateEngine.Abstractions;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
public class DerivedSymbol : BaseValueSymbol
{
internal const string TypeName = "derived";
public string ValueTransform { get; set; }
public string ValueSource { get; set; }
public static ISymbolModel FromJObject(JObject jObject, IParameterSymbolLocalizationModel localization, string defaultOverride)
{
DerivedSymbol symbol = FromJObject<DerivedSymbol>(jObject, localization, defaultOverride);
symbol.ValueTransform = jObject.ToString(nameof(ValueTransform));
symbol.ValueSource = jObject.ToString(nameof(ValueSource));
return symbol;
}
}
}
|
Add uploading of coverage reports to Coveralls | Task("DevBuild")
.IsDependentOn("Build")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
Task("PrBuild")
.IsDependentOn("Build")
.IsDependentOn("Test-NUnit");
Task("KpiBuild")
.IsDependentOn("Build")
.IsDependentOn("Test-NUnit")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
| Task("DevBuild")
.IsDependentOn("Build")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
Task("KpiBuild")
.IsDependentOn("Build")
.IsDependentOn("Test-NUnit")
.IsDependentOn("Upload-Coverage-Report")
.IsDependentOn("Octopus-Packaging")
.IsDependentOn("Octopus-Deployment");
|
Clarify error throw when Command has no name string provided | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EntryPoint {
/// <summary>
/// Used to mark a method as a Command, in a CliCommands class
/// </summary>
[AttributeUsage(
AttributeTargets.Method,
AllowMultiple = false,
Inherited = true)]
public class CommandAttribute : Attribute {
/// <summary>
/// Marks a Method as a Command
/// </summary>
/// <param name="Name">The case in-sensitive name for the command, which is invoked to activate it</param>
public CommandAttribute(string Name) {
if (Name == null || Name.Length == 0) {
throw new ArgumentException(
"You must give a Command a name");
}
this.Name = Name;
}
/// <summary>
/// The case in-sensitive name for the command
/// </summary>
internal string Name { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EntryPoint {
/// <summary>
/// Used to mark a method as a Command, in a CliCommands class
/// </summary>
[AttributeUsage(
AttributeTargets.Method,
AllowMultiple = false,
Inherited = true)]
public class CommandAttribute : Attribute {
/// <summary>
/// Marks a Method as a Command
/// </summary>
/// <param name="Name">The case in-sensitive name for the command, which is invoked to activate it</param>
public CommandAttribute(string Name) {
if (Name == null || Name.Length == 0) {
throw new ArgumentException(
$"A {nameof(CommandAttribute)} was not given a name");
}
this.Name = Name;
}
/// <summary>
/// The case in-sensitive name for the command
/// </summary>
internal string Name { get; set; }
}
}
|
Fix assembly load for plugins | using System;
using System.IO;
using System.Reflection;
namespace AIMP.SDK
{
internal static class CustomAssemblyResolver
{
private static string curPath;
private static bool isInited;
/// <summary>
/// Initializes the specified path.
/// </summary>
/// <param name="path">The path.</param>
public static void Initialize(string path)
{
curPath = path +"\\";
if (!isInited)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
isInited = true;
}
}
/// <summary>
/// Deinitializes this instance.
/// </summary>
public static void Deinitialize()
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
isInited = false;
}
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
string projectDir = Path.GetDirectoryName(curPath);
string shortAssemblyName = args.Name.Substring(0, args.Name.IndexOf(','));
string fileName = Path.Combine(projectDir, shortAssemblyName + ".dll");
if (File.Exists(fileName))
{
Assembly result = Assembly.LoadFrom(fileName);
return result;
}
return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace AIMP.SDK
{
internal static class CustomAssemblyResolver
{
private static string curPath;
private static bool isInited;
/// <summary>
/// Initializes the specified path.
/// </summary>
/// <param name="path">The path.</param>
public static void Initialize(string path)
{
curPath = path +"\\";
if (!isInited)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
isInited = true;
}
}
/// <summary>
/// Deinitializes this instance.
/// </summary>
public static void Deinitialize()
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
isInited = false;
}
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
string projectDir = Path.GetDirectoryName(curPath);
string shortAssemblyName = args.Name.Substring(0, args.Name.IndexOf(','));
string fileName = Path.Combine(projectDir, shortAssemblyName + ".dll");
if (File.Exists(fileName))
{
Assembly result = Assembly.LoadFrom(fileName);
return result;
}
var assemblyPath = Directory.EnumerateFiles(projectDir, shortAssemblyName + ".dll", SearchOption.AllDirectories).FirstOrDefault();
if (assemblyPath != null)
{
return Assembly.LoadFrom(assemblyPath);
}
return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
}
}
}
|
Move the speech_quickstart doc tag so that users can copy and paste all the code. | /*
* Copyright (c) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
// [START speech_quickstart]
using Google.Cloud.Speech.V1Beta1;
// [END speech_quickstart]
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// [START speech_quickstart]
var speech = SpeechClient.Create();
var response = speech.SyncRecognize(new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRate = 16000,
}, RecognitionAudio.FromFile("audio.raw"));
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Console.WriteLine(alternative.Transcript);
}
}
// [END speech_quickstart]
}
}
}
| /*
* Copyright (c) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
// [START speech_quickstart]
using Google.Cloud.Speech.V1Beta1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
var speech = SpeechClient.Create();
var response = speech.SyncRecognize(new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRate = 16000,
}, RecognitionAudio.FromFile("audio.raw"));
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Console.WriteLine(alternative.Transcript);
}
}
}
}
}
// [END speech_quickstart]
|
Add tags to playlist location | using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Playlists.Response
{
[Serializable]
public class PlaylistLocation : UserBasedUpdatableItem
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("links")]
[XmlArrayItem("link")]
public List<Link> Links { get; set; }
[XmlElement("trackCount")]
public int TrackCount { get; set; }
[XmlElement("visibility")]
public PlaylistVisibilityType Visibility { get; set; }
[XmlElement("status")]
public PlaylistStatusType Status { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", Id, Name);
}
}
} | using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Playlists.Response
{
[Serializable]
public class PlaylistLocation : UserBasedUpdatableItem
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("links")]
[XmlArrayItem("link")]
public List<Link> Links { get; set; }
[XmlElement("trackCount")]
public int TrackCount { get; set; }
[XmlElement("visibility")]
public PlaylistVisibilityType Visibility { get; set; }
[XmlElement("status")]
public PlaylistStatusType Status { get; set; }
[XmlElement("tags")]
public List<Tag> Tags { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", Id, Name);
}
}
} |
Fix wildcard path in bootstrap js bundle | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="BundleConfig.cs" company="KriaSoft LLC">
// Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace App.Web
{
using System.Web.Optimization;
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/js/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/js/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/js/bootstrap").Include("~/Scripts/bootstrap/*"));
bundles.Add(new ScriptBundle("~/js/site").Include(
"~/Scripts/Site.js"));
bundles.Add(new StyleBundle("~/css/bootstrap").Include("~/Styles/bootstrap.css"));
bundles.Add(new StyleBundle("~/css/site").Include("~/Styles/Site.css"));
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="BundleConfig.cs" company="KriaSoft LLC">
// Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace App.Web
{
using System.Web.Optimization;
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/js/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/js/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/js/bootstrap").Include("~/Scripts/bootstrap/*.js"));
bundles.Add(new ScriptBundle("~/js/site").Include(
"~/Scripts/Site.js"));
bundles.Add(new StyleBundle("~/css/bootstrap").Include("~/Styles/bootstrap.css"));
bundles.Add(new StyleBundle("~/css/site").Include("~/Styles/Site.css"));
}
}
} |
Write value separators when serializing dynamic body | using System.Collections.Generic;
namespace Elasticsearch.Net
{
internal class DynamicBodyFormatter : IJsonFormatter<DynamicBody>
{
private static readonly DictionaryFormatter<string, object> DictionaryFormatter =
new DictionaryFormatter<string, object>();
public void Serialize(ref JsonWriter writer, DynamicBody value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteBeginObject();
var formatter = formatterResolver.GetFormatter<object>();
foreach (var kv in (IDictionary<string, object>)value)
{
writer.WritePropertyName(kv.Key);
formatter.Serialize(ref writer, kv.Value, formatterResolver);
}
writer.WriteEndObject();
}
public DynamicBody Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var dictionary = DictionaryFormatter.Deserialize(ref reader, formatterResolver);
return DynamicBody.Create(dictionary);
}
}
}
| using System.Collections.Generic;
namespace Elasticsearch.Net
{
internal class DynamicBodyFormatter : IJsonFormatter<DynamicBody>
{
private static readonly DictionaryFormatter<string, object> DictionaryFormatter =
new DictionaryFormatter<string, object>();
public void Serialize(ref JsonWriter writer, DynamicBody value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteBeginObject();
var formatter = formatterResolver.GetFormatter<object>();
var count = 0;
foreach (var kv in (IDictionary<string, object>)value)
{
if (count > 0)
writer.WriteValueSeparator();
writer.WritePropertyName(kv.Key);
formatter.Serialize(ref writer, kv.Value, formatterResolver);
count++;
}
writer.WriteEndObject();
}
public DynamicBody Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var dictionary = DictionaryFormatter.Deserialize(ref reader, formatterResolver);
return DynamicBody.Create(dictionary);
}
}
}
|
Reduce unnecessary logging of missing optional methods | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Harmony
{
internal static class PatchTools
{
static readonly Dictionary<object, object> objectReferences = new Dictionary<object, object>();
internal static void RememberObject(object key, object value)
{
objectReferences[key] = value;
}
internal static MethodInfo GetPatchMethod<T>(Type patchType, string name)
{
var attributeType = typeof(T).FullName;
var method = patchType.GetMethods(AccessTools.all)
.FirstOrDefault(m => m.GetCustomAttributes(true).Any(a => a.GetType().FullName == attributeType));
if (method == null)
method = AccessTools.Method(patchType, name);
return method;
}
[UpgradeToLatestVersion(1)]
internal static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler)
{
prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Harmony
{
internal static class PatchTools
{
static readonly Dictionary<object, object> objectReferences = new Dictionary<object, object>();
internal static void RememberObject(object key, object value)
{
objectReferences[key] = value;
}
internal static MethodInfo GetPatchMethod<T>(Type patchType, string name)
{
var attributeType = typeof(T).FullName;
var method = patchType.GetMethods(AccessTools.all)
.FirstOrDefault(m => m.GetCustomAttributes(true).Any(a => a.GetType().FullName == attributeType));
if (method == null)
{
// not-found is common and normal case, don't use AccessTools which will generate not-found warnings
method = patchType.GetMethod(name, AccessTools.all);
}
return method;
}
[UpgradeToLatestVersion(1)]
internal static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler)
{
prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
}
}
} |
Fix bug with logic for if the token is valid | using System;
using Newtonsoft.Json;
namespace Stranne.VasttrafikNET.Models
{
internal class Token
{
private DateTimeOffset _createDate = DateTimeOffset.Now;
[JsonProperty("Expires_In")]
public int ExpiresIn { get; set; }
[JsonProperty("Access_Token")]
public string AccessToken { get; set; }
public bool IsValid() => _createDate.AddSeconds(ExpiresIn) < DateTimeOffset.Now;
}
}
| using System;
using Newtonsoft.Json;
namespace Stranne.VasttrafikNET.Models
{
internal class Token
{
private DateTimeOffset _createDate = DateTimeOffset.Now;
[JsonProperty("Expires_In")]
public int ExpiresIn { get; set; }
[JsonProperty("Access_Token")]
public string AccessToken { get; set; }
public bool IsValid() => _createDate.AddSeconds(ExpiresIn) > DateTimeOffset.Now;
}
}
|
Raise rating of gif search | namespace awesome_bot.Giphy
{
public static partial class GiphyEndPoints
{
public class RandomEndPoint
{
private const string RandomPath = "/v1/gifs/random";
public string Build(string searchText, Rating rating = null)
=> string.Join(string.Empty, Root, RandomPath, "?",
$"api_key={ApiKey}&tag={searchText}&rating={rating ?? Rating.G}");
}
}
} | namespace awesome_bot.Giphy
{
public static partial class GiphyEndPoints
{
public class RandomEndPoint
{
private const string RandomPath = "/v1/gifs/random";
public string Build(string searchText, Rating rating = null)
=> string.Join(string.Empty, Root, RandomPath, "?",
$"api_key={ApiKey}&tag={searchText}&rating={rating ?? Rating.PG13}");
}
}
} |
Add JsonProperty attribute on each property | namespace Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
{
/// <summary>
/// This represents the parameters entity to render api.js.
/// </summary>
/// <remarks>More details: https://developers.google.com/recaptcha/docs/display#js_param</remarks>
public partial class ResourceParameters
{
/// <summary>
/// Gets or sets the callback method name on load.
/// </summary>
public string OnLoad { get; set; }
/// <summary>
/// Gets or sets the render option.
/// </summary>
public WidgetRenderType Render { get; set; }
/// <summary>
/// Gets or sets the language code to display reCaptcha control.
/// </summary>
public WidgetLanguageCode LanguageCode { get; set; }
}
} | using Newtonsoft.Json;
namespace Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
{
/// <summary>
/// This represents the parameters entity to render api.js.
/// </summary>
/// <remarks>More details: https://developers.google.com/recaptcha/docs/display#js_param</remarks>
public partial class ResourceParameters
{
/// <summary>
/// Gets or sets the callback method name on load.
/// </summary>
[JsonProperty(PropertyName = "onload")]
public string OnLoad { get; set; }
/// <summary>
/// Gets or sets the render option.
/// </summary>
[JsonProperty(PropertyName = "render")]
public WidgetRenderType Render { get; set; }
/// <summary>
/// Gets or sets the language code to display reCaptcha control.
/// </summary>
[JsonProperty(PropertyName = "hl")]
public WidgetLanguageCode LanguageCode { get; set; }
}
} |
Add more supported image extensions | using System;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
namespace DesktopWidgets.Helpers
{
public static class ImageHelper
{
public static readonly List<string> SupportedExtensions = new List<string>
{
".bmp",
".gif",
".ico",
".jpg",
".jpeg",
".png",
".tiff"
};
public static bool IsSupported(string extension)
{
return SupportedExtensions.Contains(extension.ToLower());
}
public static BitmapImage LoadBitmapImageFromPath(string path)
{
var bmi = new BitmapImage();
bmi.BeginInit();
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
bmi.EndInit();
bmi.Freeze();
return bmi;
}
}
} | using System;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
namespace DesktopWidgets.Helpers
{
public static class ImageHelper
{
// https://msdn.microsoft.com/en-us/library/ee719654(v=VS.85).aspx#wpfc_codecs.
public static readonly List<string> SupportedExtensions = new List<string>
{
".bmp",
".gif",
".ico",
".jpg",
".jpeg",
".png",
".tiff",
".wmp",
".dds"
};
public static bool IsSupported(string extension)
{
return SupportedExtensions.Contains(extension.ToLower());
}
public static BitmapImage LoadBitmapImageFromPath(string path)
{
var bmi = new BitmapImage();
bmi.BeginInit();
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
bmi.EndInit();
bmi.Freeze();
return bmi;
}
}
} |
Include all parameters in visibleRaycast | using UnityEngine;
using System.Collections;
public class PhysicsHelper2D
{
/// <summary>
/// Ignores collision for every single GameObject with a particular tag
/// </summary>
/// <param name="object1"></param>
/// <param name="tag"></param>
/// <param name="ignore"></param>
public static void ignoreCollisionWithTag(GameObject object1, string tag, bool ignore)
{
Collider2D[] colliders = object1.GetComponents<Collider2D>();
GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject taggedObject in taggedObjects)
{
for (int i = 0; i < colliders.Length; i++)
{
Physics2D.IgnoreCollision(colliders[i], taggedObject.GetComponent<Collider2D>(), ignore);
}
}
}
/// <summary>
/// performs Physics2D.raycast and also Debug.DrawLine with the same vector
/// </summary>
public static bool visibleRaycast(Vector2 origin, Vector2 direction, float distance = float.PositiveInfinity, Color? color = null)
{
Debug.DrawLine(origin, origin + (direction.resize(distance)), color ?? Color.white);
return Physics2D.Raycast(origin, direction, distance);
}
}
| using UnityEngine;
using System.Collections;
public class PhysicsHelper2D
{
/// <summary>
/// Ignores collision for every single GameObject with a particular tag
/// </summary>
/// <param name="object1"></param>
/// <param name="tag"></param>
/// <param name="ignore"></param>
public static void ignoreCollisionWithTag(GameObject object1, string tag, bool ignore)
{
Collider2D[] colliders = object1.GetComponents<Collider2D>();
GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject taggedObject in taggedObjects)
{
for (int i = 0; i < colliders.Length; i++)
{
Physics2D.IgnoreCollision(colliders[i], taggedObject.GetComponent<Collider2D>(), ignore);
}
}
}
/// <summary>
/// performs Physics2D.raycast and also Debug.DrawLine with the same vector
/// </summary>
public static RaycastHit2D visibleRaycast(Vector2 origin, Vector2 direction,
float distance = float.PositiveInfinity, int layerMask = Physics2D.DefaultRaycastLayers,
float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity,
Color? color = null)
{
Debug.DrawLine(origin, origin + (direction.resize(distance)), color ?? Color.white);
return Physics2D.Raycast(origin, direction, distance, layerMask, minDepth, maxDepth);
}
}
|
Comment test harness unit test with lame check | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="HarnessTests.cs" company="LunchBox corp">
// Copyright 2014 The Lunch-Box mob:
// Ozgur DEVELIOGLU (@Zgurrr)
// Cyrille DUPUYDAUBY (@Cyrdup)
// Tomasz JASKULA (@tjaskula)
// Mendel MONTEIRO-BECKERMAN (@MendelMonteiro)
// Thomas PIERRAIN (@tpierrain)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SimpleOrderRouting.Tests
{
using NFluent;
using SimpleOrderRouting.Journey1;
using Xunit;
public class HarnessTests
{
[Fact]
public void ShouldReturnALatency()
{
var runner = new SorTestHarness();
runner.Run();
Check.That<double>(runner.AverageLatency).IsPositive();
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="HarnessTests.cs" company="LunchBox corp">
// Copyright 2014 The Lunch-Box mob:
// Ozgur DEVELIOGLU (@Zgurrr)
// Cyrille DUPUYDAUBY (@Cyrdup)
// Tomasz JASKULA (@tjaskula)
// Mendel MONTEIRO-BECKERMAN (@MendelMonteiro)
// Thomas PIERRAIN (@tpierrain)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SimpleOrderRouting.Tests
{
using NFluent;
using SimpleOrderRouting.Journey1;
using Xunit;
public class HarnessTests
{
//[Fact]
public void ShouldReturnALatency()
{
var runner = new SorTestHarness();
runner.Run();
Check.That<double>(runner.AverageLatency).IsPositive();
}
}
} |
Resolve full for specified .deployment project file. | using System;
using System.IO;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public class DeploymentConfiguration
{
internal const string DeployConfigFile = ".deployment";
private readonly IniFile _iniFile;
private readonly string _path;
public DeploymentConfiguration(string path)
{
_path = path;
_iniFile = new IniFile(Path.Combine(path, DeployConfigFile));
}
public string ProjectPath
{
get
{
string projectPath = _iniFile.GetSectionValue("config", "project");
if (String.IsNullOrEmpty(projectPath))
{
return null;
}
return Path.Combine(_path, projectPath.TrimStart('/', '\\'));
}
}
}
}
| using System;
using System.IO;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public class DeploymentConfiguration
{
internal const string DeployConfigFile = ".deployment";
private readonly IniFile _iniFile;
private readonly string _path;
public DeploymentConfiguration(string path)
{
_path = path;
_iniFile = new IniFile(Path.Combine(path, DeployConfigFile));
}
public string ProjectPath
{
get
{
string projectPath = _iniFile.GetSectionValue("config", "project");
if (String.IsNullOrEmpty(projectPath))
{
return null;
}
return Path.GetFullPath(Path.Combine(_path, projectPath.TrimStart('/', '\\')));
}
}
}
}
|
Work around bug in FormsAuthMiddleware | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Owin;
namespace JabbR.Middleware
{
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using AppFunc = Func<IDictionary<string, object>, Task>;
public class FixCookieHandler
{
private readonly AppFunc _next;
private readonly TicketDataHandler _ticketHandler;
public FixCookieHandler(AppFunc next, TicketDataHandler ticketHandler)
{
_ticketHandler = ticketHandler;
_next = next;
}
public Task Invoke(IDictionary<string, object> env)
{
var request = new OwinRequest(env);
var cookies = request.GetCookies();
string cookieValue;
if (cookies != null && cookies.TryGetValue("jabbr.id", out cookieValue))
{
AuthenticationTicket ticket = _ticketHandler.Unprotect(cookieValue);
}
return _next(env);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
namespace JabbR.Middleware
{
using AppFunc = Func<IDictionary<string, object>, Task>;
public class FixCookieHandler
{
private readonly AppFunc _next;
private readonly TicketDataHandler _ticketHandler;
public FixCookieHandler(AppFunc next, TicketDataHandler ticketHandler)
{
_ticketHandler = ticketHandler;
_next = next;
}
public Task Invoke(IDictionary<string, object> env)
{
var request = new OwinRequest(env);
var cookies = request.GetCookies();
string cookieValue;
if (cookies != null && cookies.TryGetValue("jabbr.id", out cookieValue))
{
AuthenticationTicket ticket = _ticketHandler.Unprotect(cookieValue);
if (ticket.Extra == null)
{
// The forms auth module has a bug where it null refs on a null Extra
var headers = request.Get<IDictionary<string, string[]>>(Owin.Types.OwinConstants.RequestHeaders);
var cookieBuilder = new StringBuilder();
foreach (var cookie in cookies)
{
// Skip the jabbr.id cookie
if (cookie.Key == "jabbr.id")
{
continue;
}
if (cookieBuilder.Length > 0)
{
cookieBuilder.Append(";");
}
cookieBuilder.Append(cookie.Key)
.Append("=")
.Append(Uri.EscapeDataString(cookie.Value));
}
headers["Cookie"] = new[] { cookieBuilder.ToString() };
}
}
return _next(env);
}
}
}
|
Remove an useless namespace usage | using BlackFox.Roslyn.TestDiagnostics.NoNewGuid;
using BlackFox.Roslyn.TestDiagnostics.NoStringEmpty;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NFluent;
using TestDiagnosticsUnitTests.Helpers.DiagnosticTestHelpers;
namespace TestDiagnosticsUnitTests
{
[TestClass]
public class NoNewGuidAnalyzerTests
{
[TestMethod]
public void No_diagnostic_on_guid_empty()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = Guid.Empty;");
Check.That(diagnostics).IsEmpty();
}
[TestMethod]
public void Diagnostic_new_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_namespace_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new System.Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_fully_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new global::System.Guid();");
Check.That(diagnostics).HasSize(1);
}
}
}
| using BlackFox.Roslyn.TestDiagnostics.NoNewGuid;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NFluent;
using TestDiagnosticsUnitTests.Helpers.DiagnosticTestHelpers;
namespace TestDiagnosticsUnitTests
{
[TestClass]
public class NoNewGuidAnalyzerTests
{
[TestMethod]
public void No_diagnostic_on_guid_empty()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = Guid.Empty;");
Check.That(diagnostics).IsEmpty();
}
[TestMethod]
public void Diagnostic_new_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_namespace_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new System.Guid();");
Check.That(diagnostics).HasSize(1);
}
[TestMethod]
public void Diagnostic_on_fully_qualified_call()
{
var analyzer = new NoNewGuidAnalyzer();
var diagnostics = GetDiagnosticsInSimpleCode(analyzer, "var x = new global::System.Guid();");
Check.That(diagnostics).HasSize(1);
}
}
}
|
Add null check for request. | using System.Web;
namespace FeatureSwitcher.DebugConsole.Behaviours
{
public class DebugConsoleBehaviour
{
private readonly bool _isForced = false;
private DebugConsoleBehaviour(bool isForced)
{
this._isForced = isForced;
}
internal static FeatureSwitcher.Feature.Behavior AlwaysEnabled => new DebugConsoleBehaviour(true).Behaviour;
public static FeatureSwitcher.Feature.Behavior IsEnabled => new DebugConsoleBehaviour(false).Behaviour;
private bool? Behaviour(Feature.Name name)
{
if (HttpContext.Current == null)
return null;
if (name == null || string.IsNullOrWhiteSpace(name.Value))
return null;
if (HttpContext.Current.IsDebuggingEnabled || this._isForced)
{
var cookie = HttpContext.Current.Request.Cookies[name.Value];
if (cookie == null)
return null;
return cookie.Value == "true";
}
return null;
}
}
}
| using System.Web;
namespace FeatureSwitcher.DebugConsole.Behaviours
{
public class DebugConsoleBehaviour
{
private readonly bool _isForced = false;
private DebugConsoleBehaviour(bool isForced)
{
this._isForced = isForced;
}
internal static FeatureSwitcher.Feature.Behavior AlwaysEnabled => new DebugConsoleBehaviour(true).Behaviour;
public static FeatureSwitcher.Feature.Behavior IsEnabled => new DebugConsoleBehaviour(false).Behaviour;
private bool? Behaviour(Feature.Name name)
{
if (HttpContext.Current == null)
return null;
if (name == null || string.IsNullOrWhiteSpace(name.Value))
return null;
if (HttpContext.Current.IsDebuggingEnabled || this._isForced)
{
if (HttpContext.Current.Request == null)
return null;
var cookie = HttpContext.Current.Request.Cookies[name.Value];
if (cookie == null)
return null;
return cookie.Value == "true";
}
return null;
}
}
}
|
Update SystemClock test to account for time passing. | // Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
namespace NodaTime.Test
{
public class SystemClockTest
{
[Test]
public void InstanceNow()
{
long frameworkNowTicks = NodaConstants.BclEpoch.PlusTicks(DateTime.UtcNow.Ticks).ToUnixTimeTicks();
long nodaTicks = SystemClock.Instance.GetCurrentInstant().ToUnixTimeTicks();
Assert.Less(Math.Abs(nodaTicks - frameworkNowTicks), Duration.FromSeconds(1).BclCompatibleTicks);
}
[Test]
public void Sanity()
{
// Previously all the conversions missed the SystemConversions.DateTimeEpochTicks,
// so they were self-consistent but not consistent with sanity.
Instant minimumExpected = Instant.FromUtc(2011, 8, 1, 0, 0);
Instant maximumExpected = Instant.FromUtc(2020, 1, 1, 0, 0);
Instant now = SystemClock.Instance.GetCurrentInstant();
Assert.Less(minimumExpected.ToUnixTimeTicks(), now.ToUnixTimeTicks());
Assert.Less(now.ToUnixTimeTicks(), maximumExpected.ToUnixTimeTicks());
}
}
}
| // Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
namespace NodaTime.Test
{
public class SystemClockTest
{
[Test]
public void InstanceNow()
{
long frameworkNowTicks = NodaConstants.BclEpoch.PlusTicks(DateTime.UtcNow.Ticks).ToUnixTimeTicks();
long nodaTicks = SystemClock.Instance.GetCurrentInstant().ToUnixTimeTicks();
Assert.Less(Math.Abs(nodaTicks - frameworkNowTicks), Duration.FromSeconds(1).BclCompatibleTicks);
}
[Test]
public void Sanity()
{
// Previously all the conversions missed the SystemConversions.DateTimeEpochTicks,
// so they were self-consistent but not consistent with sanity.
Instant minimumExpected = Instant.FromUtc(2019, 8, 1, 0, 0);
Instant maximumExpected = Instant.FromUtc(2025, 1, 1, 0, 0);
Instant now = SystemClock.Instance.GetCurrentInstant();
Assert.Less(minimumExpected.ToUnixTimeTicks(), now.ToUnixTimeTicks());
Assert.Less(now.ToUnixTimeTicks(), maximumExpected.ToUnixTimeTicks());
}
}
}
|
Make usage of UrlBuilder and fix namespace | using SsrsDeploy;
using SsrsDeploy.ReportingService;
using SsrsDeploy.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SsrDeploy.Factory
{
class ServiceFactory
{
private readonly ReportingService2010 rs;
public ServiceFactory(Options options)
{
this.rs = GetReportingService(options);
}
protected virtual ReportingService2010 GetReportingService(Options options)
{
var rs = new ReportingService2010();
rs.Url = GetUrl(options);
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
return rs;
}
public ReportService GetReportService()
{
return new ReportService(rs);
}
public FolderService GetFolderService()
{
return new FolderService(rs);
}
public DataSourceService GetDataSourceService()
{
return new DataSourceService(rs);
}
public static string GetUrl(Options options)
{
var baseUrl = options.Url;
var builder = new UriBuilder(baseUrl);
if (string.IsNullOrEmpty(builder.Scheme))
builder.Scheme = Uri.UriSchemeHttp;
if (builder.Scheme != Uri.UriSchemeHttp && builder.Scheme != Uri.UriSchemeHttps)
throw new ArgumentException();
if (!builder.Path.EndsWith("/ReportService2010.asmx"))
builder.Path += (builder.Path.EndsWith("/") ? "" : "/") + "ReportService2010.asmx";
if (builder.Path.Equals("/ReportService2010.asmx"))
builder.Path = "/ReportServer" + builder.Path;
if (builder.Uri.IsDefaultPort)
return builder.Uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped);
return builder.ToString();
}
}
}
| using SsrsDeploy;
using SsrsDeploy.ReportingService;
using SsrsDeploy.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SsrsDeploy.Factory
{
class ServiceFactory
{
private readonly ReportingService2010 rs;
public ServiceFactory(Options options)
{
this.rs = GetReportingService(options);
}
protected virtual ReportingService2010 GetReportingService(Options options)
{
var rs = new ReportingService2010();
var urlBuilder = new UrlBuilder();
urlBuilder.Setup(options);
urlBuilder.Build();
rs.Url = urlBuilder.GetUrl();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
return rs;
}
public ReportService GetReportService()
{
return new ReportService(rs);
}
public FolderService GetFolderService()
{
return new FolderService(rs);
}
public DataSourceService GetDataSourceService()
{
return new DataSourceService(rs);
}
}
}
|
Allow for grouping to null | using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace Verdeler
{
internal class ConcurrencyLimiter<TSubject>
{
private readonly Func<TSubject, object> _subjectReductionMap;
private readonly int _concurrencyLimit;
private readonly ConcurrentDictionary<object, SemaphoreSlim> _semaphores
= new ConcurrentDictionary<object, SemaphoreSlim>();
public ConcurrencyLimiter(Func<TSubject, object> subjectReductionMap, int concurrencyLimit)
{
if (concurrencyLimit <= 0)
{
throw new ArgumentException(@"Concurrency limit must be greater than 0.", nameof(concurrencyLimit));
}
_subjectReductionMap = subjectReductionMap;
_concurrencyLimit = concurrencyLimit;
}
public async Task WaitFor(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
await semaphore.WaitAsync().ConfigureAwait(false);
}
public void Release(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
semaphore.Release();
}
private SemaphoreSlim GetSemaphoreForReducedSubject(TSubject subject)
{
var reducedSubject = _subjectReductionMap.Invoke(subject);
var semaphore = _semaphores.GetOrAdd(reducedSubject, new SemaphoreSlim(_concurrencyLimit));
return semaphore;
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace Verdeler
{
internal class ConcurrencyLimiter<TSubject>
{
private readonly Func<TSubject, object> _subjectReductionMap;
private readonly int _concurrencyLimit;
private readonly ConcurrentDictionary<object, SemaphoreSlim> _semaphores
= new ConcurrentDictionary<object, SemaphoreSlim>();
public ConcurrencyLimiter(Func<TSubject, object> subjectReductionMap, int concurrencyLimit)
{
if (concurrencyLimit <= 0)
{
throw new ArgumentException(@"Concurrency limit must be greater than 0.", nameof(concurrencyLimit));
}
_subjectReductionMap = subjectReductionMap;
_concurrencyLimit = concurrencyLimit;
}
public async Task WaitFor(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
if (semaphore == null)
{
await Task.FromResult(0);
}
else
{
await semaphore.WaitAsync().ConfigureAwait(false);
}
}
public void Release(TSubject subject)
{
var semaphore = GetSemaphoreForReducedSubject(subject);
semaphore?.Release();
}
private SemaphoreSlim GetSemaphoreForReducedSubject(TSubject subject)
{
var reducedSubject = _subjectReductionMap.Invoke(subject);
if (reducedSubject == null)
{
return null;
}
var semaphore = _semaphores.GetOrAdd(reducedSubject, new SemaphoreSlim(_concurrencyLimit));
return semaphore;
}
}
}
|
Add access token to project. | using System.Collections.Generic;
namespace Bibliotheca.Server.Depository.FileSystem.Core.DataTransferObjects
{
public class ProjectDto
{
public ProjectDto()
{
Tags = new List<string>();
VisibleBranches = new List<string>();
EditLinks = new List<EditLinkDto>();
}
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string DefaultBranch { get; set; }
public List<string> VisibleBranches { get; set; }
public List<string> Tags { get; private set; }
public string Group { get; set; }
public string ProjectSite { get; set; }
public List<ContactPersonDto> ContactPeople { get; set; }
public List<EditLinkDto> EditLinks { get; set; }
}
} | using System.Collections.Generic;
namespace Bibliotheca.Server.Depository.FileSystem.Core.DataTransferObjects
{
public class ProjectDto
{
public ProjectDto()
{
Tags = new List<string>();
VisibleBranches = new List<string>();
EditLinks = new List<EditLinkDto>();
}
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string DefaultBranch { get; set; }
public List<string> VisibleBranches { get; set; }
public List<string> Tags { get; private set; }
public string Group { get; set; }
public string ProjectSite { get; set; }
public List<ContactPersonDto> ContactPeople { get; set; }
public List<EditLinkDto> EditLinks { get; set; }
public string AccessToken { get; set; }
}
} |
Add sample script when a script is created | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Duality;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython.Resources
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScript)]
public class PythonScript : Resource
{
protected string _content;
public string Content { get { return _content; } }
public void UpdateContent(string content)
{
_content = content;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Duality;
using Duality.Editor;
namespace RockyTV.Duality.Plugins.IronPython.Resources
{
[EditorHintCategory(Properties.ResNames.CategoryScripts)]
[EditorHintImage(Properties.ResNames.IconScript)]
public class PythonScript : Resource
{
protected string _content;
public string Content { get { return _content; } }
public PythonScript()
{
var sb = new StringBuilder();
sb.AppendLine("# You can access the parent GameObject by calling `gameObject`.");
sb.AppendLine("# To use Duality objects, you must first import them.");
sb.AppendLine("# Example:");
sb.AppendLine(@"#\tfrom Duality import Vector2");
sb.AppendLine();
sb.AppendLine("class PyModule: ");
sb.AppendLine(" def __init__(self):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine("# The `start` function is called whenever a component is initializing.");
sb.AppendLine(" def start(self):");
sb.AppendLine(" pass");
sb.AppendLine();
sb.AppendLine("# The `update` function is called whenever an update happens, and includes a delta.");
sb.AppendLine(" def update(self, delta):");
sb.AppendLine(" pass");
sb.AppendLine();
_content = sb.ToString();
}
public void UpdateContent(string content)
{
_content = content;
}
}
}
|
Rename ENVVAR in line with previous one (`OSU_TESTS_NO_TIMEOUT`) | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using NUnit.Framework;
namespace osu.Game.Tests
{
/// <summary>
/// An attribute to mark any flaky tests.
/// Will add a retry count unless environment variable `FAIL_FLAKY_TESTS` is set to `1`.
/// </summary>
public class FlakyTestAttribute : RetryAttribute
{
public FlakyTestAttribute()
: this(10)
{
}
public FlakyTestAttribute(int tryCount)
: base(Environment.GetEnvironmentVariable("FAIL_FLAKY_TESTS") == "1" ? 0 : tryCount)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using NUnit.Framework;
namespace osu.Game.Tests
{
/// <summary>
/// An attribute to mark any flaky tests.
/// Will add a retry count unless environment variable `FAIL_FLAKY_TESTS` is set to `1`.
/// </summary>
public class FlakyTestAttribute : RetryAttribute
{
public FlakyTestAttribute()
: this(10)
{
}
public FlakyTestAttribute(int tryCount)
: base(Environment.GetEnvironmentVariable("OSU_TESTS_FAIL_FLAKY") == "1" ? 0 : tryCount)
{
}
}
}
|
Make sure blue alien is visible next time you visit Sprites Room. | using UnityEngine;
using System.Collections;
using Fungus;
public class SpritesRoom : Room
{
public Room menuRoom;
public Animator blueAlienAnim;
public SpriteController blueAlienSprite;
void OnEnter()
{
Say("Pink Alien says to Blue Alien...");
Say("...'Show me your funky moves!'");
SetAnimatorTrigger(blueAlienAnim, "StartBlueWalk");
Say("Blue Alien starts to dance.");
Say("Tap on Blue Alien to stop him dancing.");
}
// This method is called from the Button component on the BlueAlien object
void StopDancing()
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Nice moves there Blue Alien!");
Say("Uh oh, you look like you're turning a little green after all that dancing!");
SetAnimatorTrigger(blueAlienAnim, "StartGreenWalk");
Say("Never mind, you'll feel better soon!");
}
void OnAnimationEvent(string eventName)
{
if (eventName == "GreenAnimationFinished")
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Well done Blue Alien! Time to say goodbye!");
FadeSprite(blueAlienSprite, 0, 1f);
Wait(1f);
Say("Heh. That Blue Alien - what a guy!");
MoveToRoom(menuRoom);
}
}
}
| using UnityEngine;
using System.Collections;
using Fungus;
public class SpritesRoom : Room
{
public Room menuRoom;
public Animator blueAlienAnim;
public SpriteController blueAlienSprite;
void OnEnter()
{
ShowSprite(blueAlienSprite);
Say("Pink Alien says to Blue Alien...");
Say("...'Show me your funky moves!'");
SetAnimatorTrigger(blueAlienAnim, "StartBlueWalk");
Say("Blue Alien starts to dance.");
Say("Tap on Blue Alien to stop him dancing.");
}
// This method is called from the Button component on the BlueAlien object
void StopDancing()
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Nice moves there Blue Alien!");
Say("Uh oh, you look like you're turning a little green after all that dancing!");
SetAnimatorTrigger(blueAlienAnim, "StartGreenWalk");
Say("Never mind, you'll feel better soon!");
}
void OnAnimationEvent(string eventName)
{
if (eventName == "GreenAnimationFinished")
{
SetAnimatorTrigger(blueAlienAnim, "Stop");
Say("Well done Blue Alien! Time to say goodbye!");
FadeSprite(blueAlienSprite, 0, 1f);
Wait(1f);
Say("Heh. That Blue Alien - what a guy!");
MoveToRoom(menuRoom);
}
}
}
|
Add a comment explaining why we're using QuadVertexBuffer | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.OpenGL.Buffers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.OpenGL.Vertices;
using osuTK.Graphics.ES30;
namespace osu.Framework.Graphics.Batches
{
/// <summary>
/// A batch to be used when drawing triangles with <see cref="TextureGLSingle.DrawTriangle"/>.
/// </summary>
public class TriangleBatch<T> : VertexBatch<T>
where T : struct, IEquatable<T>, IVertex
{
public TriangleBatch(int size, int maxBuffers)
: base(size, maxBuffers)
{
}
protected override VertexBuffer<T> CreateVertexBuffer() => new QuadVertexBuffer<T>(Size, BufferUsageHint.DynamicDraw);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.OpenGL.Buffers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.OpenGL.Vertices;
using osuTK.Graphics.ES30;
namespace osu.Framework.Graphics.Batches
{
/// <summary>
/// A batch to be used when drawing triangles with <see cref="TextureGLSingle.DrawTriangle"/>.
/// </summary>
public class TriangleBatch<T> : VertexBatch<T>
where T : struct, IEquatable<T>, IVertex
{
public TriangleBatch(int size, int maxBuffers)
: base(size, maxBuffers)
{
}
//We can re-use the QuadVertexBuffer as both Triangles and Quads have four Vertices and six indices.
protected override VertexBuffer<T> CreateVertexBuffer() => new QuadVertexBuffer<T>(Size, BufferUsageHint.DynamicDraw);
}
}
|
Bump número de versión a 0.8.4.0 | /*
AssemblyInfo.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright (c) 2011 - 2018 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Reflection;
[assembly: AssemblyCompany("TheXDS! non-Corp.")]
[assembly: AssemblyProduct("Morgan's CLR Advanced Runtime")]
[assembly: AssemblyCopyright("Copyright © 2011-2018 César Andrés Morgan")]
[assembly: AssemblyVersion("0.8.3.4")]
#if CLSCompliance
[assembly: System.CLSCompliant(true)]
#endif | /*
AssemblyInfo.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright (c) 2011 - 2018 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Reflection;
[assembly: AssemblyCompany("TheXDS! non-Corp.")]
[assembly: AssemblyProduct("Morgan's CLR Advanced Runtime")]
[assembly: AssemblyCopyright("Copyright © 2011-2018 César Andrés Morgan")]
[assembly: AssemblyVersion("0.8.4.0")]
#if CLSCompliance
[assembly: System.CLSCompliant(true)]
#endif |
Correct misspelled word in the interface summary | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Timing
{
/// <summary>
/// A clock which will only update its current time when a frame proces is triggered.
/// Useful for keeping a consistent time state across an individual update.
/// </summary>
public interface IFrameBasedClock : IClock
{
/// <summary>
/// Elapsed time since last frame in milliseconds.
/// </summary>
double ElapsedFrameTime { get; }
/// <summary>
/// A moving average representation of the frames per second of this clock.
/// Do not use this for any timing purposes (use <see cref="ElapsedFrameTime"/> instead).
/// </summary>
double FramesPerSecond { get; }
FrameTimeInfo TimeInfo { get; }
/// <summary>
/// Processes one frame. Generally should be run once per update loop.
/// </summary>
void ProcessFrame();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Timing
{
/// <summary>
/// A clock which will only update its current time when a frame process is triggered.
/// Useful for keeping a consistent time state across an individual update.
/// </summary>
public interface IFrameBasedClock : IClock
{
/// <summary>
/// Elapsed time since last frame in milliseconds.
/// </summary>
double ElapsedFrameTime { get; }
/// <summary>
/// A moving average representation of the frames per second of this clock.
/// Do not use this for any timing purposes (use <see cref="ElapsedFrameTime"/> instead).
/// </summary>
double FramesPerSecond { get; }
FrameTimeInfo TimeInfo { get; }
/// <summary>
/// Processes one frame. Generally should be run once per update loop.
/// </summary>
void ProcessFrame();
}
}
|
Add new contructors to Index.cs | using System.Xml.Serialization;
namespace Gigobyte.Daterpillar
{
/// <summary>
/// Represents a database indexed column.
/// </summary>
public struct IndexColumn
{
/// <summary>
/// Gets or sets the column's name.
/// </summary>
/// <value>The name.</value>
[XmlText]
public string Name { get; set; }
/// <summary>
/// Gets or sets the column's order.
/// </summary>
/// <value>The order.</value>
[XmlAttribute("order")]
public SortOrder Order { get; set; }
}
} | using System.Xml.Serialization;
namespace Gigobyte.Daterpillar
{
/// <summary>
/// Represents a database indexed column.
/// </summary>
public struct IndexColumn
{
/// <summary>
/// Initializes a new instance of the <see cref="IndexColumn"/> struct.
/// </summary>
/// <param name="name">The name.</param>
public IndexColumn(string name) : this(name, SortOrder.ASC)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="IndexColumn"/> struct.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="order">The order.</param>
public IndexColumn(string name, SortOrder order)
{
Name = name;
Order = order;
}
/// <summary>
/// Gets or sets the column's name.
/// </summary>
/// <value>The name.</value>
[XmlText]
public string Name { get; set; }
/// <summary>
/// Gets or sets the column's order.
/// </summary>
/// <value>The order.</value>
[XmlAttribute("order")]
public SortOrder Order { get; set; }
}
} |
Clear comments list on navigation | using CodeHub.Helpers;
using CodeHub.ViewModels;
using Octokit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace CodeHub.Views
{
public sealed partial class IssueDetailView : Windows.UI.Xaml.Controls.Page
{
public IssueDetailViewmodel ViewModel;
public IssueDetailView()
{
this.InitializeComponent();
ViewModel = new IssueDetailViewmodel();
this.DataContext = ViewModel;
NavigationCacheMode = NavigationCacheMode.Required;
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
commentsListView.SelectedIndex = -1;
if (e.NavigationMode != NavigationMode.Back)
{
await ViewModel.Load((e.Parameter as Tuple<string,string, Issue>));
}
}
}
}
| using CodeHub.Helpers;
using CodeHub.ViewModels;
using Octokit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace CodeHub.Views
{
public sealed partial class IssueDetailView : Windows.UI.Xaml.Controls.Page
{
public IssueDetailViewmodel ViewModel;
public IssueDetailView()
{
this.InitializeComponent();
ViewModel = new IssueDetailViewmodel();
this.DataContext = ViewModel;
NavigationCacheMode = NavigationCacheMode.Required;
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
commentsListView.SelectedIndex = -1;
if (e.NavigationMode != NavigationMode.Back)
{
if (ViewModel.Comments != null)
{
ViewModel.Comments.Clear();
}
await ViewModel.Load((e.Parameter as Tuple<string,string, Issue>));
}
}
}
}
|
Use `ScheduleAfterChildren` to better match comment | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A container which is serialised and can encapsulate multiple skinnable elements into a single return type (for consumption via <see cref="ISkin.GetDrawableComponent"/>.
/// Will also optionally apply default cross-element layout dependencies when initialised from a non-deserialised source.
/// </summary>
[Serializable]
public class SkinnableTargetWrapper : Container, ISkinnableDrawable
{
public bool IsEditable => false;
private readonly Action<Container> applyDefaults;
/// <summary>
/// Construct a wrapper with defaults that should be applied once.
/// </summary>
/// <param name="applyDefaults">A function to apply the default layout.</param>
public SkinnableTargetWrapper(Action<Container> applyDefaults)
: this()
{
this.applyDefaults = applyDefaults;
}
[JsonConstructor]
public SkinnableTargetWrapper()
{
RelativeSizeAxes = Axes.Both;
}
protected override void LoadComplete()
{
base.LoadComplete();
// schedule is required to allow children to run their LoadComplete and take on their correct sizes.
Schedule(() => applyDefaults?.Invoke(this));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A container which is serialised and can encapsulate multiple skinnable elements into a single return type (for consumption via <see cref="ISkin.GetDrawableComponent"/>.
/// Will also optionally apply default cross-element layout dependencies when initialised from a non-deserialised source.
/// </summary>
[Serializable]
public class SkinnableTargetWrapper : Container, ISkinnableDrawable
{
public bool IsEditable => false;
private readonly Action<Container> applyDefaults;
/// <summary>
/// Construct a wrapper with defaults that should be applied once.
/// </summary>
/// <param name="applyDefaults">A function to apply the default layout.</param>
public SkinnableTargetWrapper(Action<Container> applyDefaults)
: this()
{
this.applyDefaults = applyDefaults;
}
[JsonConstructor]
public SkinnableTargetWrapper()
{
RelativeSizeAxes = Axes.Both;
}
protected override void LoadComplete()
{
base.LoadComplete();
// schedule is required to allow children to run their LoadComplete and take on their correct sizes.
ScheduleAfterChildren(() => applyDefaults?.Invoke(this));
}
}
}
|
Improve performance of puzzle 5 | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=5</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle005 : Puzzle
{
/// <inheritdoc />
public override string Question => "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to the specified value?";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified maximum number is invalid.");
return -1;
}
var divisors = Enumerable.Range(1, max).ToList();
for (int i = 1; i < int.MaxValue; i++)
{
if (divisors.All((p) => i % p == 0))
{
Answer = i;
break;
}
}
return 0;
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=5</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle005 : Puzzle
{
/// <inheritdoc />
public override string Question => "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to the specified value?";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified maximum number is invalid.");
return -1;
}
var divisors = Enumerable.Range(1, max).ToList();
for (int n = max; ; n++)
{
if (divisors.All((p) => n % p == 0))
{
Answer = n;
break;
}
}
return 0;
}
}
}
|
Change version number to 0.8.7 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AngleSharp")]
[assembly: AssemblyDescription("AngleSharp is the ultimate angle brackets parser library. It parses HTML5, MathML, SVG, XML and CSS to construct a DOM based on the official W3C specification.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AngleVisions")]
[assembly: AssemblyProduct("AngleSharp")]
[assembly: AssemblyCopyright("Copyright © Florian Rappl et al. 2013-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleToAttribute("AngleSharp.Core.Tests")]
[assembly: AssemblyVersion("0.8.6.*")]
[assembly: AssemblyFileVersion("0.8.6")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AngleSharp")]
[assembly: AssemblyDescription("AngleSharp is the ultimate angle brackets parser library. It parses HTML5, MathML, SVG, XML and CSS to construct a DOM based on the official W3C specification.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AngleVisions")]
[assembly: AssemblyProduct("AngleSharp")]
[assembly: AssemblyCopyright("Copyright © Florian Rappl et al. 2013-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleToAttribute("AngleSharp.Core.Tests")]
[assembly: AssemblyVersion("0.8.7.*")]
[assembly: AssemblyFileVersion("0.8.7")] |
Remove comment, null check unnecessary. | using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
namespace Mvc.Mailer {
/// <summary>
/// This class is a utility class for instantiating LinkedResource objects
/// </summary>
public class LinkedResourceProvider : ILinkedResourceProvider {
public virtual List<LinkedResource> GetAll(Dictionary<string, string> resources) {
return resources
.Select(resource => Get(resource.Key, resource.Value))
.ToList();
}
public virtual LinkedResource Get(string contentId, string filePath) {
return new LinkedResource(filePath, GetContentType(filePath)) { ContentId = contentId };
}
public virtual ContentType GetContentType(string fileName) {
// Tyler: Possible null reference
var ext = System.IO.Path.GetExtension(fileName).ToLower();
var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null) {
return new ContentType(regKey.GetValue("Content Type").ToString());
}
return null;
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
namespace Mvc.Mailer {
/// <summary>
/// This class is a utility class for instantiating LinkedResource objects
/// </summary>
public class LinkedResourceProvider : ILinkedResourceProvider {
public virtual List<LinkedResource> GetAll(Dictionary<string, string> resources) {
return resources
.Select(resource => Get(resource.Key, resource.Value))
.ToList();
}
public virtual LinkedResource Get(string contentId, string filePath) {
return new LinkedResource(filePath, GetContentType(filePath)) { ContentId = contentId };
}
public virtual ContentType GetContentType(string fileName) {
var ext = System.IO.Path.GetExtension(fileName).ToLower();
var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null) {
return new ContentType(regKey.GetValue("Content Type").ToString());
}
return null;
}
}
} |
Replace InitOnLoad with MRTK > Utils > WMR > Check Config | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System.IO;
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality
{
/// <summary>
/// Class to perform checks for configuration checks for the Windows Mixed Reality provider.
/// </summary>
[InitializeOnLoad]
static class WindowsMixedRealityConfigurationChecker
{
private const string FileName = "Microsoft.Windows.MixedReality.DotNetWinRT.dll";
private static readonly string[] definitions = { "DOTNETWINRT_PRESENT" };
static WindowsMixedRealityConfigurationChecker()
{
ReconcileDotNetWinRTDefine();
}
/// <summary>
/// Ensures that the appropriate symbolic constant is defined based on the presence of the DotNetWinRT binary.
/// </summary>
private static void ReconcileDotNetWinRTDefine()
{
FileInfo[] files = FileUtilities.FindFilesInAssets(FileName);
if (files.Length > 0)
{
ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
else
{
ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
}
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System.IO;
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality
{
/// <summary>
/// Class to perform checks for configuration checks for the Windows Mixed Reality provider.
/// </summary>
static class WindowsMixedRealityConfigurationChecker
{
private const string FileName = "Microsoft.Windows.MixedReality.DotNetWinRT.dll";
private static readonly string[] definitions = { "DOTNETWINRT_PRESENT" };
/// <summary>
/// Ensures that the appropriate symbolic constant is defined based on the presence of the DotNetWinRT binary.
/// </summary>
[MenuItem("Mixed Reality Toolkit/Utilities/Windows Mixed Reality/Check Configuration")]
private static void ReconcileDotNetWinRTDefine()
{
FileInfo[] files = FileUtilities.FindFilesInAssets(FileName);
if (files.Length > 0)
{
ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
else
{
ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions);
}
}
}
}
|
Fix webview reload on rotation | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
if (savedInstanceState == null)
{
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState(outState);
webView.SaveState(outState);
}
protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
base.OnRestoreInstanceState(savedInstanceState);
webView.RestoreState(savedInstanceState);
}
}
} |
Call Insights.Save when reporting a crash | using System;
using System.Collections.Generic;
using Xamarin;
namespace Espera.Core.Analytics
{
internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint
{
private Guid id;
public void Dispose()
{
// Xamarin Insights can only be terminated if it has been started before, otherwise it
// throws an exception
if (Insights.IsInitialized)
{
Insights.Terminate();
}
}
public void Identify(string id, IDictionary<string, string> traits = null)
{
traits.Add(Insights.Traits.Name, id);
Insights.Identify(id, traits);
}
public void Initialize(Guid id)
{
this.id = id;
Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath);
}
public void ReportBug(string message)
{
var exception = new Exception(message);
Insights.Report(exception);
}
public void ReportFatalException(Exception exception) => Insights.Report(exception, ReportSeverity.Error);
public void ReportNonFatalException(Exception exception) => Insights.Report(exception);
public void Track(string key, IDictionary<string, string> traits = null) => Insights.Track(key, traits);
public IDisposable TrackTime(string key, IDictionary<string, string> traits = null) => Insights.TrackTime(key, traits);
public void UpdateEmail(string email) => Insights.Identify(id.ToString(), Insights.Traits.Email, email);
}
} | using System;
using System.Collections.Generic;
using Xamarin;
namespace Espera.Core.Analytics
{
internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint
{
private Guid id;
public void Dispose()
{
// Xamarin Insights can only be terminated if it has been started before, otherwise it
// throws an exception
if (Insights.IsInitialized)
{
Insights.Terminate();
}
}
public void Identify(string id, IDictionary<string, string> traits = null)
{
traits.Add(Insights.Traits.Name, id);
Insights.Identify(id, traits);
}
public void Initialize(Guid id)
{
this.id = id;
Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath);
}
public void ReportBug(string message)
{
var exception = new Exception(message);
Insights.Report(exception);
}
public void ReportFatalException(Exception exception)
{
Insights.Report(exception, ReportSeverity.Error);
Insights.Save().Wait();
}
public void ReportNonFatalException(Exception exception) => Insights.Report(exception);
public void Track(string key, IDictionary<string, string> traits = null) => Insights.Track(key, traits);
public IDisposable TrackTime(string key, IDictionary<string, string> traits = null) => Insights.TrackTime(key, traits);
public void UpdateEmail(string email) => Insights.Identify(id.ToString(), Insights.Traits.Email, email);
}
} |
Create VM in MVVM app template. | using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
app.Run(new MainWindow());
}
}
}
| using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
var window = new MainWindow
{
DataContext = new MainWindowViewModel(),
};
app.Run(window);
}
}
}
|
Exclude compiler generated types by default | namespace TestStack.ConventionTests.ConventionData
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// This is where we set what our convention is all about.
/// </summary>
public class Types : IConventionData
{
public Types(string descriptionOfTypes)
{
Description = descriptionOfTypes;
}
public Type[] TypesToVerify { get; set; }
public string Description { get; private set; }
public bool HasData {get { return TypesToVerify.Any(); }}
public static Types InAssemblyOf<T>()
{
var assembly = typeof(T).Assembly;
return new Types(assembly.GetName().Name)
{
TypesToVerify = assembly.GetTypes()
};
}
public static Types InAssemblyOf<T>(string descriptionOfTypes, Func<IEnumerable<Type>, IEnumerable<Type>> types)
{
var assembly = typeof (T).Assembly;
return new Types(descriptionOfTypes)
{
TypesToVerify = types(assembly.GetTypes()).ToArray()
};
}
}
} | namespace TestStack.ConventionTests.ConventionData
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
/// <summary>
/// This is where we set what our convention is all about.
/// </summary>
public class Types : IConventionData
{
public Types(string descriptionOfTypes)
{
Description = descriptionOfTypes;
}
public Type[] TypesToVerify { get; set; }
public string Description { get; private set; }
public bool HasData {get { return TypesToVerify.Any(); }}
public static Types InAssemblyOf<T>(bool excludeCompilerGeneratedTypes = true)
{
var assembly = typeof(T).Assembly;
var typesToVerify = assembly.GetTypes();
if (excludeCompilerGeneratedTypes)
{
typesToVerify = typesToVerify
.Where(t => !t.GetCustomAttributes(typeof (CompilerGeneratedAttribute), true).Any())
.ToArray();
}
return new Types(assembly.GetName().Name)
{
TypesToVerify = typesToVerify
};
}
public static Types InAssemblyOf<T>(string descriptionOfTypes, Func<IEnumerable<Type>, IEnumerable<Type>> types)
{
var assembly = typeof (T).Assembly;
return new Types(descriptionOfTypes)
{
TypesToVerify = types(assembly.GetTypes()).ToArray()
};
}
}
} |
Fix : Null ttl value | using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Redists.Core
{
internal class TimeSeriesWriter : ITimeSeriesWriter
{
private readonly IDatabaseAsync dbAsync;
private TimeSpan? ttl;
private IDataPointParser parser;
private ConcurrentDictionary<string, DateTime> expirations = new ConcurrentDictionary<string, DateTime>();
public TimeSeriesWriter(IDatabaseAsync dbAsync, IDataPointParser parser, TimeSpan? ttl)
{
this.dbAsync = dbAsync;
this.parser = parser;
this.ttl = ttl;
}
public Task<long> AppendAsync(string redisKey, params DataPoint[] dataPoints)
{
ManageKeyExpiration(redisKey);
var toAppend = parser.Serialize(dataPoints) + Constants.InterDelimiter;
return this.dbAsync.StringAppendAsync(redisKey, toAppend);
}
private void ManageKeyExpiration(string key)
{
DateTime lastSent=expirations.GetOrAdd(key, DateTime.MinValue);
if ((DateTime.UtcNow- lastSent)> this.ttl.Value)
{
this.dbAsync.KeyExpireAsync(key, ttl);
expirations.TryUpdate(key, DateTime.UtcNow, lastSent);
}
}
}
}
| using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Redists.Core
{
internal class TimeSeriesWriter : ITimeSeriesWriter
{
private readonly IDatabaseAsync dbAsync;
private TimeSpan? ttl;
private IDataPointParser parser;
private ConcurrentDictionary<string, DateTime> expirations = new ConcurrentDictionary<string, DateTime>();
public TimeSeriesWriter(IDatabaseAsync dbAsync, IDataPointParser parser, TimeSpan? ttl)
{
this.dbAsync = dbAsync;
this.parser = parser;
this.ttl = ttl;
}
public Task<long> AppendAsync(string redisKey, params DataPoint[] dataPoints)
{
ManageKeyExpiration(redisKey);
var toAppend = parser.Serialize(dataPoints) + Constants.InterDelimiter;
return this.dbAsync.StringAppendAsync(redisKey, toAppend);
}
private void ManageKeyExpiration(string key)
{
if (!this.ttl.HasValue)
return;
DateTime lastSent=expirations.GetOrAdd(key, DateTime.MinValue);
if ((DateTime.UtcNow- lastSent)> this.ttl.Value)
{
this.dbAsync.KeyExpireAsync(key, ttl);
expirations.TryUpdate(key, DateTime.UtcNow, lastSent);
}
}
}
}
|
Revert "Removing the assembly version attribute since appveyor doesn't seem to respect custom version format" | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Utils.Net")]
[assembly: AssemblyDescription("Collection of utilities for .NET projects")]
[assembly: AssemblyProduct("Utils.Net")]
[assembly: AssemblyCopyright("Copyright © Utils.NET 2015")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91da47c7-b676-42c6-935f-b42282c46c27")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: InternalsVisibleTo("UtilsTest")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Utils.Net")]
[assembly: AssemblyDescription("Collection of utilities for .NET projects")]
[assembly: AssemblyProduct("Utils.Net")]
[assembly: AssemblyCopyright("Copyright © Utils.NET 2015")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91da47c7-b676-42c6-935f-b42282c46c27")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
[assembly: InternalsVisibleTo("UtilsTest")]
|
Make sure AcrValues is not null | /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
namespace Thinktecture.IdentityServer.Core.Models
{
public class SignInMessage : Message
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public string IdP { get; set; }
public string Tenant { get; set; }
public string DisplayMode { get; set; }
public string UiLocales { get; set; }
public IEnumerable<string> AcrValues { get; set; }
}
} | /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
namespace Thinktecture.IdentityServer.Core.Models
{
public class SignInMessage : Message
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public string IdP { get; set; }
public string Tenant { get; set; }
public string DisplayMode { get; set; }
public string UiLocales { get; set; }
public IEnumerable<string> AcrValues { get; set; }
public SignInMessage()
{
AcrValues = Enumerable.Empty<string>();
}
}
} |
Update file ver to 3.0.3.0 | using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.2.0";
}
}
| using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.3.0";
}
}
|
Change how we find a local port. Connecting to a local port and releasing it is flaky and slow. use network info to find what port is available | using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security;
namespace HttpMock.Integration.Tests
{
internal static class PortHelper
{
internal static int FindLocalAvailablePortForTesting ()
{
for (var i = 1025; i <= 65000; i++)
{
if (!ConnectToPort(i))
return i;
}
throw new HostProtectionException("localhost seems to have ALL ports open, are you mad?");
}
private static bool ConnectToPort(int i)
{
var allIpAddresses = (from adapter in NetworkInterface.GetAllNetworkInterfaces()
from unicastAddress in adapter.GetIPProperties().UnicastAddresses
select unicastAddress.Address)
.ToList();
bool connected = false;
foreach (var ipAddress in allIpAddresses)
{
using (var tcpClient = new TcpClient())
{
try
{
tcpClient.Connect(ipAddress, i);
connected = tcpClient.Connected;
}
catch (SocketException)
{
}
finally
{
try
{
tcpClient.Close();
}
catch
{
}
}
}
if (connected)
return true;
}
return false;
}
}
}
| using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security;
namespace HttpMock.Integration.Tests
{
internal static class PortHelper
{
internal static int FindLocalAvailablePortForTesting ()
{
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
var activeTcpConnections = properties.GetActiveTcpConnections();
var minPort = activeTcpConnections.Select(a => a.LocalEndPoint.Port).Max();
var random = new Random();
var randomPort = random.Next(minPort, 65000);
while (activeTcpConnections.Any(a => a.LocalEndPoint.Port == randomPort))
{
randomPort = random.Next(minPort, 65000);
}
return randomPort;
}
}
}
|
Change sniper rifle projectile explosion sound. | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - sniperrifle.sfx.cs
// Sounds for the sniper rifle
//------------------------------------------------------------------------------
datablock AudioProfile(SniperRifleFireSound)
{
filename = "share/sounds/rotc/fire6.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperExplosionSound)
{
filename = "share/sounds/rotc/fire2.wav";
description = AudioFar3D;
preload = true;
};
datablock AudioProfile(SniperDebrisSound)
{
filename = "share/sounds/rotc/debris1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperPowerUpSound)
{
filename = "share/sounds/rotc/charge2.wav";
description = AudioClose3D;
preload = true;
};
datablock AudioProfile(SniperProjectileImpactSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioClose3D;
preload = true;
};
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - sniperrifle.sfx.cs
// Sounds for the sniper rifle
//------------------------------------------------------------------------------
datablock AudioProfile(SniperRifleFireSound)
{
filename = "share/sounds/rotc/fire6.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperExplosionSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioFar3D;
preload = true;
};
datablock AudioProfile(SniperDebrisSound)
{
filename = "share/sounds/rotc/debris1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperPowerUpSound)
{
filename = "share/sounds/rotc/charge2.wav";
description = AudioClose3D;
preload = true;
};
datablock AudioProfile(SniperProjectileImpactSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioClose3D;
preload = true;
};
|
Add compile-time constant to switch to no-op pool | // Copyright 2015 Renaud Paquay All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace mtsuite.shared.Collections {
/// <summary>
/// Default pool factory, create most generally useful <see cref="IPool{T}"/>
/// instances.
/// </summary>
public static class PoolFactory<T> where T : class {
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler);
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler, int size) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler, size);
}
}
} | // Copyright 2015 Renaud Paquay All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace mtsuite.shared.Collections {
/// <summary>
/// Default pool factory, create most generally useful <see cref="IPool{T}"/>
/// instances.
/// </summary>
public static class PoolFactory<T> where T : class {
#if USE_NOOP_POOL
public static IPool<T> Create(Func<T> creator) {
return Create(creator, _ => { });
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentNoOpPool<T>(creator);
}
#else
public static IPool<T> Create(Func<T> creator) {
return Create(creator, _ => { });
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler);
}
#endif
}
} |
Set M:M relationsheep beetween Users and Roles | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DiplomContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DiplomContext() : base()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserRole>()
.HasKey(t => new { t.UserId, t.RoleId });
modelBuilder.Entity<UserRole>()
.HasOne(pt => pt.User)
.WithMany(p => p.Roles)
.HasForeignKey(pt => pt.RoleId);
modelBuilder.Entity<UserRole>()
.HasOne(pt => pt.Role)
.WithMany(t => t.Users)
.HasForeignKey(pt => pt.UserId);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
} |
Fix look at speaker to follow Performative/Head | using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
public float blankGazeDistance;
public Transform trackedTransform;
public float lerp;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
Vector3 target;
if (speaker != null && speaker != transform.parent.parent.gameObject)
{
target = speaker.transform.Find("HeadController").position;
}
else
{
target = transform.position + transform.forward * blankGazeDistance;
}
SlowlyRotateTowards(target);
} else {
transform.position = Vector3.Lerp(transform.position, trackedTransform.position, lerp * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, trackedTransform.rotation, lerp * Time.deltaTime);
}
}
void SlowlyRotateTowards(Vector3 target)
{
Vector3 direction = (target - transform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * speed);
}
}
| using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
public float blankGazeDistance;
public Transform trackedTransform;
public float lerp;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
Vector3 target;
if (speaker != null && speaker != transform.parent.parent.gameObject)
{
target = speaker.transform.Find("Performative/Head").position;
}
else
{
target = transform.position + transform.forward * blankGazeDistance;
}
SlowlyRotateTowards(target);
} else {
transform.position = Vector3.Lerp(transform.position, trackedTransform.position, lerp * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, trackedTransform.rotation, lerp * Time.deltaTime);
}
}
void SlowlyRotateTowards(Vector3 target)
{
Vector3 direction = (target - transform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * speed);
}
}
|
Fix Linux hanging bug due to USB drive enumeration | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDesk.DBus;
namespace Palaso.UsbDrive.Linux
{
public class UDisks
{
private readonly IUDisks _udisks;
public UDisks()
{
_udisks = Bus.System.GetObject<IUDisks>("org.freedesktop.UDisks", new ObjectPath("/org/freedesktop/UDisks"));
}
public IUDisks Interface
{
get { return _udisks; }
}
public IEnumerable<string> EnumerateDeviceOnInterface(string onInterface)
{
var devices = Interface.EnumerateDevices();
foreach (var device in devices)
{
var uDiskDevice = new UDiskDevice(device);
string iface = uDiskDevice.GetProperty("DriveConnectionInterface");
string partition = uDiskDevice.GetProperty("DeviceIsPartition");
if (iface == onInterface && uDiskDevice.IsMounted)
{
yield return device;
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDesk.DBus;
namespace Palaso.UsbDrive.Linux
{
public class UDisks
{
private readonly IUDisks _udisks;
public UDisks()
{
_udisks = Bus.System.GetObject<IUDisks>("org.freedesktop.UDisks", new ObjectPath("/org/freedesktop/UDisks"));
}
public IUDisks Interface
{
get { return _udisks; }
}
public IEnumerable<string> EnumerateDeviceOnInterface(string onInterface)
{
var devices = Interface.EnumerateDevices();
foreach (var device in devices)
{
var uDiskDevice = new UDiskDevice(device);
string iface = uDiskDevice.GetProperty("DriveConnectionInterface");
string partition = uDiskDevice.GetProperty("DeviceIsPartition");
if (iface == onInterface && uDiskDevice.IsMounted)
{
yield return device;
}
}
// If Bus.System is not closed, the program hangs when it ends, waiting for
// the associated thread to quit. It appears to properly reopen Bus.System
// if we try to use it again after closing it.
// And calling Close() here appears to work okay in conjunction with the
// yield return above.
Bus.System.Close();
}
}
}
|
Use SelectMany in demo application | using System.Threading.Tasks;
using ToDoList.Automation.Api.ApiActions;
using Tranquire;
namespace ToDoList.Automation.Api
{
public static class Remove
{
public static IAction<Task> ToDoItem(string title) => Get.TheToDoItem(title)
.SelectMany<Task<Model.ToDoItem>, Task>(itemTask =>
{
return Actions.Create(
$"Remove to-do item",
async actor =>
{
var item = await itemTask;
return actor.Execute(new RemoveToDoItem(item.Id));
});
});
}
}
| using System.Threading.Tasks;
using ToDoList.Automation.Api.ApiActions;
using Tranquire;
namespace ToDoList.Automation.Api
{
public static class Remove
{
public static IAction<Task> ToDoItem(string title) => Get.TheToDoItem(title)
.SelectMany(item => new RemoveToDoItem(item.Id));
}
}
|
Mark this as required since it's nullable now | using System.ComponentModel.DataAnnotations;
namespace Tgstation.Server.Api.Models
{
/// <summary>
/// Parameters for creating a <see cref="TestMerge"/>
/// </summary>
public class TestMergeParameters
{
/// <summary>
/// The number of the pull request
/// </summary>
public int? Number { get; set; }
/// <summary>
/// The sha of the pull request revision to merge. If not specified, the latest commit shall be used (semi-unsafe)
/// </summary>
[Required]
public string PullRequestRevision { get; set; }
/// <summary>
/// Optional comment about the test
/// </summary>
public string Comment { get; set; }
}
} | using System.ComponentModel.DataAnnotations;
namespace Tgstation.Server.Api.Models
{
/// <summary>
/// Parameters for creating a <see cref="TestMerge"/>
/// </summary>
public class TestMergeParameters
{
/// <summary>
/// The number of the pull request
/// </summary>
[Required]
public int? Number { get; set; }
/// <summary>
/// The sha of the pull request revision to merge. If not specified, the latest commit shall be used (semi-unsafe)
/// </summary>
[Required]
public string PullRequestRevision { get; set; }
/// <summary>
/// Optional comment about the test
/// </summary>
public string Comment { get; set; }
}
} |
Add Tests for all public Api Methods | using BittrexSharp;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Tests.IntegrationTests
{
[TestClass]
public class BittrexTests
{
[TestMethod]
public void GetMarketSummaries_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummaries(); };
action.ShouldNotThrow();
}
}
}
| using BittrexSharp;
using BittrexSharp.Domain;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Tests.IntegrationTests
{
[TestClass]
public class BittrexTests
{
#region Public Api
private const string DefaultMarketName = "BTC-ETH";
[TestMethod]
public void GetMarkets_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarkets(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetSupportedCurrencies_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetSupportedCurrencies(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetTicker_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetTicker(DefaultMarketName); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketSummaries_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummaries(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketSummary_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummary(DefaultMarketName); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetOrderBook_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetOrderBook(DefaultMarketName, OrderType.Both, 1); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketHistory_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketHistory(DefaultMarketName); };
action.ShouldNotThrow();
}
#endregion
}
}
|
Update test to ensure page is accessible after alert | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using Toolkit.Utils;
namespace Toolkit
{
[TestClass]
public class AlertHandlerTest
{
FirefoxDriver _driver;
[TestMethod]
public void isAlertPresent()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.isAlertPresent(_driver, 3));
}
[TestMethod]
public void handleAlertTest()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.handleAlert(_driver,3));
}
[TestMethod]
public void handleAllAlertTest()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.handleAllAlerts(_driver, 2));
}
[TestCleanup]
public void TearDown()
{
_driver.Quit();
}
}
} | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using Toolkit.Utils;
namespace Toolkit
{
[TestClass]
public class AlertHandlerTest
{
FirefoxDriver _driver;
[TestInitialize]
public void startup()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
}
[TestMethod]
public void isAlertPresent()
{
Assert.IsTrue(AlertHandler.isAlertPresent(_driver, 3));
}
[TestMethod]
public void handleAlertTest()
{
Assert.IsTrue(AlertHandler.handleAlert(_driver,3));
}
[TestMethod]
public void handleAllAlertTest()
{
Assert.IsTrue(AlertHandler.handleAllAlerts(_driver, 2));
Assert.IsTrue(_driver.FindElement(By.Id("button")).Enabled);
}
[TestCleanup]
public void TearDown()
{
_driver.Quit();
}
}
} |
Update typeforward assemblyqualifiedname for TimeZoneInfoException | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class InvalidTimeZoneException : Exception
{
public InvalidTimeZoneException()
{
}
public InvalidTimeZoneException(String message)
: base(message)
{
}
public InvalidTimeZoneException(String message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class InvalidTimeZoneException : Exception
{
public InvalidTimeZoneException()
{
}
public InvalidTimeZoneException(String message)
: base(message)
{
}
public InvalidTimeZoneException(String message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
|
Fix issue that Builder for CatalogRunner is chosen when a builder for DtsRunner should be | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NBi.Core.Etl.IntegrationService
{
class SsisEtlRunnerFactory
{
public IEtlRunner Get(IEtl etl)
{
if (string.IsNullOrEmpty(etl.Server))
return new EtlFileRunner(etl);
else if (!string.IsNullOrEmpty(etl.Catalog) || !string.IsNullOrEmpty(etl.Folder) || !string.IsNullOrEmpty(etl.Project))
return new EtlCatalogRunner(etl);
else if (string.IsNullOrEmpty(etl.UserName))
return new EtlDtsWindowsRunner(etl);
else
return new EtlDtsSqlServerRunner(etl);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NBi.Core.Etl.IntegrationService
{
class SsisEtlRunnerFactory
{
public IEtlRunner Get(IEtl etl)
{
if (string.IsNullOrEmpty(etl.Server))
return new EtlFileRunner(etl);
else if (!string.IsNullOrEmpty(etl.Catalog) && !string.IsNullOrEmpty(etl.Folder) && !string.IsNullOrEmpty(etl.Project))
return new EtlCatalogRunner(etl);
else if (string.IsNullOrEmpty(etl.UserName))
return new EtlDtsWindowsRunner(etl);
else
return new EtlDtsSqlServerRunner(etl);
}
}
}
|
Update docs on XR SDK IHolographicFramePtr | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr
{
get
{
// NOTE: Currently unable to access HolographicFrame in XR SDK.
return IntPtr.Zero;
}
}
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <summary>
/// Currently unable to access HolographicFrame in XR SDK. Always returns IntPtr.Zero.
/// </summary>
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr => IntPtr.Zero;
}
}
|
Refactor route url for poiController | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using GeoChallenger.Services.Interfaces;
using GeoChallenger.Web.Api.Models;
namespace GeoChallenger.Web.Api.Controllers
{
/// <summary>
/// Geo tags controller
/// </summary>
[RoutePrefix("api/tags")]
public class PoisController : ApiController
{
private readonly IPoisService _poisService;
private readonly IMapper _mapper;
public PoisController(IPoisService poisService, IMapper mapper)
{
if (poisService == null) {
throw new ArgumentNullException(nameof(poisService));
}
_poisService = poisService;
if (mapper == null) {
throw new ArgumentNullException(nameof(mapper));
}
_mapper = mapper;
}
/// <summary>
/// Get all stub pois
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("")]
public async Task<IList<PoiReadViewModel>> Get()
{
return _mapper.Map<IList<PoiReadViewModel>>(await _poisService.GetPoisAsync());
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using GeoChallenger.Services.Interfaces;
using GeoChallenger.Web.Api.Models;
namespace GeoChallenger.Web.Api.Controllers
{
/// <summary>
/// Point of Interests controller
/// </summary>
[RoutePrefix("api/pois")]
public class PoisController : ApiController
{
private readonly IPoisService _poisService;
private readonly IMapper _mapper;
public PoisController(IPoisService poisService, IMapper mapper)
{
if (poisService == null) {
throw new ArgumentNullException(nameof(poisService));
}
_poisService = poisService;
if (mapper == null) {
throw new ArgumentNullException(nameof(mapper));
}
_mapper = mapper;
}
/// <summary>
/// Get all stub pois
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("")]
public async Task<IList<PoiReadViewModel>> Get()
{
return _mapper.Map<IList<PoiReadViewModel>>(await _poisService.GetPoisAsync());
}
}
}
|
Raise an exception if there is an error from linode |
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MCloud.Linode {
internal class LinodeResponse {
public LinodeResponse ()
{
}
public string Action {
get;
set;
}
public JObject [] Data {
get;
set;
}
public LinodeError [] Errors {
get;
set;
}
public static LinodeResponse FromJson (string json)
{
JObject obj = JObject.Parse (json);
LinodeResponse response = new LinodeResponse ();
response.Action = (string) obj ["ACTION"];
List<LinodeError> errors = new List<LinodeError> ();
foreach (JObject error in obj ["ERRORARRAY"]) {
errors.Add (new LinodeError ((string) error ["ERRORMESSAGE"], (int) error ["ERRORCODE"]));
}
response.Errors = errors.ToArray ();
List<JObject> datas = new List<JObject> ();
JArray data = obj ["DATA"] as JArray;
if (data != null) {
foreach (JObject dobj in data) {
datas.Add (dobj);
}
} else
datas.Add ((JObject) obj ["DATA"]);
response.Data = datas.ToArray ();
return response;
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MCloud.Linode {
internal class LinodeResponse {
public LinodeResponse ()
{
}
public string Action {
get;
set;
}
public JObject [] Data {
get;
set;
}
public LinodeError [] Errors {
get;
set;
}
public static LinodeResponse FromJson (string json)
{
JObject obj = JObject.Parse (json);
LinodeResponse response = new LinodeResponse ();
response.Action = (string) obj ["ACTION"];
List<LinodeError> errors = new List<LinodeError> ();
foreach (JObject error in obj ["ERRORARRAY"]) {
errors.Add (new LinodeError ((string) error ["ERRORMESSAGE"], (int) error ["ERRORCODE"]));
}
response.Errors = errors.ToArray ();
if (errors.Count > 0)
throw new Exception (errors [0].Message);
List<JObject> datas = new List<JObject> ();
JArray data = obj ["DATA"] as JArray;
if (data != null) {
foreach (JObject dobj in data) {
datas.Add (dobj);
}
} else
datas.Add ((JObject) obj ["DATA"]);
response.Data = datas.ToArray ();
return response;
}
}
}
|
Bump version to 8.2. For Sitecore 8.1. | using System.Reflection;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Synthesis")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("8.1.1.0")]
[assembly: AssemblyFileVersion("8.1.1.0")]
[assembly: AssemblyInformationalVersion("8.1.1")]
[assembly: CLSCompliant(false)] | using System.Reflection;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Synthesis")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("8.2.0.0")]
[assembly: AssemblyFileVersion("8.2.0.0")]
[assembly: AssemblyInformationalVersion("8.2.0")]
[assembly: CLSCompliant(false)] |
Set active to null (true) by default | namespace Linterhub.Cli.Strategy
{
using System.IO;
using System.Linq;
using Runtime;
using Engine;
using Engine.Exceptions;
using Linterhub.Engine.Extensions;
public class ActivateStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
var projectConfigFile = Path.Combine(context.Project, ".linterhub.json");
ExtConfig extConfig;
if (!File.Exists(projectConfigFile))
{
extConfig = new ExtConfig();
}
else
{
using (var fs = File.Open(projectConfigFile, FileMode.Open))
{
extConfig = fs.DeserializeAsJson<ExtConfig>();
}
}
var linter = extConfig.Linters.FirstOrDefault(x => x.Name == context.Linter);
if (linter != null)
{
linter.Active = context.Activate;
}
else
{
extConfig.Linters.Add(new ExtConfig.ExtLint
{
Name = context.Linter,
Active = context.Activate,
Command = engine.Factory.GetArguments(context.Linter)
});
}
var content = extConfig.SerializeAsJson();
File.WriteAllText(projectConfigFile, content);
return content;
}
}
} | namespace Linterhub.Cli.Strategy
{
using System.IO;
using System.Linq;
using Runtime;
using Engine;
using Engine.Exceptions;
using Linterhub.Engine.Extensions;
public class ActivateStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
var projectConfigFile = Path.Combine(context.Project, ".linterhub.json");
ExtConfig extConfig;
if (!File.Exists(projectConfigFile))
{
extConfig = new ExtConfig();
}
else
{
using (var fs = File.Open(projectConfigFile, FileMode.Open))
{
extConfig = fs.DeserializeAsJson<ExtConfig>();
}
}
var linter = extConfig.Linters.FirstOrDefault(x => x.Name == context.Linter);
if (linter != null)
{
linter.Active = context.Activate ? null : false;
}
else
{
extConfig.Linters.Add(new ExtConfig.ExtLint
{
Name = context.Linter,
Active = context.Activate,
Command = engine.Factory.GetArguments(context.Linter)
});
}
var content = extConfig.SerializeAsJson();
File.WriteAllText(projectConfigFile, content);
return content;
}
}
} |
Add support for `product` on the Plan Update API | using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripePlanUpdateOptions : StripeBaseOptions, ISupportMetadata
{
[JsonProperty("active")]
public bool? Active { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("nickname")]
public string Nickname { get; set; }
}
}
| using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripePlanUpdateOptions : StripeBaseOptions, ISupportMetadata
{
[JsonProperty("active")]
public bool? Active { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("nickname")]
public string Nickname { get; set; }
[JsonProperty("product")]
public string ProductId { get; set; }
}
}
|
Kill subprocess if it doesn't exit after the app is closed | using System;
using CefSharp.BrowserSubprocess;
namespace TweetDuck.Browser{
static class Program{
internal const string Version = "1.4.1.0";
private static int Main(string[] args){
SubProcess.EnableHighDPISupport();
const string typePrefix = "--type=";
string type = Array.Find(args, arg => arg.StartsWith(typePrefix, StringComparison.OrdinalIgnoreCase)).Substring(typePrefix.Length);
if (type == "renderer"){
using(SubProcess subProcess = new SubProcess(args)){
return subProcess.Run();
}
}
else{
return SubProcess.ExecuteProcess();
}
}
}
}
| using System;
using System.Diagnostics;
using System.Threading.Tasks;
using CefSharp.BrowserSubprocess;
namespace TweetDuck.Browser{
static class Program{
internal const string Version = "1.4.1.0";
private static int Main(string[] args){
SubProcess.EnableHighDPISupport();
string FindArg(string key){
return Array.Find(args, arg => arg.StartsWith(key, StringComparison.OrdinalIgnoreCase)).Substring(key.Length);
}
const string typePrefix = "--type=";
const string parentIdPrefix = "--host-process-id=";
if (!int.TryParse(FindArg(parentIdPrefix), out int parentId)){
return 0;
}
Task.Factory.StartNew(() => KillWhenHung(parentId), TaskCreationOptions.LongRunning);
if (FindArg(typePrefix) == "renderer"){
using(SubProcess subProcess = new SubProcess(args)){
return subProcess.Run();
}
}
else{
return SubProcess.ExecuteProcess();
}
}
private static async void KillWhenHung(int parentId){
try{
using(Process process = Process.GetProcessById(parentId)){
process.WaitForExit();
}
}catch{
// ded
}
await Task.Delay(10000);
Environment.Exit(0);
}
}
}
|
Fix comment about the patch path. | using RimWorld;
using Verse;
namespace PrepareLanding.Defs
{
/// <summary>
/// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
/// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml").
/// </summary>
public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
{
public override void Activate()
{
// default behavior (go to the world map)
base.Activate();
// do not show the main window if in tutorial mode
if (TutorSystem.TutorialMode)
{
Log.Message(
"[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
return;
}
// don't add a new window if the window is already there; if it's not create a new one.
if (PrepareLanding.Instance.MainWindow == null)
PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData);
// show the main window, minimized.
PrepareLanding.Instance.MainWindow.Show(true);
}
}
}
| using RimWorld;
using Verse;
namespace PrepareLanding.Defs
{
/// <summary>
/// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
/// (see "\PrepareLanding\Patches\MainButtonDef_Patch.xml").
/// </summary>
public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
{
public override void Activate()
{
// default behavior (go to the world map)
base.Activate();
// do not show the main window if in tutorial mode
if (TutorSystem.TutorialMode)
{
Log.Message(
"[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
return;
}
// don't add a new window if the window is already there; if it's not create a new one.
if (PrepareLanding.Instance.MainWindow == null)
PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData);
// show the main window, minimized.
PrepareLanding.Instance.MainWindow.Show(true);
}
}
}
|
Add category service constructor validation | using System.Linq;
using ZobShop.Data.Contracts;
using ZobShop.Factories;
using ZobShop.Models;
using ZobShop.Services.Contracts;
namespace ZobShop.Services
{
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> repository;
private readonly IUnitOfWork unitOfWork;
private readonly ICategoryFactory factory;
public CategoryService(IRepository<Category> repository, IUnitOfWork unitOfWork, ICategoryFactory factory)
{
this.repository = repository;
this.unitOfWork = unitOfWork;
this.factory = factory;
}
public Category GetCategoryByName(string name)
{
var category = this.repository
.GetAll((Category c) => c.Name == name)
.FirstOrDefault();
return category;
}
public Category CreateCategory(string name)
{
var category = this.factory.CreateCategory(name);
this.repository.Add(category);
this.unitOfWork.Commit();
return category;
}
}
}
| using System;
using System.Linq;
using ZobShop.Data.Contracts;
using ZobShop.Factories;
using ZobShop.Models;
using ZobShop.Services.Contracts;
namespace ZobShop.Services
{
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> repository;
private readonly IUnitOfWork unitOfWork;
private readonly ICategoryFactory factory;
public CategoryService(IRepository<Category> repository, IUnitOfWork unitOfWork, ICategoryFactory factory)
{
if (repository == null)
{
throw new ArgumentNullException("repository cannot be null");
}
if (factory == null)
{
throw new ArgumentNullException("factory cannot be null");
}
if (unitOfWork == null)
{
throw new ArgumentNullException("unit of work cannot be null");
}
this.repository = repository;
this.unitOfWork = unitOfWork;
this.factory = factory;
}
public Category GetCategoryByName(string name)
{
var category = this.repository
.GetAll((Category c) => c.Name == name)
.FirstOrDefault();
return category;
}
public Category CreateCategory(string name)
{
var category = this.factory.CreateCategory(name);
this.repository.Add(category);
this.unitOfWork.Commit();
return category;
}
}
}
|
Fix typo in succeed command output | using InEngine.Core;
namespace InEngine.Commands
{
/// <summary>
/// Dummy command for testing and sample code.
/// </summary>
public class AlwaysSucceed : AbstractCommand
{
public override void Run()
{
Info("Ths command always succeeds.");
}
}
}
| using InEngine.Core;
namespace InEngine.Commands
{
/// <summary>
/// Dummy command for testing and sample code.
/// </summary>
public class AlwaysSucceed : AbstractCommand
{
public override void Run()
{
Info("This command always succeeds.");
}
}
}
|
Fix integration test due to breaking change in latest Octokit.net release | var octokit = Require<OctokitPack>();
var client = octokit.Create("ScriptCs.Octokit");
var userTask = client.User.Get("alfhenrik");
var user = userTask.Result;
Console.WriteLine(user.Name);
var repoTask = client.Repository.GetAllBranches("alfhenrik", "octokit.net");
var branches = repoTask.Result;
Console.WriteLine(branches.Count);
foreach(var branch in branches)
{
Console.WriteLine(branch.Name);
} | var octokit = Require<OctokitPack>();
var client = octokit.Create("ScriptCs.Octokit");
var userTask = client.User.Get("alfhenrik");
var user = userTask.Result;
Console.WriteLine(user.Name);
var repoTask = client.Repository.Branch.GetAll("alfhenrik", "octokit.net");
var branches = repoTask.Result;
Console.WriteLine(branches.Count);
foreach(var branch in branches)
{
Console.WriteLine(branch.Name);
} |
Add Target Language, Compiler Interface | using System;
namespace Mocca {
public class MoccaCompiler {
public MoccaCompiler() {
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Mocca.DataType;
namespace Mocca {
public enum TargetLanguage {
Python, // Now available
Java, // NOT available
Javascript, // NOT available
C_sharp, // NOT available
Swift // NOT Available
}
public interface Compiler {
string compile(List<MoccaBlockGroup> source);
}
public class MoccaCompiler {
List<MoccaBlockGroup> source;
TargetLanguage lang;
public MoccaCompiler(List<MoccaBlockGroup> source, TargetLanguage lang) {
this.source = source;
this.lang = lang;
}
}
}
|
Hide already deleted variants if not set | using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.DataModel;
namespace JoinRpg.Domain
{
public static class FieldExtensions
{
public static bool HasValueList(this ProjectField field)
{
return field.FieldType == ProjectFieldType.Dropdown || field.FieldType == ProjectFieldType.MultiSelect;
}
public static bool HasSpecialGroup(this ProjectField field)
{
return field.HasValueList() && field.FieldBoundTo == FieldBoundTo.Character;
}
public static IReadOnlyList<ProjectFieldDropdownValue> GetDropdownValues(this FieldWithValue field)
{
var value = field.GetSelectedIds();
return field.GetPossibleValues().Where(
v => value.Contains(v.ProjectFieldDropdownValueId)).ToList().AsReadOnly();
}
private static IEnumerable<int> GetSelectedIds(this FieldWithValue field)
{
return string.IsNullOrWhiteSpace(field.Value) ? Enumerable.Empty<int>() : field.Value.Split(',').Select(Int32.Parse);
}
public static IEnumerable<ProjectFieldDropdownValue> GetPossibleValues(this FieldWithValue field)
=> field.Field.GetOrderedValues();
public static string GetSpecialGroupName(this ProjectFieldDropdownValue fieldValue)
{
return $"{fieldValue.Label}";
}
public static string GetSpecialGroupName(this ProjectField field)
{
return $"{field.FieldName}";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.DataModel;
namespace JoinRpg.Domain
{
public static class FieldExtensions
{
public static bool HasValueList(this ProjectField field)
{
return field.FieldType == ProjectFieldType.Dropdown || field.FieldType == ProjectFieldType.MultiSelect;
}
public static bool HasSpecialGroup(this ProjectField field)
{
return field.HasValueList() && field.FieldBoundTo == FieldBoundTo.Character;
}
public static IReadOnlyList<ProjectFieldDropdownValue> GetDropdownValues(this FieldWithValue field)
{
var value = field.GetSelectedIds();
return field.GetPossibleValues().Where(
v => value.Contains(v.ProjectFieldDropdownValueId)).ToList().AsReadOnly();
}
private static IEnumerable<int> GetSelectedIds(this FieldWithValue field)
{
return string.IsNullOrWhiteSpace(field.Value) ? Enumerable.Empty<int>() : field.Value.Split(',').Select(int.Parse);
}
public static IEnumerable<ProjectFieldDropdownValue> GetPossibleValues(this FieldWithValue field)
{
var value = field.GetSelectedIds();
return field.Field.GetOrderedValues().Where(v => v.IsActive || value.Contains(v.ProjectFieldDropdownValueId));
}
public static string GetSpecialGroupName(this ProjectFieldDropdownValue fieldValue)
{
return $"{fieldValue.Label}";
}
public static string GetSpecialGroupName(this ProjectField field)
{
return $"{field.FieldName}";
}
}
}
|
Use getter only auto property for player resources. |
namespace SettlersOfCatan.Mutable
{
public class Player
{
public Resources Hand { get; private set; }
public Player()
{
Hand = new Resources();
}
public void Trade(Player other, Resources give, Resources take)
{
Hand.RequireAtLeast(give);
other.Hand.RequireAtLeast(take);
Hand.Subtract(give);
other.Hand.Add(give);
Hand.Add(take);
other.Hand.Subtract(take);
}
}
}
|
namespace SettlersOfCatan.Mutable
{
public class Player
{
public Resources Hand { get; }
public Player()
{
Hand = new Resources();
}
public void Trade(Player other, Resources give, Resources take)
{
Hand.RequireAtLeast(give);
other.Hand.RequireAtLeast(take);
Hand.Subtract(give);
other.Hand.Add(give);
Hand.Add(take);
other.Hand.Subtract(take);
}
}
}
|
Use default routes from package. | using System.Data.Services;
using System.ServiceModel.Activation;
using System.Web.Routing;
using NuGet.Server;
using NuGet.Server.DataServices;
using NuGet.Server.Publishing;
using RouteMagic;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyGet.NuGetRoutes), "Start")]
namespace MyGet
{
public static class NuGetRoutes
{
public static void Start()
{
ServiceResolver.SetServiceResolver(new DefaultServiceResolver());
MapRoutes(RouteTable.Routes);
}
private static void MapRoutes(RouteCollection routes)
{
// Route to create a new package(http://{root}/nuget)
routes.MapDelegate("CreatePackageNuGet",
"nuget",
new { httpMethod = new HttpMethodConstraint("PUT") },
context => CreatePackageService().CreatePackage(context.HttpContext));
// The default route is http://{root}/nuget/Packages
var factory = new DataServiceHostFactory();
var serviceRoute = new ServiceRoute("nuget", factory, typeof(Packages));
serviceRoute.Defaults = new RouteValueDictionary { { "serviceType", "odata" } };
serviceRoute.Constraints = new RouteValueDictionary { { "serviceType", "odata" } };
routes.Add("nuget", serviceRoute);
}
private static IPackageService CreatePackageService()
{
return ServiceResolver.Resolve<IPackageService>();
}
}
}
| using System.Data.Services;
using System.ServiceModel.Activation;
using System.Web.Routing;
using NuGet.Server;
using NuGet.Server.DataServices;
using NuGet.Server.Publishing;
using RouteMagic;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyGet.NuGetRoutes), "Start")]
namespace MyGet {
public static class NuGetRoutes {
public static void Start() {
ServiceResolver.SetServiceResolver(new DefaultServiceResolver());
MapRoutes(RouteTable.Routes);
}
private static void MapRoutes(RouteCollection routes) {
// Route to create a new package(http://{root}/nuget)
routes.MapDelegate("CreatePackageNuGet",
"nuget",
new { httpMethod = new HttpMethodConstraint("PUT") },
context => CreatePackageService().CreatePackage(context.HttpContext));
// The default route is http://{root}/nuget/Packages
var factory = new DataServiceHostFactory();
var serviceRoute = new ServiceRoute("nuget", factory, typeof(Packages));
serviceRoute.Defaults = new RouteValueDictionary { { "serviceType", "odata" } };
serviceRoute.Constraints = new RouteValueDictionary { { "serviceType", "odata" } };
routes.Add("nuget", serviceRoute);
}
private static IPackageService CreatePackageService()
{
return ServiceResolver.Resolve<IPackageService>();
}
}
}
|
Fix regression in Script serialization | using System;
namespace VGPrompter {
public class Logger {
public bool Enabled { get; set; }
public string Name { get; private set; }
Action<object> _logger;
public Logger(bool enabled = true) : this("Default", enabled: enabled) { }
public Logger(string name, Action<object> f = null, bool enabled = true) {
Enabled = enabled;
Name = name;
_logger = f ?? Console.WriteLine;
}
public void Log(object s) {
if (Enabled) _logger(s);
}
}
} | using System;
namespace VGPrompter {
[Serializable]
public class Logger {
public bool Enabled { get; set; }
public string Name { get; private set; }
Action<object> _logger;
public Logger(bool enabled = true) : this("Default", enabled: enabled) { }
public Logger(string name, Action<object> f = null, bool enabled = true) {
Enabled = enabled;
Name = name;
_logger = f ?? Console.WriteLine;
}
public void Log(object s) {
if (Enabled) _logger(s);
}
}
} |
Fix error in hash key selector would return -1 | using System;
using System.Collections.Concurrent;
using System.Linq;
using KafkaNet.Model;
using KafkaNet.Protocol;
namespace KafkaNet
{
public class DefaultPartitionSelector : IPartitionSelector
{
private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>();
public Partition Select(Topic topic, string key)
{
if (topic == null) throw new ArgumentNullException("topic");
if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic));
//use round robing
var partitions = topic.Partitions;
if (key == null)
{
return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) =>
{
var index = partitions.FindIndex(0, p => p.Equals(i));
if (index == -1) return partitions.First();
if (++index >= partitions.Count) return partitions.First();
return partitions[index];
});
}
//use key hash
var partitionId = key.GetHashCode() % partitions.Count;
var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId);
if (partition == null)
throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}",
partitionId, string.Join(",", partitions.Select(x => x.PartitionId))));
return partition;
}
}
} | using System;
using System.Collections.Concurrent;
using System.Linq;
using KafkaNet.Model;
using KafkaNet.Protocol;
namespace KafkaNet
{
public class DefaultPartitionSelector : IPartitionSelector
{
private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>();
public Partition Select(Topic topic, string key)
{
if (topic == null) throw new ArgumentNullException("topic");
if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic));
//use round robing
var partitions = topic.Partitions;
if (key == null)
{
return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) =>
{
var index = partitions.FindIndex(0, p => p.Equals(i));
if (index == -1) return partitions.First();
if (++index >= partitions.Count) return partitions.First();
return partitions[index];
});
}
//use key hash
var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count;
var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId);
if (partition == null)
throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}",
partitionId, string.Join(",", partitions.Select(x => x.PartitionId))));
return partition;
}
}
} |
Include manager leave request functions and update to version 1.1.0.15-rc2 | using KeyPay.DomainModels.V2.Business;
using KeyPay.DomainModels.V2.Manager;
using System.Collections.Generic;
namespace KeyPay.ApiFunctions.V2
{
public class ManagerFunction : BaseFunction
{
public ManagerFunction(ApiRequestExecutor api) : base(api)
{
LeaveRequests = new ManagerLeaveRequestsFunction(api);
Kiosk = new ManagerKioskFunction(api);
TimeAndAttendance = new ManagerTimeAndAttendanceFunction(api);
}
public ManagerLeaveRequestsFunction LeaveRequests { get; set; }
public List<ManagerLeaveEmployeeModel> Employees(int businessId)
{
return ApiRequest<List<ManagerLeaveEmployeeModel>>($"/business/{businessId}/manager/employees");
}
public List<LocationModel> Locations(int businessId)
{
return ApiRequest<List<LocationModel>>($"/business/{businessId}/manager/locations");
}
public ManagerKioskFunction Kiosk { get; set; }
public ManagerTimeAndAttendanceFunction TimeAndAttendance { get; set; }
}
} | using KeyPay.DomainModels.V2.Business;
using KeyPay.DomainModels.V2.Manager;
using System.Collections.Generic;
namespace KeyPay.ApiFunctions.V2
{
public class ManagerFunction : BaseFunction
{
public ManagerFunction(ApiRequestExecutor api) : base(api)
{
LeaveRequests = new ManagerLeaveRequestsFunction(api);
Kiosk = new ManagerKioskFunction(api);
TimeAndAttendance = new ManagerTimeAndAttendanceFunction(api);
}
public ManagerLeaveRequestsFunction LeaveRequests { get; set; }
public ManagerKioskFunction Kiosk { get; set; }
public ManagerTimeAndAttendanceFunction TimeAndAttendance { get; set; }
public List<ManagerLeaveEmployeeModel> Employees(int businessId)
{
return ApiRequest<List<ManagerLeaveEmployeeModel>>($"/business/{businessId}/manager/employees");
}
public List<LocationModel> Locations(int businessId)
{
return ApiRequest<List<LocationModel>>($"/business/{businessId}/manager/locations");
}
}
} |
Update prefabs resources.load flow, fix dual load. | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrefabsPool : GameObjectBehavior {
public Dictionary<string, GameObject> prefabs;
// Only one ObjectPoolManager can exist. We use a singleton pattern to enforce this.
private static PrefabsPool _instance = null;
public static PrefabsPool instance {
get {
if (!_instance) {
_instance = FindObjectOfType(typeof(PrefabsPool)) as PrefabsPool;
if (!_instance) {
var obj = new GameObject("_PrefabsPool");
_instance = obj.AddComponent<PrefabsPool>();
}
}
return _instance;
}
}
private void OnApplicationQuit() {
_instance = null;
}
public static void CheckPrefabs() {
if(instance == null) {
return;
}
if(instance.prefabs == null) {
instance.prefabs = new Dictionary<string, GameObject>();
}
}
public static GameObject PoolPrefab(string path) {
if(instance == null) {
return null;
}
CheckPrefabs();
string key = CryptoUtil.CalculateSHA1ASCII(path);
if(!instance.prefabs.ContainsKey(key)) {
GameObject prefab = Resources.Load(path) as GameObject;
if(prefab != null) {
instance.prefabs.Add(key, Resources.Load(path) as GameObject);
}
}
if(instance.prefabs.ContainsKey(key)) {
return instance.prefabs[key];
}
return null;
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrefabsPool : GameObjectBehavior {
public Dictionary<string, GameObject> prefabs;
// Only one ObjectPoolManager can exist. We use a singleton pattern to enforce this.
private static PrefabsPool _instance = null;
public static PrefabsPool instance {
get {
if (!_instance) {
_instance = FindObjectOfType(typeof(PrefabsPool)) as PrefabsPool;
if (!_instance) {
var obj = new GameObject("_PrefabsPool");
_instance = obj.AddComponent<PrefabsPool>();
}
}
return _instance;
}
}
private void OnApplicationQuit() {
_instance = null;
}
public static void CheckPrefabs() {
if(instance == null) {
return;
}
if(instance.prefabs == null) {
instance.prefabs = new Dictionary<string, GameObject>();
}
}
public static GameObject PoolPrefab(string path) {
if(instance == null) {
return null;
}
CheckPrefabs();
string key = CryptoUtil.CalculateSHA1ASCII(path);
if(!instance.prefabs.ContainsKey(key)) {
GameObject prefab = Resources.Load(path) as GameObject;
if(prefab != null) {
instance.prefabs.Add(key, prefab);
}
}
if(instance.prefabs.ContainsKey(key)) {
return instance.prefabs[key];
}
return null;
}
}
|
Change default behaviour to listen on all IP addresses | using System;
using System.Net;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
namespace BmpListener
{
internal class Program
{
private static void Main()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new IPAddressConverter());
settings.Converters.Add(new TestConverter());
return settings;
};
var ip = IPAddress.Parse("192.168.1.126");
var bmpListener = new BmpListener(ip);
bmpListener.Start(WriteJson).Wait();
}
private static void WriteJson(BmpMessage msg)
{
var json = JsonConvert.SerializeObject(msg);
Console.WriteLine(json);
}
}
} | using System;
using System.Net;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
namespace BmpListener
{
internal class Program
{
private static void Main()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new IPAddressConverter());
settings.Converters.Add(new TestConverter());
return settings;
};
var bmpListener = new BmpListener();
bmpListener.Start(WriteJson).Wait();
}
private static void WriteJson(BmpMessage msg)
{
var json = JsonConvert.SerializeObject(msg);
Console.WriteLine(json);
}
}
} |
Fix "Random Skin" text not showing up correctly | // 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 Realms;
#nullable enable
namespace osu.Game.Database
{
/// <summary>
/// Provides a method of working with unmanaged realm objects.
/// Usually used for testing purposes where the instance is never required to be managed.
/// </summary>
/// <typeparam name="T">The underlying object type.</typeparam>
public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey
{
/// <summary>
/// Construct a new instance of live realm data.
/// </summary>
/// <param name="data">The realm data.</param>
public RealmLiveUnmanaged(T data)
{
Value = data;
}
public bool Equals(ILive<T>? other) => ID == other?.ID;
public Guid ID => Value.ID;
public void PerformRead(Action<T> perform) => perform(Value);
public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value);
public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value");
public bool IsManaged => false;
/// <summary>
/// The original live data used to create this instance.
/// </summary>
public T Value { get; }
}
}
| // 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 Realms;
#nullable enable
namespace osu.Game.Database
{
/// <summary>
/// Provides a method of working with unmanaged realm objects.
/// Usually used for testing purposes where the instance is never required to be managed.
/// </summary>
/// <typeparam name="T">The underlying object type.</typeparam>
public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey
{
/// <summary>
/// Construct a new instance of live realm data.
/// </summary>
/// <param name="data">The realm data.</param>
public RealmLiveUnmanaged(T data)
{
Value = data;
}
public bool Equals(ILive<T>? other) => ID == other?.ID;
public override string ToString() => Value.ToString();
public Guid ID => Value.ID;
public void PerformRead(Action<T> perform) => perform(Value);
public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value);
public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value");
public bool IsManaged => false;
/// <summary>
/// The original live data used to create this instance.
/// </summary>
public T Value { get; }
}
}
|
Change CTRL to Ctrl in commands description. | using System;
namespace GitIStage
{
internal sealed class ConsoleCommand
{
private readonly Action _handler;
private readonly ConsoleKey _key;
public readonly string Description;
private readonly ConsoleModifiers _modifiers;
public ConsoleCommand(Action handler, ConsoleKey key, string description)
{
_handler = handler;
_key = key;
Description = description;
_modifiers = 0;
}
public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description)
{
_handler = handler;
_key = key;
_modifiers = modifiers;
Description = description;
}
public void Execute()
{
_handler();
}
public bool MatchesKey(ConsoleKeyInfo keyInfo)
{
return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers;
}
public string GetCommandShortcut()
{
string key = _key.ToString().Replace("Arrow", "");
if (_modifiers != 0)
{
return $"{_modifiers.ToString().Replace("Control", "CTRL")} + {key.ToString()}";
}
else
return key.ToString();
}
}
} | using System;
namespace GitIStage
{
internal sealed class ConsoleCommand
{
private readonly Action _handler;
private readonly ConsoleKey _key;
public readonly string Description;
private readonly ConsoleModifiers _modifiers;
public ConsoleCommand(Action handler, ConsoleKey key, string description)
{
_handler = handler;
_key = key;
Description = description;
_modifiers = 0;
}
public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description)
{
_handler = handler;
_key = key;
_modifiers = modifiers;
Description = description;
}
public void Execute()
{
_handler();
}
public bool MatchesKey(ConsoleKeyInfo keyInfo)
{
return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers;
}
public string GetCommandShortcut()
{
string key = _key.ToString().Replace("Arrow", "");
if (_modifiers != 0)
{
return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}";
}
else
return key.ToString();
}
}
}
|
Change default backup service plan enum value. | namespace DD.CBU.Compute.Api.Contracts.Backup
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/backup")]
public enum ServicePlan {
/// <remarks/>
Essentials,
/// <remarks/>
Advanced,
/// <remarks/>
Enterprise,
}
} | namespace DD.CBU.Compute.Api.Contracts.Backup
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/backup")]
public enum ServicePlan {
/// <remarks/>
Essentials = 1,
/// <remarks/>
Advanced,
/// <remarks/>
Enterprise,
}
} |
Add SessionStateTests to AssemblyLoadContext collection | using Xunit;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Linux.Host;
namespace PSTests
{
public class SessionStateTests
{
[Fact]
public void TestDrives()
{
PowerShellAssemblyLoadContextInitializer.SetPowerShellAssemblyLoadContext(AppContext.BaseDirectory);
CultureInfo currentCulture = CultureInfo.CurrentCulture;
PSHost hostInterface = new DefaultHost(currentCulture,currentCulture);
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
InitialSessionState iss = InitialSessionState.CreateDefault2();
AutomationEngine engine = new AutomationEngine(hostInterface, runspaceConfiguration, iss);
ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss);
SessionStateInternal sessionState = new SessionStateInternal(executionContext);
Collection<PSDriveInfo> drives = sessionState.Drives(null);
Assert.True(drives.Count>0);
}
}
}
| using Xunit;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Linux.Host;
namespace PSTests
{
[Collection("AssemblyLoadContext")]
public class SessionStateTests
{
[Fact]
public void TestDrives()
{
CultureInfo currentCulture = CultureInfo.CurrentCulture;
PSHost hostInterface = new DefaultHost(currentCulture,currentCulture);
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
InitialSessionState iss = InitialSessionState.CreateDefault2();
AutomationEngine engine = new AutomationEngine(hostInterface, runspaceConfiguration, iss);
ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss);
SessionStateInternal sessionState = new SessionStateInternal(executionContext);
Collection<PSDriveInfo> drives = sessionState.Drives(null);
Assert.True(drives.Count>0);
}
}
}
|
Send Ack emails even if the system is in Simulation Mode. | using System.Text;
using log4net;
using Mail2Bug.Email.EWS;
namespace Mail2Bug.Email
{
class AckEmailHandler
{
private readonly Config.InstanceConfig _config;
public AckEmailHandler(Config.InstanceConfig config)
{
_config = config;
}
/// <summary>
/// Send mail announcing receipt of new ticket
/// </summary>
public void SendAckEmail(IIncomingEmailMessage originalMessage, string workItemId)
{
// Don't send ack emails if it's disabled in configuration or if we're in simulation mode
if (!_config.EmailSettings.SendAckEmails || _config.TfsServerConfig.SimulationMode)
{
Logger.DebugFormat("Ack emails disabled in configuration - skipping");
return;
}
var ewsMessage = originalMessage as EWSIncomingMessage;
if (ewsMessage != null)
{
HandleEWSMessage(ewsMessage, workItemId);
}
}
private void HandleEWSMessage(EWSIncomingMessage originalMessage, string workItemId)
{
originalMessage.Reply(GetReplyContents(workItemId), _config.EmailSettings.AckEmailsRecipientsAll);
}
private string GetReplyContents(string workItemId)
{
var bodyBuilder = new StringBuilder();
bodyBuilder.Append(_config.EmailSettings.GetReplyTemplate());
bodyBuilder.Replace("[BUGID]", workItemId);
bodyBuilder.Replace("[TFSCollectionUri]", _config.TfsServerConfig.CollectionUri);
return bodyBuilder.ToString();
}
private static readonly ILog Logger = LogManager.GetLogger(typeof(AckEmailHandler));
}
}
| using System.Text;
using log4net;
using Mail2Bug.Email.EWS;
namespace Mail2Bug.Email
{
class AckEmailHandler
{
private readonly Config.InstanceConfig _config;
public AckEmailHandler(Config.InstanceConfig config)
{
_config = config;
}
/// <summary>
/// Send mail announcing receipt of new ticket
/// </summary>
public void SendAckEmail(IIncomingEmailMessage originalMessage, string workItemId)
{
// Don't send ack emails if it's disabled in configuration
if (!_config.EmailSettings.SendAckEmails)
{
Logger.DebugFormat("Ack emails disabled in configuration - skipping");
return;
}
var ewsMessage = originalMessage as EWSIncomingMessage;
if (ewsMessage != null)
{
HandleEWSMessage(ewsMessage, workItemId);
}
}
private void HandleEWSMessage(EWSIncomingMessage originalMessage, string workItemId)
{
originalMessage.Reply(GetReplyContents(workItemId), _config.EmailSettings.AckEmailsRecipientsAll);
}
private string GetReplyContents(string workItemId)
{
var bodyBuilder = new StringBuilder();
bodyBuilder.Append(_config.EmailSettings.GetReplyTemplate());
bodyBuilder.Replace("[BUGID]", workItemId);
bodyBuilder.Replace("[TFSCollectionUri]", _config.TfsServerConfig.CollectionUri);
return bodyBuilder.ToString();
}
private static readonly ILog Logger = LogManager.GetLogger(typeof(AckEmailHandler));
}
}
|
Add support for invites without attached users | using System;
using Model = Discord.API.InviteMetadata;
namespace Discord.Rest
{
public class RestInviteMetadata : RestInvite, IInviteMetadata
{
private long _createdAtTicks;
public bool IsRevoked { get; private set; }
public bool IsTemporary { get; private set; }
public int? MaxAge { get; private set; }
public int? MaxUses { get; private set; }
public int Uses { get; private set; }
public RestUser Inviter { get; private set; }
public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks);
internal RestInviteMetadata(BaseDiscordClient discord, IGuild guild, IChannel channel, string id)
: base(discord, guild, channel, id)
{
}
internal static RestInviteMetadata Create(BaseDiscordClient discord, IGuild guild, IChannel channel, Model model)
{
var entity = new RestInviteMetadata(discord, guild, channel, model.Code);
entity.Update(model);
return entity;
}
internal void Update(Model model)
{
base.Update(model);
Inviter = RestUser.Create(Discord, model.Inviter);
IsRevoked = model.Revoked;
IsTemporary = model.Temporary;
MaxAge = model.MaxAge != 0 ? model.MaxAge : (int?)null;
MaxUses = model.MaxUses;
Uses = model.Uses;
_createdAtTicks = model.CreatedAt.UtcTicks;
}
IUser IInviteMetadata.Inviter => Inviter;
}
}
| using System;
using Model = Discord.API.InviteMetadata;
namespace Discord.Rest
{
public class RestInviteMetadata : RestInvite, IInviteMetadata
{
private long _createdAtTicks;
public bool IsRevoked { get; private set; }
public bool IsTemporary { get; private set; }
public int? MaxAge { get; private set; }
public int? MaxUses { get; private set; }
public int Uses { get; private set; }
public RestUser Inviter { get; private set; }
public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks);
internal RestInviteMetadata(BaseDiscordClient discord, IGuild guild, IChannel channel, string id)
: base(discord, guild, channel, id)
{
}
internal static RestInviteMetadata Create(BaseDiscordClient discord, IGuild guild, IChannel channel, Model model)
{
var entity = new RestInviteMetadata(discord, guild, channel, model.Code);
entity.Update(model);
return entity;
}
internal void Update(Model model)
{
base.Update(model);
Inviter = model.Inviter != null ? RestUser.Create(Discord, model.Inviter) : null;
IsRevoked = model.Revoked;
IsTemporary = model.Temporary;
MaxAge = model.MaxAge != 0 ? model.MaxAge : (int?)null;
MaxUses = model.MaxUses;
Uses = model.Uses;
_createdAtTicks = model.CreatedAt.UtcTicks;
}
IUser IInviteMetadata.Inviter => Inviter;
}
}
|
Update exception handling for physical file manifest reader | using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Webpack.AspNetCore.Internal;
namespace Webpack.AspNetCore.Static
{
internal class PhysicalFileManifestReader : IManifestReader
{
private readonly WebpackContext context;
public PhysicalFileManifestReader(WebpackContext context)
{
this.context = context ?? throw new System.ArgumentNullException(nameof(context));
}
public async ValueTask<IDictionary<string, string>> ReadAsync()
{
var manifestFileInfo = context.GetManifestFileInfo();
if (!manifestFileInfo.Exists)
{
return null;
}
try
{
using (var manifestStream = manifestFileInfo.CreateReadStream())
{
using (var manifestReader = new StreamReader(manifestStream))
{
var manifestJson = await manifestReader.ReadToEndAsync();
try
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(
manifestJson
);
}
catch (JsonException)
{
return null;
}
}
}
}
catch (FileNotFoundException)
{
return null;
}
}
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Webpack.AspNetCore.Internal;
namespace Webpack.AspNetCore.Static
{
internal class PhysicalFileManifestReader : IManifestReader
{
private readonly WebpackContext context;
public PhysicalFileManifestReader(WebpackContext context)
{
this.context = context ?? throw new System.ArgumentNullException(nameof(context));
}
/// <summary>
/// Reads manifest from the physical file, specified in
/// <see cref="WebpackContext" /> as a deserialized dictionary
/// </summary>
/// <returns>
/// Manifest dictionary if succeeded to read and parse json manifest file,
/// otherwise false
/// </returns>
public async ValueTask<IDictionary<string, string>> ReadAsync()
{
var manifestFileInfo = context.GetManifestFileInfo();
if (!manifestFileInfo.Exists)
{
return null;
}
try
{
// even though we've checked if the manifest
// file exists by the time we get here the file
// could become deleted or partially updated
using (var manifestStream = manifestFileInfo.CreateReadStream())
using (var manifestReader = new StreamReader(manifestStream))
{
var manifestJson = await manifestReader.ReadToEndAsync();
return JsonConvert.DeserializeObject<Dictionary<string, string>>(
manifestJson
);
}
}
catch (Exception ex) when (shouldHandle(ex))
{
return null;
}
bool shouldHandle(Exception ex) => ex is IOException || ex is JsonException;
}
}
}
|
Add debug log for latency on server | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class TableNetworking : NetworkBehaviour
{
[SyncVar]
public string variant;
[SyncVar]
public string table;
[SyncVar]
public bool selected;
[ServerCallback]
void Start ()
{
selected = false;
table = "";
variant = "";
}
public string GetTable()
{
return table;
}
public string GetVariant()
{
return variant;
}
public bool ServerHasSelected()
{
return selected;
}
public void SetTableInfo(string serverVariant, string serverTable)
{
selected = true;
variant = serverVariant;
table = serverTable;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class TableNetworking : NetworkBehaviour
{
[SyncVar]
public string variant;
[SyncVar]
public string table;
[SyncVar]
public bool selected;
public float logPingFrequency = 5.0f;
[ServerCallback]
void Start ()
{
selected = false;
table = "";
variant = "";
InvokeRepeating("LogPing", 0.0f, logPingFrequency);
}
void OnClientConnect(NetworkConnection conn)
{
InvokeRepeating("LogPing", 0.0f, logPingFrequency);
}
void LogPing()
{
foreach (NetworkClient conn in NetworkClient.allClients)
{
Debug.Log("Ping for connection " + conn.connection.address.ToString() + ": " + conn.GetRTT().ToString() + " (ms)");
}
}
public string GetTable()
{
return table;
}
public string GetVariant()
{
return variant;
}
public bool ServerHasSelected()
{
return selected;
}
public void SetTableInfo(string serverVariant, string serverTable)
{
selected = true;
variant = serverVariant;
table = serverTable;
}
}
|
Remove conditional Oracle connection builder compilation | #if NETFRAMEWORK
using System;
using Oracle.ManagedDataAccess.Client;
public static class OracleConnectionBuilder
{
public static OracleConnection Build()
{
return Build(false);
}
public static OracleConnection Build(bool disableMetadataPooling)
{
var connection = Environment.GetEnvironmentVariable("OracleConnectionString");
if (string.IsNullOrWhiteSpace(connection))
{
throw new Exception("OracleConnectionString environment variable is empty");
}
if (disableMetadataPooling)
{
var builder = new OracleConnectionStringBuilder(connection)
{
MetadataPooling = false
};
connection = builder.ConnectionString;
}
return new OracleConnection(connection);
}
}
#endif | using System;
using Oracle.ManagedDataAccess.Client;
public static class OracleConnectionBuilder
{
public static OracleConnection Build()
{
return Build(false);
}
public static OracleConnection Build(bool disableMetadataPooling)
{
var connection = Environment.GetEnvironmentVariable("OracleConnectionString");
if (string.IsNullOrWhiteSpace(connection))
{
throw new Exception("OracleConnectionString environment variable is empty");
}
if (disableMetadataPooling)
{
var builder = new OracleConnectionStringBuilder(connection)
{
MetadataPooling = false
};
connection = builder.ConnectionString;
}
return new OracleConnection(connection);
}
}
|
Remove ifdef for net45 in sample |
#if NET45
using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.DependencyInjection;
using Microsoft.AspNet.DependencyInjection.Fallback;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Routing;
namespace MvcSample.Web
{
public class Startup
{
public void Configuration(IBuilder builder)
{
var services = new ServiceCollection();
services.Add(MvcServices.GetDefaultServices());
services.AddSingleton<PassThroughAttribute, PassThroughAttribute>();
var serviceProvider = services.BuildServiceProvider(builder.ServiceProvider);
var routes = new RouteCollection()
{
DefaultHandler = new MvcApplication(serviceProvider),
};
// TODO: Add support for route constraints, so we can potentially constrain by existing routes
routes.MapRoute("{area}/{controller}/{action}");
routes.MapRoute(
"{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute(
"{controller}",
new { controller = "Home" });
builder.UseRouter(routes);
}
}
}
#endif
| using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.DependencyInjection;
using Microsoft.AspNet.DependencyInjection.Fallback;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Routing;
namespace MvcSample.Web
{
public class Startup
{
public void Configuration(IBuilder builder)
{
var services = new ServiceCollection();
services.Add(MvcServices.GetDefaultServices());
services.AddSingleton<PassThroughAttribute, PassThroughAttribute>();
var serviceProvider = services.BuildServiceProvider(builder.ServiceProvider);
var routes = new RouteCollection()
{
DefaultHandler = new MvcApplication(serviceProvider),
};
// TODO: Add support for route constraints, so we can potentially constrain by existing routes
routes.MapRoute("{area}/{controller}/{action}");
routes.MapRoute(
"{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute(
"{controller}",
new { controller = "Home" });
builder.UseRouter(routes);
}
}
}
|
Add basic test for pushups and run | using BatteryCommander.Web.Models.Data;
using System;
using Xunit;
namespace BatteryCommander.Tests
{
public class ACFTTests
{
[Theory]
[InlineData(15, 54, 84)]
public void Calculate_Run_Score(int minutes, int seconds, int expected)
{
Assert.Equal(expected, ACFTScoreTables.TwoMileRun(new TimeSpan(0, minutes, seconds)));
}
}
}
| using BatteryCommander.Web.Models.Data;
using System;
using Xunit;
namespace BatteryCommander.Tests
{
public class ACFTTests
{
[Theory]
[InlineData(15, 54, 84)]
[InlineData(13, 29, 100)]
[InlineData(23, 01, 0)]
[InlineData(19, 05, 64)]
[InlineData(17, 42, 72)]
public void Calculate_Run_Score(int minutes, int seconds, int expected)
{
Assert.Equal(expected, ACFTScoreTables.TwoMileRun(new TimeSpan(0, minutes, seconds)));
}
[Theory]
[InlineData(61, 100)]
[InlineData(30, 70)]
public void Calculate_Pushups(int reps, int expected)
{
Assert.Equal(expected, ACFTScoreTables.HandReleasePushUps(reps));
}
}
}
|
Make sure BodyText can take a large string. | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Mapping;
using UCDArch.Core.DomainModel;
namespace Commencement.Core.Domain
{
public class Template : DomainObject
{
public Template(string bodyText, TemplateType templateType, Ceremony ceremony)
{
BodyText = bodyText;
TemplateType = templateType;
Ceremony = ceremony;
SetDefaults();
}
public Template()
{
SetDefaults();
}
private void SetDefaults()
{
IsActive = true;
}
[Required]
public virtual string BodyText { get; set; }
[Required]
public virtual TemplateType TemplateType { get; set; }
[Required]
public virtual Ceremony Ceremony { get; set; }
public virtual bool IsActive { get; set; }
[StringLength(100)]
public virtual string Subject { get; set; }
}
public class TemplateMap : ClassMap<Template>
{
public TemplateMap()
{
Id(x => x.Id);
Map(x => x.BodyText);
Map(x => x.IsActive);
Map(x => x.Subject);
References(x => x.TemplateType);
References(x => x.Ceremony);
}
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Mapping;
using UCDArch.Core.DomainModel;
namespace Commencement.Core.Domain
{
public class Template : DomainObject
{
public Template(string bodyText, TemplateType templateType, Ceremony ceremony)
{
BodyText = bodyText;
TemplateType = templateType;
Ceremony = ceremony;
SetDefaults();
}
public Template()
{
SetDefaults();
}
private void SetDefaults()
{
IsActive = true;
}
[Required]
public virtual string BodyText { get; set; }
[Required]
public virtual TemplateType TemplateType { get; set; }
[Required]
public virtual Ceremony Ceremony { get; set; }
public virtual bool IsActive { get; set; }
[StringLength(100)]
public virtual string Subject { get; set; }
}
public class TemplateMap : ClassMap<Template>
{
public TemplateMap()
{
Id(x => x.Id);
Map(x => x.BodyText).Length(int.MaxValue);
Map(x => x.IsActive);
Map(x => x.Subject);
References(x => x.TemplateType);
References(x => x.Ceremony);
}
}
}
|
Update tests to match new equality not including online ID checks | // 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 NUnit.Framework;
using osu.Game.Beatmaps;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class BeatmapSetInfoEqualityTest
{
[Test]
public void TestOnlineWithOnline()
{
var ourInfo = new BeatmapSetInfo { OnlineID = 123 };
var otherInfo = new BeatmapSetInfo { OnlineID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithDatabased()
{
var ourInfo = new BeatmapSetInfo { ID = 123 };
var otherInfo = new BeatmapSetInfo { ID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithOnline()
{
var ourInfo = new BeatmapSetInfo { ID = 123, OnlineID = 12 };
var otherInfo = new BeatmapSetInfo { OnlineID = 12 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestCheckNullID()
{
var ourInfo = new BeatmapSetInfo { Hash = "1" };
var otherInfo = new BeatmapSetInfo { Hash = "2" };
Assert.AreNotEqual(ourInfo, otherInfo);
}
}
}
| // 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 NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class BeatmapSetInfoEqualityTest
{
[Test]
public void TestOnlineWithOnline()
{
var ourInfo = new BeatmapSetInfo { OnlineID = 123 };
var otherInfo = new BeatmapSetInfo { OnlineID = 123 };
Assert.AreNotEqual(ourInfo, otherInfo);
Assert.IsTrue(ourInfo.MatchesOnlineID(otherInfo));
}
[Test]
public void TestDatabasedWithDatabased()
{
var ourInfo = new BeatmapSetInfo { ID = 123 };
var otherInfo = new BeatmapSetInfo { ID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithOnline()
{
var ourInfo = new BeatmapSetInfo { ID = 123, OnlineID = 12 };
var otherInfo = new BeatmapSetInfo { OnlineID = 12 };
Assert.AreNotEqual(ourInfo, otherInfo);
Assert.IsTrue(ourInfo.MatchesOnlineID(otherInfo));
}
[Test]
public void TestCheckNullID()
{
var ourInfo = new BeatmapSetInfo { Hash = "1" };
var otherInfo = new BeatmapSetInfo { Hash = "2" };
Assert.AreNotEqual(ourInfo, otherInfo);
}
}
}
|
Throw exception for crazy input | using System.IO;
using System.Runtime.CompilerServices;
using Assent;
namespace ExpressionToCodeTest
{
static class ApprovalTest
{
public static void Verify(string text, [CallerFilePath] string filepath = null, [CallerMemberName] string membername = null)
{
var filename = Path.GetFileNameWithoutExtension(filepath);
var filedir = Path.GetDirectoryName(filepath);
var config = new Configuration().UsingNamer(new Assent.Namers.FixedNamer(Path.Combine(filedir, filename + "." + membername)));
"bla".Assent(text, config, membername, filepath);
//var writer = WriterFactory.CreateTextWriter(text);
//var namer = new SaneNamer { Name = filename + "." + membername, SourcePath = filedir };
//var reporter = new DiffReporter();
//Approver.Verify(new FileApprover(writer, namer, true), reporter);
}
//public class SaneNamer : IApprovalNamer
//{
// public string SourcePath { get; set; }
// public string Name { get; set; }
//}
}
}
| using System.IO;
using System.Runtime.CompilerServices;
using Assent;
namespace ExpressionToCodeTest
{
static class ApprovalTest
{
public static void Verify(string text, [CallerFilePath] string filepath = null, [CallerMemberName] string membername = null)
{
var filename = Path.GetFileNameWithoutExtension(filepath);
var filedir = Path.GetDirectoryName(filepath) ?? throw new InvalidOperationException("path " + filepath + " has no directory");
var config = new Configuration().UsingNamer(new Assent.Namers.FixedNamer(Path.Combine(filedir, filename + "." + membername)));
"bla".Assent(text, config, membername, filepath);
//var writer = WriterFactory.CreateTextWriter(text);
//var namer = new SaneNamer { Name = filename + "." + membername, SourcePath = filedir };
//var reporter = new DiffReporter();
//Approver.Verify(new FileApprover(writer, namer, true), reporter);
}
//public class SaneNamer : IApprovalNamer
//{
// public string SourcePath { get; set; }
// public string Name { get; set; }
//}
}
}
|
Fix name on test console write out | using System;
using System.Linq;
using NUnit.Framework;
namespace Faker.Tests
{
[TestFixture]
public class RandomNumberFixture
{
[TestCase(1, "Coin flip")] // 0 ... 1 Coin flip
[TestCase(6, "6 sided die")] // 0 .. 6
[TestCase(9, "Random single digit")] // 0 ... 9
[TestCase(20, "D20")] // 0 ... 20 The signature dice of the dungeons and dragons
public void Should_Yield_All_ValuesWithinRange(int maxValue, string testName)
{
var maxExclusiveLimit = maxValue + 1;
Console.WriteLine($@"RandomNumber.Next [{testName}]");
var results = Enumerable.Range(0, maxExclusiveLimit).ToDictionary(k => k, k => false);
do
{
var randValue = RandomNumber.Next(0, maxExclusiveLimit);
results[randValue] = true;
Console.WriteLine($@"RandomNumber.Next(0,maxValueExclusive)=[{randValue}]");
} while (!results.All(j => j.Value));
Assert.IsTrue(results.Select(z => z.Value).All(y => y));
}
[Test]
public void Should_Create_Zero()
{
var zero = RandomNumber.Next(0, 0);
Console.WriteLine($@"RandomNumber.Next(0,0)=[{zero}]");
Assert.IsTrue(zero == 0);
}
}
} | using System;
using System.Linq;
using NUnit.Framework;
namespace Faker.Tests
{
[TestFixture]
public class RandomNumberFixture
{
[TestCase(1, "Coin flip")] // 0 ... 1 Coin flip
[TestCase(6, "6 sided die")] // 0 .. 6
[TestCase(9, "Random single digit")] // 0 ... 9
[TestCase(20, "D20")] // 0 ... 20 The signature dice of the dungeons and dragons
public void Should_Yield_All_ValuesWithinRange(int maxValue, string testName)
{
var maxExclusiveLimit = maxValue + 1;
Console.WriteLine($@"RandomNumber.Next [{testName}]");
var results = Enumerable.Range(0, maxExclusiveLimit).ToDictionary(k => k, k => false);
do
{
var randValue = RandomNumber.Next(0, maxExclusiveLimit);
results[randValue] = true;
Console.WriteLine($@"RandomNumber.Next(0,{maxExclusiveLimit})=[{randValue}]");
} while (!results.All(j => j.Value));
Assert.IsTrue(results.Select(z => z.Value).All(y => y));
}
[Test]
public void Should_Create_Zero()
{
var zero = RandomNumber.Next(0, 0);
Console.WriteLine($@"RandomNumber.Next(0,0)=[{zero}]");
Assert.IsTrue(zero == 0);
}
}
} |
Make settings object bit cleaner | using System;
namespace Rooijakkers.MeditationTimer.Data
{
/// <summary>
/// Stores settings data in local settings storage
/// </summary>
public class Settings
{
private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage";
public TimeSpan TimeToGetReady
{
get
{
var secondsToGetReady =
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE];
if (secondsToGetReady == null)
{
secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS;
SetTimeToGetReady(Convert.ToInt32(secondsToGetReady));
}
// Return stored time in seconds as a TimeSpan.
return new TimeSpan(0, 0, Convert.ToInt32(secondsToGetReady));
}
set
{
// Store time in seconds obtained from TimeSpan.
SetTimeToGetReady(value.Seconds);
}
}
private void SetTimeToGetReady(int value)
{
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value;
}
}
}
| using System;
namespace Rooijakkers.MeditationTimer.Data
{
/// <summary>
/// Stores settings data in local settings storage
/// </summary>
public class Settings
{
private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage";
public TimeSpan TimeToGetReady
{
get
{
int? secondsToGetReady =
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] as int?;
// If settings were not yet stored set to default value.
if (secondsToGetReady == null)
{
secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS;
SetTimeToGetReady(secondsToGetReady.Value);
}
// Return stored time in seconds as a TimeSpan.
return new TimeSpan(0, 0, secondsToGetReady.Value);
}
set
{
// Store time in seconds obtained from TimeSpan.
SetTimeToGetReady(value.Seconds);
}
}
private void SetTimeToGetReady(int value)
{
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.