Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix test for 64-bit platforms | // 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.
// Passing a very large struct by value on the stack, on arm32 and x86,
// can cause it to be copied from a temp to the outgoing space without
// probing the stack.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace BigFrames
{
[StructLayout(LayoutKind.Explicit)]
public struct LargeStructWithRef
{
[FieldOffset(0)]
public int i1;
[FieldOffset(65500)]
public Object o1;
}
public class Test
{
public static int iret = 1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void TestWrite(LargeStructWithRef s)
{
Console.Write("Enter TestWrite: ");
Console.WriteLine(s.o1.GetHashCode());
iret = 100;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Test1()
{
Console.WriteLine("Enter Test1");
LargeStructWithRef s = new LargeStructWithRef();
s.o1 = new Object();
TestWrite(s);
}
public static int Main()
{
Test1();
if (iret == 100)
{
Console.WriteLine("TEST PASSED");
}
else
{
Console.WriteLine("TEST FAILED");
}
return iret;
}
}
}
| // 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.
// Passing a very large struct by value on the stack, on arm32 and x86,
// can cause it to be copied from a temp to the outgoing space without
// probing the stack.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace BigFrames
{
[StructLayout(LayoutKind.Explicit)]
public struct LargeStructWithRef
{
[FieldOffset(0)]
public int i1;
[FieldOffset(65496)] // Must be 8-byte aligned for test to work on 64-bit platforms.
public Object o1;
}
public class Test
{
public static int iret = 1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void TestWrite(LargeStructWithRef s)
{
Console.Write("Enter TestWrite: ");
Console.WriteLine(s.o1.GetHashCode());
iret = 100;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Test1()
{
Console.WriteLine("Enter Test1");
LargeStructWithRef s = new LargeStructWithRef();
s.o1 = new Object();
TestWrite(s);
}
public static int Main()
{
Test1();
if (iret == 100)
{
Console.WriteLine("TEST PASSED");
}
else
{
Console.WriteLine("TEST FAILED");
}
return iret;
}
}
}
|
Check for Fixie library reference | using System;
using JetBrains.Application;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.UnitTestFramework;
namespace ReSharperFixieRunner.UnitTestProvider
{
[FileUnitTestExplorer]
public class FixieTestFileExplorer : IUnitTestFileExplorer
{
private readonly FixieTestProvider provider;
private readonly UnitTestElementFactory unitTestElementFactory;
public FixieTestFileExplorer(FixieTestProvider provider, UnitTestElementFactory unitTestElementFactory)
{
this.provider = provider;
this.unitTestElementFactory = unitTestElementFactory;
}
public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
if (interrupted())
return;
psiFile.ProcessDescendants(new FixiePsiFileExplorer(unitTestElementFactory, consumer, psiFile, interrupted));
}
public IUnitTestProvider Provider { get { return provider; } }
}
} | using System;
using System.Linq;
using JetBrains.Application;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.UnitTestFramework;
namespace ReSharperFixieRunner.UnitTestProvider
{
[FileUnitTestExplorer]
public class FixieTestFileExplorer : IUnitTestFileExplorer
{
private readonly FixieTestProvider provider;
private readonly UnitTestElementFactory unitTestElementFactory;
public FixieTestFileExplorer(FixieTestProvider provider, UnitTestElementFactory unitTestElementFactory)
{
this.provider = provider;
this.unitTestElementFactory = unitTestElementFactory;
}
public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
if (interrupted())
return;
// don't bother going any further if there's isn't a project with a reference to the Fixie assembly
var project = psiFile.GetProject();
if (project == null)
return;
if(project.GetModuleReferences().All(module => module.Name != "Fixie"))
return;
psiFile.ProcessDescendants(new FixiePsiFileExplorer(unitTestElementFactory, consumer, psiFile, interrupted));
}
public IUnitTestProvider Provider { get { return provider; } }
}
} |
Switch to the memory repository | using Bootstrap.StructureMap;
using Manufacturing.DataCollector.Datasources.Simulation;
using StructureMap;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;
using StructureMap.Pipeline;
namespace Manufacturing.DataPusher
{
public class DataPusherContainer : IStructureMapRegistration
{
public void Register(IContainer container)
{
container.Configure(x => x.Scan(y =>
{
y.TheCallingAssembly();
y.SingleImplementationsOfInterface().OnAddedPluginTypes(z => z.LifecycleIs(new TransientLifecycle()));
y.ExcludeType<IDataPusher>();
x.AddRegistry(new DataPusherRegistry());
x.For<RandomDatasource>().LifecycleIs<SingletonLifecycle>();
}));
}
}
public class DataPusherRegistry : Registry
{
public DataPusherRegistry()
{
For<IDataPusher>().Use<EventHubsDataPusher>();
}
}
}
| using Bootstrap.StructureMap;
using Manufacturing.DataCollector;
using Manufacturing.DataCollector.Datasources.Simulation;
using StructureMap;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;
using StructureMap.Pipeline;
namespace Manufacturing.DataPusher
{
public class DataPusherContainer : IStructureMapRegistration
{
public void Register(IContainer container)
{
container.Configure(x => x.Scan(y =>
{
y.TheCallingAssembly();
y.SingleImplementationsOfInterface().OnAddedPluginTypes(z => z.LifecycleIs(new TransientLifecycle()));
y.ExcludeType<IDataPusher>();
x.AddRegistry(new DataPusherRegistry());
x.For<RandomDatasource>().LifecycleIs<SingletonLifecycle>();
x.For<ILocalRecordRepository>().Use<MemoryRecordRepository>();
}));
}
}
public class DataPusherRegistry : Registry
{
public DataPusherRegistry()
{
For<IDataPusher>().Use<EventHubsDataPusher>();
}
}
}
|
Check early for commit on current branch | using System;
using System.Collections.Generic;
using GitVersion.Common;
using LibGit2Sharp;
namespace GitVersion.VersionCalculation
{
/// <summary>
/// Version is 0.1.0.
/// BaseVersionSource is the "root" commit reachable from the current commit.
/// Does not increment.
/// </summary>
public class FallbackVersionStrategy : VersionStrategyBase
{
private readonly IRepositoryMetadataProvider repositoryMetadataProvider;
public FallbackVersionStrategy(IRepositoryMetadataProvider repositoryMetadataProvider, Lazy<GitVersionContext> versionContext) : base(versionContext)
{
this.repositoryMetadataProvider = repositoryMetadataProvider;
}
public override IEnumerable<BaseVersion> GetVersions()
{
Commit baseVersionSource;
var currentBranchTip = Context.CurrentBranch.Tip;
try
{
baseVersionSource = repositoryMetadataProvider.GetBaseVersionSource(currentBranchTip);
}
catch (NotFoundException exception)
{
throw new GitVersionException($"Can't find commit {currentBranchTip.Sha}. Please ensure that the repository is an unshallow clone with `git fetch --unshallow`.", exception);
}
yield return new BaseVersion("Fallback base version", false, new SemanticVersion(minor: 1), baseVersionSource, null);
}
}
}
| using System;
using System.Collections.Generic;
using GitVersion.Common;
using LibGit2Sharp;
namespace GitVersion.VersionCalculation
{
/// <summary>
/// Version is 0.1.0.
/// BaseVersionSource is the "root" commit reachable from the current commit.
/// Does not increment.
/// </summary>
public class FallbackVersionStrategy : VersionStrategyBase
{
private readonly IRepositoryMetadataProvider repositoryMetadataProvider;
public FallbackVersionStrategy(IRepositoryMetadataProvider repositoryMetadataProvider, Lazy<GitVersionContext> versionContext) : base(versionContext)
{
this.repositoryMetadataProvider = repositoryMetadataProvider;
}
public override IEnumerable<BaseVersion> GetVersions()
{
Commit baseVersionSource;
var currentBranchTip = Context.CurrentBranch.Tip;
if (currentBranchTip == null)
{
throw new GitVersionException("No commits found on the current branch.");
}
try
{
baseVersionSource = repositoryMetadataProvider.GetBaseVersionSource(currentBranchTip);
}
catch (NotFoundException exception)
{
throw new GitVersionException($"Can't find commit {currentBranchTip.Sha}. Please ensure that the repository is an unshallow clone with `git fetch --unshallow`.", exception);
}
yield return new BaseVersion("Fallback base version", false, new SemanticVersion(minor: 1), baseVersionSource, null);
}
}
}
|
Remove all network operation codes | using System;
using System.Collections.Generic;
using System.Text;
namespace Rs317.Extended
{
/// <summary>
/// Operation codes for the RS317 packets.
/// </summary>
public enum RsNetworkOperationCode : byte
{
/// <summary>
/// Operation code for packet type that indicates a login
/// success.
/// </summary>
ConnectionInitialized = 0,
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Rs317.Extended
{
/// <summary>
/// Operation codes for the RS317 packets.
/// </summary>
public enum RsNetworkOperationCode : byte
{
}
}
|
Make the constraint on RestfulHttpMethodConstraint, so the match will work. | using System.Web.Routing;
namespace RestfulRouting
{
public abstract class Mapper
{
private readonly IRouteHandler _routeHandler;
protected Mapper(IRouteHandler routeHandler)
{
_routeHandler = routeHandler;
}
protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
{
return new Route(path,
new RouteValueDictionary(new { controller, action }),
new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
_routeHandler);
}
}
}
| using System.Web.Routing;
namespace RestfulRouting
{
public abstract class Mapper
{
private readonly IRouteHandler _routeHandler;
protected Mapper(IRouteHandler routeHandler)
{
_routeHandler = routeHandler;
}
protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
{
return new Route(path,
new RouteValueDictionary(new { controller, action }),
new RouteValueDictionary(new { httpMethod = new RestfulHttpMethodConstraint(httpMethods) }),
_routeHandler);
}
}
}
|
Replace string queries with GUID for DummyAlembic.abc | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.Formats.Alembic.Importer;
namespace UnityEditor.Formats.Alembic.Exporter.UnitTests
{
public class AssetRenameTests
{
readonly List<string> deleteFileList = new List<string>();
const string copiedAbcFile = "Assets/abc.abc";
GameObject go;
[SetUp]
public void SetUp()
{
var srcDummyFile = AssetDatabase.FindAssets("Dummy").Select(AssetDatabase.GUIDToAssetPath).SelectMany(AssetDatabase.LoadAllAssetsAtPath).OfType<AlembicStreamPlayer>().First().StreamDescriptor.PathToAbc;
File.Copy(srcDummyFile,copiedAbcFile, true);
AssetDatabase.Refresh();
var asset = AssetDatabase.LoadMainAssetAtPath(copiedAbcFile);
go = PrefabUtility.InstantiatePrefab(asset) as GameObject;
}
[TearDown]
public void TearDown()
{
foreach (var file in deleteFileList)
{
AssetDatabase.DeleteAsset(file);
}
deleteFileList.Clear();
}
[Test]
public void TestRenameDoesNotRenameInstances()
{
Assert.AreEqual("abc",go.name);
var ret = AssetDatabase.RenameAsset(copiedAbcFile,"new.abc");
AssetDatabase.Refresh();
Assert.AreEqual("abc",go.name);
Assert.IsEmpty(ret);
deleteFileList.Add("Assets/new.abc");
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.Formats.Alembic.Importer;
namespace UnityEditor.Formats.Alembic.Exporter.UnitTests
{
public class AssetRenameTests
{
readonly List<string> deleteFileList = new List<string>();
const string copiedAbcFile = "Assets/abc.abc";
GameObject go;
[SetUp]
public void SetUp()
{
const string dummyGUID = "1a066d124049a413fb12b82470b82811"; // GUID of DummyAlembic.abc
var path = AssetDatabase.GUIDToAssetPath(dummyGUID);
var srcDummyFile = AssetDatabase.LoadAllAssetsAtPath(path).OfType<AlembicStreamPlayer>().First().StreamDescriptor.PathToAbc;
File.Copy(srcDummyFile,copiedAbcFile, true);
AssetDatabase.Refresh();
var asset = AssetDatabase.LoadMainAssetAtPath(copiedAbcFile);
go = PrefabUtility.InstantiatePrefab(asset) as GameObject;
}
[TearDown]
public void TearDown()
{
foreach (var file in deleteFileList)
{
AssetDatabase.DeleteAsset(file);
}
deleteFileList.Clear();
}
[Test]
public void TestRenameDoesNotRenameInstances()
{
Assert.AreEqual("abc",go.name);
var ret = AssetDatabase.RenameAsset(copiedAbcFile,"new.abc");
AssetDatabase.Refresh();
Assert.AreEqual("abc",go.name);
Assert.IsEmpty(ret);
deleteFileList.Add("Assets/new.abc");
}
}
}
|
Return if input is null or empty | using System;
using System.Text.RegularExpressions;
namespace InternetSeparationAdapter
{
public static class UtilsExtension
{
// http://stackoverflow.com/a/33113820
public static string Base64UrlEncode(this byte[] arg)
{
var s = Convert.ToBase64String(arg); // Regular base64 encoder
s = s.Split('=')[0]; // Remove any trailing '='s
s = s.Replace('+', '-'); // 62nd char of encoding
s = s.Replace('/', '_'); // 63rd char of encoding
return s;
}
public static byte[] Base64UrlDecode(this string arg)
{
var s = arg;
s = s.Replace('-', '+'); // 62nd char of encoding
s = s.Replace('_', '/'); // 63rd char of encoding
switch (s.Length % 4) // Pad with trailing '='s
{
case 0:
break; // No pad chars in this case
case 2:
s += "==";
break; // Two pad chars
case 3:
s += "=";
break; // One pad char
default:
throw new InvalidOperationException("This code should never be executed");
}
return Convert.FromBase64String(s); // Standard base64 decoder
}
public static string StripSuccessiveNewLines(this string input)
{
const string pattern = @"(\r\n|\n|\n\r){2,}";
var regex = new Regex(pattern);
return regex.Replace(input, "\n\n");
}
}
}
| using System;
using System.Text.RegularExpressions;
namespace InternetSeparationAdapter
{
public static class UtilsExtension
{
// http://stackoverflow.com/a/33113820
public static string Base64UrlEncode(this byte[] arg)
{
var s = Convert.ToBase64String(arg); // Regular base64 encoder
s = s.Split('=')[0]; // Remove any trailing '='s
s = s.Replace('+', '-'); // 62nd char of encoding
s = s.Replace('/', '_'); // 63rd char of encoding
return s;
}
public static byte[] Base64UrlDecode(this string arg)
{
var s = arg;
s = s.Replace('-', '+'); // 62nd char of encoding
s = s.Replace('_', '/'); // 63rd char of encoding
switch (s.Length % 4) // Pad with trailing '='s
{
case 0:
break; // No pad chars in this case
case 2:
s += "==";
break; // Two pad chars
case 3:
s += "=";
break; // One pad char
default:
throw new InvalidOperationException("This code should never be executed");
}
return Convert.FromBase64String(s); // Standard base64 decoder
}
public static string StripSuccessiveNewLines(this string input)
{
if (string.IsNullOrEmpty(input)) return input;
const string pattern = @"(\r\n|\n|\n\r){2,}";
var regex = new Regex(pattern);
return regex.Replace(input, "\n\n");
}
}
}
|
Change wrong values used to form target URL | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Online.Chat;
namespace osu.Game.Online.API.Requests
{
public class MarkChannelAsReadRequest : APIRequest
{
private readonly Channel channel;
private readonly Message message;
public MarkChannelAsReadRequest(Channel channel, Message message)
{
this.channel = channel;
this.message = message;
}
protected override string Target => $"/chat/channels/{channel}/mark-as-read/{message}";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Online.Chat;
namespace osu.Game.Online.API.Requests
{
public class MarkChannelAsReadRequest : APIRequest
{
private readonly Channel channel;
private readonly Message message;
public MarkChannelAsReadRequest(Channel channel, Message message)
{
this.channel = channel;
this.message = message;
}
protected override string Target => $"chat/channels/{channel.Id}/mark-as-read/{message.Id}";
}
}
|
Switch RequestProfiler consumers over to using provider | using Glimpse.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Glimpse.Agent.Web
{
public class MasterRequestProfiler : IRequestRuntime
{
private readonly IDiscoverableCollection<IRequestProfiler> _requestProfiliers;
private readonly IEnumerable<IIgnoredRequestPolicy> _ignoredRequestPolicies;
public MasterRequestProfiler(IDiscoverableCollection<IRequestProfiler> requestProfiliers, IIgnoredRequestProvider ignoredRequestProvider)
{
_requestProfiliers = requestProfiliers;
_requestProfiliers.Discover();
_ignoredRequestPolicies = ignoredRequestProvider.Policies;
}
public async Task Begin(IHttpContext context)
{
if (ShouldProfile(context))
{
foreach (var requestRuntime in _requestProfiliers)
{
await requestRuntime.Begin(context);
}
}
}
public async Task End(IHttpContext context)
{
if (ShouldProfile(context))
{
foreach (var requestRuntime in _requestProfiliers)
{
await requestRuntime.End(context);
}
}
}
public bool ShouldProfile(IHttpContext context)
{
if (_ignoredRequestPolicies.Any())
{
foreach (var policy in _ignoredRequestPolicies)
{
if (policy.ShouldIgnore(context))
{
return false;
}
}
}
return true;
}
}
} | using Glimpse.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Glimpse.Agent.Web
{
public class MasterRequestProfiler : IRequestRuntime
{
private readonly IEnumerable<IRequestProfiler> _requestProfiliers;
private readonly IEnumerable<IIgnoredRequestPolicy> _ignoredRequestPolicies;
public MasterRequestProfiler(IRequestProfilerProvider requestProfilerProvider, IIgnoredRequestProvider ignoredRequestProvider)
{
_requestProfiliers = requestProfilerProvider.Profilers;
_ignoredRequestPolicies = ignoredRequestProvider.Policies;
}
public async Task Begin(IHttpContext context)
{
if (ShouldProfile(context))
{
foreach (var requestRuntime in _requestProfiliers)
{
await requestRuntime.Begin(context);
}
}
}
public async Task End(IHttpContext context)
{
if (ShouldProfile(context))
{
foreach (var requestRuntime in _requestProfiliers)
{
await requestRuntime.End(context);
}
}
}
public bool ShouldProfile(IHttpContext context)
{
if (_ignoredRequestPolicies.Any())
{
foreach (var policy in _ignoredRequestPolicies)
{
if (policy.ShouldIgnore(context))
{
return false;
}
}
}
return true;
}
}
} |
Change "Weather" "Font Size" default value | using System;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Weather
{
public class Settings : WidgetSettingsBase
{
[Category("Style")]
[DisplayName("Unit Type")]
public TemperatureUnitType UnitType { get; set; }
[Category("General")]
[DisplayName("Refresh Interval")]
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromHours(1);
[Category("General")]
[DisplayName("Zip Code")]
public int ZipCode { get; set; }
[Category("Style")]
[DisplayName("Show Icon")]
public bool ShowIcon { get; set; } = true;
[Category("Style")]
[DisplayName("Show Temperature")]
public bool ShowTemperature { get; set; } = true;
[Category("Style")]
[DisplayName("Show Temperature Range")]
public bool ShowTempMinMax { get; set; } = false;
[Category("Style")]
[DisplayName("Show Description")]
public bool ShowDescription { get; set; } = true;
}
} | using System;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Weather
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Style.FontSettings.FontSize = 16;
}
[Category("Style")]
[DisplayName("Unit Type")]
public TemperatureUnitType UnitType { get; set; }
[Category("General")]
[DisplayName("Refresh Interval")]
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromHours(1);
[Category("General")]
[DisplayName("Zip Code")]
public int ZipCode { get; set; }
[Category("Style")]
[DisplayName("Show Icon")]
public bool ShowIcon { get; set; } = true;
[Category("Style")]
[DisplayName("Show Temperature")]
public bool ShowTemperature { get; set; } = true;
[Category("Style")]
[DisplayName("Show Temperature Range")]
public bool ShowTempMinMax { get; set; } = false;
[Category("Style")]
[DisplayName("Show Description")]
public bool ShowDescription { get; set; } = true;
}
} |
Add ticker and period information to partial candle tokenizer | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Finance
{
public class PartialCandleTokenizer : AbstractCandleTokenizer
{
private AbstractCandleTokenizer ct;
private int start;
private int length;
public PartialCandleTokenizer(AbstractCandleTokenizer ct, int start, int length)
{
this.ct = ct;
this.start = start;
this.length = length;
}
public override Candle this[int index]
{
get
{
return ct[index + start];
}
}
public override int GetLength()
{
return length;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Finance
{
public class PartialCandleTokenizer : AbstractCandleTokenizer
{
private AbstractCandleTokenizer ct;
private int start;
private int length;
public PartialCandleTokenizer(AbstractCandleTokenizer ct, int start, int length)
{
this.ct = ct;
this.start = start;
this.length = length;
ticker = ct.GetTicker();
period = ct.GetPeriod();
}
public override Candle this[int index]
{
get
{
return ct[index + start];
}
}
public override int GetLength()
{
return length;
}
}
}
|
Fix cookie middleware name for interop package | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Interop;
namespace Owin
{
public static class CookieInterop
{
public static ISecureDataFormat<AuthenticationTicket> CreateSharedDataFormat(DirectoryInfo keyDirectory, string authenticationType)
{
var dataProtector = DataProtectionProvider.Create(keyDirectory)
.CreateProtector("Microsoft.AspNet.Authentication.Cookies.CookieAuthenticationMiddleware", // full name of the ASP.NET 5 type
authenticationType, "v2");
return new AspNetTicketDataFormat(new DataProtectorShim(dataProtector));
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Interop;
namespace Owin
{
public static class CookieInterop
{
public static ISecureDataFormat<AuthenticationTicket> CreateSharedDataFormat(DirectoryInfo keyDirectory, string authenticationType)
{
var dataProtector = DataProtectionProvider.Create(keyDirectory)
.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", // full name of the ASP.NET 5 type
authenticationType, "v2");
return new AspNetTicketDataFormat(new DataProtectorShim(dataProtector));
}
}
} |
Fix assembly name in Client.net40 | 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("IntegrationEngine.Client.net40")]
// 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("446e2264-b09d-4fb2-91d6-cae870d1b4d6")]
| 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("IntegrationEngine.Client")]
// 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("446e2264-b09d-4fb2-91d6-cae870d1b4d6")]
|
Use intValue instead of enumValueIndex | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Audio.Editor
{
[CustomEditor(typeof(TextToSpeech))]
public class TextToSpeechInspector : UnityEditor.Editor
{
private SerializedProperty voiceProperty;
private void OnEnable()
{
voiceProperty = serializedObject.FindProperty("voice");
}
public override void OnInspectorGUI()
{
if (voiceProperty.enumValueIndex == (int)TextToSpeechVoice.Other)
{
DrawDefaultInspector();
EditorGUILayout.HelpBox("Use the links below to find more available voices (for non en-US languages):", MessageType.Info);
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Voices for HoloLens 2", EditorStyles.miniButton))
{
Application.OpenURL("https://docs.microsoft.com/hololens/hololens2-language-support");
}
if (GUILayout.Button("Voices for desktop Windows", EditorStyles.miniButton))
{
Application.OpenURL("https://support.microsoft.com/windows/appendix-a-supported-languages-and-voices-4486e345-7730-53da-fcfe-55cc64300f01#WindowsVersion=Windows_11");
}
}
}
else
{
DrawPropertiesExcluding(serializedObject, "customVoice");
}
serializedObject.ApplyModifiedProperties();
}
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Audio.Editor
{
[CustomEditor(typeof(TextToSpeech))]
public class TextToSpeechInspector : UnityEditor.Editor
{
private SerializedProperty voiceProperty;
private void OnEnable()
{
voiceProperty = serializedObject.FindProperty("voice");
}
public override void OnInspectorGUI()
{
if (voiceProperty.intValue == (int)TextToSpeechVoice.Other)
{
DrawDefaultInspector();
EditorGUILayout.HelpBox("Use the links below to find more available voices (for non en-US languages):", MessageType.Info);
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Voices for HoloLens 2", EditorStyles.miniButton))
{
Application.OpenURL("https://docs.microsoft.com/hololens/hololens2-language-support");
}
if (GUILayout.Button("Voices for desktop Windows", EditorStyles.miniButton))
{
Application.OpenURL("https://support.microsoft.com/windows/appendix-a-supported-languages-and-voices-4486e345-7730-53da-fcfe-55cc64300f01#WindowsVersion=Windows_11");
}
}
}
else
{
DrawPropertiesExcluding(serializedObject, "customVoice");
}
serializedObject.ApplyModifiedProperties();
}
}
}
|
Disable hanging OSX NetworkInformation test | // 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 Xunit;
namespace System.Net.NetworkInformation.Tests
{
public class NetworkChangeTest
{
[Fact]
public void NetworkAddressChanged_AddRemove_Success()
{
NetworkAddressChangedEventHandler handler = NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAddressChanged += handler;
NetworkChange.NetworkAddressChanged -= handler;
}
[Fact]
public void NetworkAddressChanged_JustRemove_Success()
{
NetworkAddressChangedEventHandler handler = NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAddressChanged -= handler;
}
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
}
| // 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 Xunit;
namespace System.Net.NetworkInformation.Tests
{
public class NetworkChangeTest
{
[Fact]
[ActiveIssue(8066, PlatformID.OSX)]
public void NetworkAddressChanged_AddRemove_Success()
{
NetworkAddressChangedEventHandler handler = NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAddressChanged += handler;
NetworkChange.NetworkAddressChanged -= handler;
}
[Fact]
public void NetworkAddressChanged_JustRemove_Success()
{
NetworkAddressChangedEventHandler handler = NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAddressChanged -= handler;
}
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
}
|
Add other rollbar client tests | using Newtonsoft.Json;
using Xunit;
namespace Rollbar.Test {
public class RollbarClientFixture {
private readonly RollbarClient _rollbarClient;
public RollbarClientFixture() {
this._rollbarClient= new RollbarClient();
}
[Fact]
public void Client_rendered_as_dict_when_empty() {
Assert.Equal("{}", JsonConvert.SerializeObject(_rollbarClient));
}
}
}
| using Newtonsoft.Json;
using Xunit;
namespace Rollbar.Test {
public class RollbarClientFixture {
private readonly RollbarClient _rollbarClient;
public RollbarClientFixture() {
this._rollbarClient= new RollbarClient();
}
[Fact]
public void Client_rendered_as_dict_when_empty() {
Assert.Equal("{}", JsonConvert.SerializeObject(_rollbarClient));
}
[Fact]
public void Client_renders_arbitrary_keys_correctly() {
_rollbarClient["test-key"] = "test-value";
Assert.Equal("{\"test-key\":\"test-value\"}", JsonConvert.SerializeObject(_rollbarClient));
}
[Fact]
public void Client_renders_javascript_entry_correctly() {
_rollbarClient.Javascript = new RollbarJavascriptClient();
Assert.Equal("{\"javascript\":{}}", JsonConvert.SerializeObject(_rollbarClient));
}
}
}
|
Remove length object from all JSON messages | using System;
using System.Linq;
using Newtonsoft.Json;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected BgpMessage(ref ArraySegment<byte> data)
{
var bgpHeader = new BgpHeader(data);
Type = bgpHeader.Type;
var offset = data.Offset + 19;
Length = (int) bgpHeader.Length;
data = new ArraySegment<byte>(data.Array, offset, Length - 19);
}
public int Length { get; }
[JsonIgnore]
public MessageType Type { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
var msgType = (MessageType) data.ElementAt(18);
switch (msgType)
{
case MessageType.Open:
return new BgpOpenMessage(data);
case MessageType.Update:
return new BgpUpdateMessage(data);
case MessageType.Notification:
return new BgpNotification(data);
case MessageType.Keepalive:
throw new NotImplementedException();
case MessageType.RouteRefresh:
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
}
} | using System;
using System.Linq;
using Newtonsoft.Json;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected BgpMessage(ref ArraySegment<byte> data)
{
var bgpHeader = new BgpHeader(data);
Type = bgpHeader.Type;
var offset = data.Offset + 19;
Length = (int) bgpHeader.Length;
data = new ArraySegment<byte>(data.Array, offset, Length - 19);
}
[JsonIgnore]
public int Length { get; }
[JsonIgnore]
public MessageType Type { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
var msgType = (MessageType) data.ElementAt(18);
switch (msgType)
{
case MessageType.Open:
return new BgpOpenMessage(data);
case MessageType.Update:
return new BgpUpdateMessage(data);
case MessageType.Notification:
return new BgpNotification(data);
case MessageType.Keepalive:
throw new NotImplementedException();
case MessageType.RouteRefresh:
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
}
} |
Make StateChanged action more verbose in its arguments. | // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An element which starts hidden and can be toggled to visible.
/// </summary>
public abstract class OverlayContainer : Container, IStateful<Visibility>
{
protected override void LoadComplete()
{
if (state == Visibility.Hidden)
{
PopOut();
Flush(true);
}
base.LoadComplete();
}
private Visibility state;
public Visibility State
{
get { return state; }
set
{
if (value == state) return;
state = value;
switch (value)
{
case Visibility.Hidden:
PopOut();
break;
case Visibility.Visible:
PopIn();
break;
}
StateChanged?.Invoke();
}
}
public event Action StateChanged;
protected abstract void PopIn();
protected abstract void PopOut();
public override void Hide() => State = Visibility.Hidden;
public override void Show() => State = Visibility.Visible;
public void ToggleVisibility() => State = (State == Visibility.Visible ? Visibility.Hidden : Visibility.Visible);
}
public enum Visibility
{
Hidden,
Visible
}
}
| // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An element which starts hidden and can be toggled to visible.
/// </summary>
public abstract class OverlayContainer : Container, IStateful<Visibility>
{
protected override void LoadComplete()
{
if (state == Visibility.Hidden)
{
PopOut();
Flush(true);
}
base.LoadComplete();
}
private Visibility state;
public Visibility State
{
get { return state; }
set
{
if (value == state) return;
state = value;
switch (value)
{
case Visibility.Hidden:
PopOut();
break;
case Visibility.Visible:
PopIn();
break;
}
StateChanged?.Invoke(this, state);
}
}
public event Action<OverlayContainer, Visibility> StateChanged;
protected abstract void PopIn();
protected abstract void PopOut();
public override void Hide() => State = Visibility.Hidden;
public override void Show() => State = Visibility.Visible;
public void ToggleVisibility() => State = (State == Visibility.Visible ? Visibility.Hidden : Visibility.Visible);
}
public enum Visibility
{
Hidden,
Visible
}
}
|
Test for checking Fork update | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MailTest
{
public partial class LogOut : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MailTest
{
public partial class LogOut : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Modifying file to check fork update
}
}
} |
Fix bools not being parsed correctly from config (case sensitivity). | // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Configuration
{
public class BindableBool : Bindable<bool>
{
public BindableBool(bool value = false)
: base(value)
{
}
public static implicit operator bool(BindableBool value) => value != null && value.Value;
public override string ToString() => Value.ToString();
public override bool Parse(object s)
{
string str = s as string;
if (str == null) return false;
Value = str == @"1" || str == @"true";
return true;
}
public void Toggle() => Value = !Value;
}
}
| // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Configuration
{
public class BindableBool : Bindable<bool>
{
public BindableBool(bool value = false)
: base(value)
{
}
public static implicit operator bool(BindableBool value) => value != null && value.Value;
public override string ToString() => Value.ToString();
public override bool Parse(object s)
{
string str = s as string;
if (str == null) return false;
Value = str == @"1" || str.Equals(@"true", System.StringComparison.OrdinalIgnoreCase);
return true;
}
public void Toggle() => Value = !Value;
}
}
|
Update TestCaseActiveState to cover Window.CursorInWindow state | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Platform
{
public class TestSceneActiveState : FrameworkTestScene
{
private IBindable<bool> isActive;
private Box isActiveBox;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
isActive = host.IsActive.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
Children = new Drawable[]
{
isActiveBox = new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
};
isActive.BindValueChanged(active => isActiveBox.Colour = active.NewValue ? Color4.Green : Color4.Red);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Platform
{
public class TestSceneActiveState : FrameworkTestScene
{
private IBindable<bool> isActive;
private IBindable<bool> cursorInWindow;
private Box isActiveBox;
private Box cursorInWindowBox;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
isActive = host.IsActive.GetBoundCopy();
cursorInWindow = host.Window.CursorInWindow.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
Children = new Drawable[]
{
isActiveBox = new Box
{
Colour = Color4.Black,
Width = 0.5f,
RelativeSizeAxes = Axes.Both,
},
cursorInWindowBox = new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
Width = 0.5f,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
};
isActive.BindValueChanged(active => isActiveBox.Colour = active.NewValue ? Color4.Green : Color4.Red, true);
cursorInWindow.BindValueChanged(active => cursorInWindowBox.Colour = active.NewValue ? Color4.Green : Color4.Red, true);
}
}
}
|
Add comment about Exclusive tracks. | // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Linq;
using osu.Framework.IO.Stores;
namespace osu.Framework.Audio.Track
{
public class TrackManager : AudioCollectionManager<AudioTrack>
{
IResourceStore<byte[]> store;
AudioTrack exclusiveTrack;
public TrackManager(IResourceStore<byte[]> store)
{
this.store = store;
}
public AudioTrack Get(string name)
{
AudioTrackBass track = new AudioTrackBass(store.GetStream(name));
AddItem(track);
return track;
}
public void SetExclusive(AudioTrack track)
{
if (exclusiveTrack == track) return;
Items.ForEach(i => i.Stop());
exclusiveTrack?.Dispose();
exclusiveTrack = track;
AddItem(track);
}
public override void Update()
{
base.Update();
if (exclusiveTrack?.HasCompleted != false)
findExclusiveTrack();
}
private void findExclusiveTrack()
{
exclusiveTrack = Items.FirstOrDefault();
}
}
}
| // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Linq;
using osu.Framework.IO.Stores;
namespace osu.Framework.Audio.Track
{
public class TrackManager : AudioCollectionManager<AudioTrack>
{
IResourceStore<byte[]> store;
AudioTrack exclusiveTrack;
public TrackManager(IResourceStore<byte[]> store)
{
this.store = store;
}
public AudioTrack Get(string name)
{
AudioTrackBass track = new AudioTrackBass(store.GetStream(name));
AddItem(track);
return track;
}
/// <summary>
/// Specify an AudioTrack which should get exclusive playback over everything else.
/// Will pause all other tracks and throw away any existing exclusive track.
/// </summary>
public void SetExclusive(AudioTrack track)
{
if (exclusiveTrack == track) return;
Items.ForEach(i => i.Stop());
exclusiveTrack?.Dispose();
exclusiveTrack = track;
AddItem(track);
}
public override void Update()
{
base.Update();
if (exclusiveTrack?.HasCompleted != false)
findExclusiveTrack();
}
private void findExclusiveTrack()
{
exclusiveTrack = Items.FirstOrDefault();
}
}
}
|
Make tests for delete collection methods. | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Arango.Test
{
[TestClass]
public class CollectionTests
{
[TestMethod]
public void TestMethod1()
{
}
}
}
| using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Arango.Client;
namespace Arango.Test
{
[TestClass]
public class CollectionTests
{
private ArangoDatabase _database;
public CollectionTests()
{
string alias = "test";
string[] connectionString = File.ReadAllText(@"..\..\..\..\..\ConnectionString.txt").Split(';');
ArangoNode node = new ArangoNode(
connectionString[0],
int.Parse(connectionString[1]),
connectionString[2],
connectionString[3],
alias
);
ArangoClient.Nodes.Add(node);
_database = new ArangoDatabase(alias);
}
[TestMethod]
public void CreateCollectionAndDeleteItByID()
{
ArangoCollection testCollection = new ArangoCollection();
testCollection.Name = "tempUnitTestCollection001xyz";
testCollection.Type = ArangoCollectionType.Document;
testCollection.WaitForSync = false;
testCollection.JournalSize = 1024 * 1024; // 1 MB
ArangoCollection newCollection = _database.CreateCollection(testCollection.Name, testCollection.Type, testCollection.WaitForSync, testCollection.JournalSize);
Assert.AreEqual(testCollection.Name, newCollection.Name);
Assert.AreEqual(testCollection.Type, newCollection.Type);
Assert.AreEqual(testCollection.WaitForSync, newCollection.WaitForSync);
Assert.AreEqual(testCollection.JournalSize, newCollection.JournalSize);
bool isDeleted = _database.DeleteCollection(newCollection.ID);
Assert.IsTrue(isDeleted);
}
[TestMethod]
public void CreateCollectionAndDeleteItByName()
{
ArangoCollection testCollection = new ArangoCollection();
testCollection.Name = "tempUnitTestCollection002xyz";
testCollection.Type = ArangoCollectionType.Document;
testCollection.WaitForSync = false;
testCollection.JournalSize = 1024 * 1024; // 1 MB
ArangoCollection newCollection = _database.CreateCollection(testCollection.Name, testCollection.Type, testCollection.WaitForSync, testCollection.JournalSize);
Assert.AreEqual(testCollection.Name, newCollection.Name);
Assert.AreEqual(testCollection.Type, newCollection.Type);
Assert.AreEqual(testCollection.WaitForSync, newCollection.WaitForSync);
Assert.AreEqual(testCollection.JournalSize, newCollection.JournalSize);
bool isDeleted = _database.DeleteCollection(newCollection.Name);
Assert.IsTrue(isDeleted);
}
}
}
|
Fix error when items had invariant language versions (versions compared could be incorrectly the default language instead of the invariant language) | using System;
using System.Linq;
using Sitecore.Data.Managers;
using Sitecore.Globalization;
namespace Unicorn.Data
{
public static class SourceItemExtensions
{
/// <summary>
/// Helper method to get a specific version from a source item, if it exists
/// </summary>
/// <returns>Null if the version does not exist or the version if it exists</returns>
public static ItemVersion GetVersion(this ISourceItem sourceItem, string language, int versionNumber)
{
if (language.Equals(Language.Invariant.Name)) language = LanguageManager.DefaultLanguage.Name;
return sourceItem.Versions.FirstOrDefault(x => x.Language.Equals(language, StringComparison.OrdinalIgnoreCase) && x.VersionNumber == versionNumber);
}
}
}
| using System;
using System.Linq;
namespace Unicorn.Data
{
public static class SourceItemExtensions
{
/// <summary>
/// Helper method to get a specific version from a source item, if it exists
/// </summary>
/// <returns>Null if the version does not exist or the version if it exists</returns>
public static ItemVersion GetVersion(this ISourceItem sourceItem, string language, int versionNumber)
{
return sourceItem.Versions.FirstOrDefault(x => x.Language.Equals(language, StringComparison.OrdinalIgnoreCase) && x.VersionNumber == versionNumber);
}
}
}
|
Add DetailedErrorPolicy in global configuration | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Samesound
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Samesound
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
}
|
Build SMA with version 0.0.0.0 | using System.Runtime.CompilerServices;
using System.Reflection;
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Management")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Utility")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Security")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.Host")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.UnitTests")]
[assembly:AssemblyFileVersionAttribute("3.0.0.0")]
[assembly:AssemblyVersion("3.0.0.0")]
namespace System.Management.Automation
{
internal class NTVerpVars
{
internal const int PRODUCTMAJORVERSION = 10;
internal const int PRODUCTMINORVERSION = 0;
internal const int PRODUCTBUILD = 10032;
internal const int PRODUCTBUILD_QFE = 0;
internal const int PACKAGEBUILD_QFE = 814;
}
}
| using System.Runtime.CompilerServices;
using System.Reflection;
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Management")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Utility")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Security")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.Host")]
[assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.UnitTests")]
[assembly:AssemblyFileVersionAttribute("0.0.0.0")]
[assembly:AssemblyVersion("0.0.0.0")]
namespace System.Management.Automation
{
internal class NTVerpVars
{
internal const int PRODUCTMAJORVERSION = 10;
internal const int PRODUCTMINORVERSION = 0;
internal const int PRODUCTBUILD = 10032;
internal const int PRODUCTBUILD_QFE = 0;
internal const int PACKAGEBUILD_QFE = 814;
}
}
|
Refactor to use linq expression | using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
IEnumerable<FileInfo> files = directory.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (var nestedDirectory in directory.GetDirectories())
{
if (excludedDirectories.Contains(nestedDirectory.Name))
{
continue;
}
files = files.Concat(GetFiles(nestedDirectory, excludedDirectories));
}
return files;
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
return directory.GetFiles("*", SearchOption.TopDirectoryOnly)
.Concat(directory.GetDirectories()
.Where(x => excludedDirectories.Contains(x.Name))
.SelectMany(x => GetFiles(x, excludedDirectories)));
}
}
}
|
Update Fun token image URL. | using Discord;
using Discord.Commands;
using System;
namespace CoinBot.Discord.Commands
{
public abstract class CommandBase : ModuleBase
{
protected static void AddAuthor(EmbedBuilder builder)
{
builder.WithAuthor(new EmbedAuthorBuilder
{
Name = "FunFair CoinBot - right click above to block",
Url = "https://funfair.io",
IconUrl = "https://files.coinmarketcap.com/static/img/coins/32x32/funfair.png"
});
}
protected static void AddFooter(EmbedBuilder builder, DateTime? dateTime = null)
{
if (dateTime.HasValue)
{
builder.Timestamp = dateTime;
builder.Footer = new EmbedFooterBuilder
{
Text = "Prices updated"
};
}
}
}
}
| using Discord;
using Discord.Commands;
using System;
namespace CoinBot.Discord.Commands
{
public abstract class CommandBase : ModuleBase
{
protected static void AddAuthor(EmbedBuilder builder)
{
builder.WithAuthor(new EmbedAuthorBuilder
{
Name = "FunFair CoinBot - right click above to block",
Url = "https://funfair.io",
IconUrl = "https://s2.coinmarketcap.com/static/img/coins/32x32/1757.png"
});
}
protected static void AddFooter(EmbedBuilder builder, DateTime? dateTime = null)
{
if (dateTime.HasValue)
{
builder.Timestamp = dateTime;
builder.Footer = new EmbedFooterBuilder
{
Text = "Prices updated"
};
}
}
}
}
|
Select first item by default in "Select Item" window | using System.Collections.Generic;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
namespace DesktopWidgets.WindowViewModels
{
public class SelectItemViewModel : ViewModelBase
{
private object _selectedItem;
public SelectItemViewModel(IEnumerable<object> items)
{
ItemsList = new ObservableCollection<object>(items);
}
public ObservableCollection<object> ItemsList { get; set; }
public object SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
RaisePropertyChanged();
}
}
}
}
} | using System.Collections.Generic;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
namespace DesktopWidgets.WindowViewModels
{
public class SelectItemViewModel : ViewModelBase
{
private object _selectedItem;
public SelectItemViewModel(IEnumerable<object> items)
{
ItemsList = new ObservableCollection<object>(items);
if (ItemsList.Count > 0)
{
SelectedItem = ItemsList[0];
}
}
public ObservableCollection<object> ItemsList { get; set; }
public object SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
RaisePropertyChanged();
}
}
}
}
} |
Allow XR Plug-in Management settings to be configured post-build | using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.XR.Management;
using UnityEngine;
using UnityEngine.XR.Management;
namespace SuperSystems.UnityBuild
{
public class XRPluginManagement : BuildAction, IPreBuildAction, IPreBuildPerPlatformAction
{
[Header("XR Settings")]
[Tooltip("XR plugin loaders to use for this build")] public List<XRLoader> XRPlugins = new List<XRLoader>();
[Tooltip("Whether or not to use automatic initialization of XR plugin loaders on startup")] public bool InitializeXROnStartup = true;
public override void PerBuildExecute(BuildReleaseType releaseType, BuildPlatform platform, BuildArchitecture architecture, BuildDistribution distribution, DateTime buildTime, ref BuildOptions options, string configKey, string buildPath)
{
XRGeneralSettings generalSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(platform.targetGroup);
XRManagerSettings settingsManager = generalSettings.Manager;
List<XRLoader> previousLoaders = settingsManager.loaders;
generalSettings.InitManagerOnStart = InitializeXROnStartup;
settingsManager.loaders = XRPlugins;
}
}
}
| using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.XR.Management;
using UnityEngine;
using UnityEngine.XR.Management;
namespace SuperSystems.UnityBuild
{
public class XRPluginManagement : BuildAction, IPreBuildPerPlatformAction, IPostBuildPerPlatformAction
{
[Header("XR Settings")]
[Tooltip("XR plugin loaders to use for this build")] public List<XRLoader> XRPlugins = new List<XRLoader>();
[Tooltip("Whether or not to use automatic initialization of XR plugin loaders on startup")] public bool InitializeXROnStartup = true;
public override void PerBuildExecute(BuildReleaseType releaseType, BuildPlatform platform, BuildArchitecture architecture, BuildDistribution distribution, DateTime buildTime, ref BuildOptions options, string configKey, string buildPath)
{
XRGeneralSettings generalSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(platform.targetGroup);
XRManagerSettings settingsManager = generalSettings.Manager;
generalSettings.InitManagerOnStart = InitializeXROnStartup;
settingsManager.loaders = XRPlugins;
}
}
}
|
Support responses for collectors, and commonise | using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using SurveyMonkey.Containers;
using SurveyMonkey.RequestSettings;
namespace SurveyMonkey
{
public partial class SurveyMonkeyApi
{
public List<Response> GetResponseOverviews(int id)
{
string endPoint = String.Format("https://api.surveymonkey.net/v3/surveys/{0}/responses", id);
var verb = Verb.GET;
JToken result = MakeApiRequest(endPoint, verb, new RequestData());
var responses = result["data"].ToObject<List<Response>>();
return responses;
}
public List<Response> GetResponseDetails(int id)
{
string endPoint = String.Format("https://api.surveymonkey.net/v3/surveys/{0}/responses/bulk", id);
var verb = Verb.GET;
JToken result = MakeApiRequest(endPoint, verb, new RequestData());
var responses = result["data"].ToObject<List<Response>>();
return responses;
}
}
} | using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using SurveyMonkey.Containers;
using SurveyMonkey.RequestSettings;
namespace SurveyMonkey
{
public partial class SurveyMonkeyApi
{
private enum SurveyOrCollector
{
Survey,
Collector
}
public List<Response> GetSurveyResponseOverviews(int id)
{
return GetResponsesRequest(id, false, SurveyOrCollector.Survey);
}
public List<Response> GetSurveyResponseDetails(int id)
{
return GetResponsesRequest(id, true, SurveyOrCollector.Survey);
}
public List<Response> GetCollectorResponseOverviews(int id)
{
return GetResponsesRequest(id, false, SurveyOrCollector.Collector);
}
public List<Response> GetCollectorResponseDetails(int id)
{
return GetResponsesRequest(id, true, SurveyOrCollector.Collector);
}
private List<Response> GetResponsesRequest(int id, bool details, SurveyOrCollector source)
{
var bulk = details ? "/bulk" : String.Empty;
string endPoint = String.Format("https://api.surveymonkey.net/v3/{0}s/{1}/responses{2}", source.ToString().ToLower(), id, bulk);
var verb = Verb.GET;
JToken result = MakeApiRequest(endPoint, verb, new RequestData());
var responses = result["data"].ToObject<List<Response>>();
return responses;
}
}
} |
Add connection pruning test (currently just fails) | using Medallion.Threading.Postgres;
using Microsoft.Data.SqlClient;
using Npgsql;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Medallion.Threading.Tests.Tests.Postgres
{
public class PostgresDistributedLockTest
{
[Test]
public async Task TestInt64AndInt32PairKeyNamespacesAreDifferent()
{
var connectionString = TestingPostgresDistributedLockEngine.GetConnectionString();
var key1 = new PostgresAdvisoryLockKey(0);
var key2 = new PostgresAdvisoryLockKey(0, 0);
var @lock1 = new PostgresDistributedLock(key1, connectionString);
var @lock2 = new PostgresDistributedLock(key2, connectionString);
using var handle1 = await lock1.TryAcquireAsync();
Assert.IsNotNull(handle1);
using var handle2 = await lock2.TryAcquireAsync();
Assert.IsNotNull(handle2);
}
// todo idle pruning interval?
}
}
| using Medallion.Threading.Postgres;
using Microsoft.Data.SqlClient;
using Npgsql;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Medallion.Threading.Tests.Tests.Postgres
{
public class PostgresDistributedLockTest
{
[Test]
public async Task TestInt64AndInt32PairKeyNamespacesAreDifferent()
{
var connectionString = TestingPostgresDistributedLockEngine.GetConnectionString();
var key1 = new PostgresAdvisoryLockKey(0);
var key2 = new PostgresAdvisoryLockKey(0, 0);
var @lock1 = new PostgresDistributedLock(key1, connectionString);
var @lock2 = new PostgresDistributedLock(key2, connectionString);
using var handle1 = await lock1.TryAcquireAsync();
Assert.IsNotNull(handle1);
using var handle2 = await lock2.TryAcquireAsync();
Assert.IsNotNull(handle2);
}
// todo probably just always needs keepalive
[Test]
public async Task TestIdleConnectionPruning()
{
var connectionString = new NpgsqlConnectionStringBuilder(TestingPostgresDistributedLockEngine.GetConnectionString())
{
ConnectionIdleLifetime = 1,
ConnectionPruningInterval = 1,
MaxPoolSize = 1,
Timeout = 2,
}.ConnectionString;
var @lock = new PostgresDistributedLock(new PostgresAdvisoryLockKey("IdeConPru"), connectionString);
using var handle1 = await @lock.AcquireAsync();
await Task.Delay(TimeSpan.FromSeconds(.5));
using var handle2 = await @lock.TryAcquireAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(handle2);
}
// todo idle pruning interval?
}
}
|
Write the top-level function for checking for updates | using System;
using System.IO;
namespace NSync.Client
{
public class UpdateManager
{
Func<string, Stream> openPath;
Func<string, IObservable<string>> downloadUrl;
public UpdateManager(string url,
Func<string, Stream> openPathMock = null,
Func<string, IObservable<string>> downloadUrlMock = null)
{
openPath = openPathMock;
downloadUrl = downloadUrlMock;
}
public IObservable<UpdateInfo> CheckForUpdate()
{
throw new NotImplementedException();
}
}
public class UpdateInfo
{
public string Version { get; protected set; }
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using NSync.Core;
namespace NSync.Client
{
public class UpdateManager
{
Func<string, Stream> openPath;
Func<string, IObservable<string>> downloadUrl;
string updateUrl;
public UpdateManager(string url,
Func<string, Stream> openPathMock = null,
Func<string, IObservable<string>> downloadUrlMock = null)
{
updateUrl = url;
openPath = openPathMock;
downloadUrl = downloadUrlMock;
}
public IObservable<UpdateInfo> CheckForUpdate()
{
IEnumerable<ReleaseEntry> localReleases;
using (var sr = new StreamReader(openPath(Path.Combine("packages", "RELEASES")))) {
localReleases = ReleaseEntry.ParseReleaseFile(sr.ReadToEnd());
}
var ret = downloadUrl(updateUrl)
.Select(ReleaseEntry.ParseReleaseFile)
.Select(releases => determineUpdateInfo(localReleases, releases))
.Multicast(new AsyncSubject<UpdateInfo>());
ret.Connect();
return ret;
}
UpdateInfo determineUpdateInfo(IEnumerable<ReleaseEntry> localReleases, IEnumerable<ReleaseEntry> remoteReleases)
{
if (localReleases.Count() == remoteReleases.Count()) {
return null;
}
}
}
public class UpdateInfo
{
public string Version { get; protected set; }
}
} |
Update namespace reference in unit comments | using System;
#pragma warning disable 1591
namespace E247.Fun
{
public struct Unit : IEquatable<Unit>
{
public static readonly Unit Value = new Unit();
public override int GetHashCode() =>
0;
public override bool Equals(object obj) =>
obj is Unit;
public override string ToString() =>
"()";
public bool Equals(Unit other) =>
true;
public static bool operator ==(Unit lhs, Unit rhs) =>
true;
public static bool operator !=(Unit lhs, Unit rhs) =>
false;
// with using static E247.Juke.Model.Entities.Unit, allows using unit instead of the ugly Unit.Value
// ReSharper disable once InconsistentNaming
public static Unit unit =>
Value;
// with using static E247.Juke.Model.Entities.Unit, allows using ignore(anything) to have anything return unit
// ReSharper disable once InconsistentNaming
public static Unit ignore<T>(T anything) =>
unit;
}
}
| using System;
#pragma warning disable 1591
namespace E247.Fun
{
public struct Unit : IEquatable<Unit>
{
public static readonly Unit Value = new Unit();
public override int GetHashCode() =>
0;
public override bool Equals(object obj) =>
obj is Unit;
public override string ToString() =>
"()";
public bool Equals(Unit other) =>
true;
public static bool operator ==(Unit lhs, Unit rhs) =>
true;
public static bool operator !=(Unit lhs, Unit rhs) =>
false;
// with using static E247.Fun.Unit, allows using unit instead of the ugly Unit.Value
// ReSharper disable once InconsistentNaming
public static Unit unit =>
Value;
// with using static E247.Fun.Unit, allows using ignore(anything) to have anything return unit
// ReSharper disable once InconsistentNaming
public static Unit ignore<T>(T anything) =>
unit;
}
}
|
Change AsNonNull to NotNull return | // 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.Diagnostics.CodeAnalysis;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
[return: NotNullIfNotNull("obj")]
public static T AsNonNull<T>(this T? obj) => obj!;
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
| // 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.Diagnostics.CodeAnalysis;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
[return: NotNull]
public static T AsNonNull<T>(this T? obj) => obj!;
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
|
Fix test failing after BDL -> `[Test]` change | // 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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Tournament.Screens.TeamWin;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneTeamWinScreen : TournamentTestScene
{
[Test]
public void TestBasic()
{
var match = Ladder.CurrentMatch.Value;
match.Round.Value = Ladder.Rounds.FirstOrDefault(g => g.Name.Value == "Finals");
match.Completed.Value = true;
Add(new TeamWinScreen
{
FillMode = FillMode.Fit,
FillAspectRatio = 16 / 9f
});
}
}
}
| // 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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Tournament.Screens.TeamWin;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneTeamWinScreen : TournamentTestScene
{
[Test]
public void TestBasic()
{
AddStep("set up match", () =>
{
var match = Ladder.CurrentMatch.Value;
match.Round.Value = Ladder.Rounds.FirstOrDefault(g => g.Name.Value == "Finals");
match.Completed.Value = true;
});
AddStep("create screen", () => Add(new TeamWinScreen
{
FillMode = FillMode.Fit,
FillAspectRatio = 16 / 9f
}));
}
}
}
|
Add Email Setting Seed Items | using Portal.CMS.Entities.Entities.Settings;
using System.Collections.Generic;
using System.Linq;
namespace Portal.CMS.Entities.Seed
{
public static class SettingSeed
{
public static void Seed(PortalEntityModel context)
{
var settingList = context.Settings.ToList();
var newSettings = new List<Setting>();
if (!settingList.Any(x => x.SettingName == "Website Name"))
newSettings.Add(new Setting { SettingName = "Website Name", SettingValue = "Portal CMS" });
if (!settingList.Any(x => x.SettingName == "Description Meta Tag"))
newSettings.Add(new Setting { SettingName = "Description Meta Tag", SettingValue = "Portal CMS is a fully featured content management system with a powerful integrated page builder." });
if (!settingList.Any(x => x.SettingName == "Google Analytics Tracking ID"))
newSettings.Add(new Setting { SettingName = "Google Analytics Tracking ID", SettingValue = "" });
if (newSettings.Any())
context.Settings.AddRange(newSettings);
}
}
} | using Portal.CMS.Entities.Entities.Settings;
using System.Collections.Generic;
using System.Linq;
namespace Portal.CMS.Entities.Seed
{
public static class SettingSeed
{
public static void Seed(PortalEntityModel context)
{
var settingList = context.Settings.ToList();
var newSettings = new List<Setting>();
if (!settingList.Any(x => x.SettingName == "Website Name"))
newSettings.Add(new Setting { SettingName = "Website Name", SettingValue = "Portal CMS" });
if (!settingList.Any(x => x.SettingName == "Description Meta Tag"))
newSettings.Add(new Setting { SettingName = "Description Meta Tag", SettingValue = "Portal CMS is a fully featured content management system with a powerful integrated page builder." });
if (!settingList.Any(x => x.SettingName == "Google Analytics Tracking ID"))
newSettings.Add(new Setting { SettingName = "Google Analytics Tracking ID", SettingValue = "" });
if (!settingList.Any(x => x.SettingName == "Email From Address"))
newSettings.Add(new Setting { SettingName = "Email From Address", SettingValue = "" });
if (!settingList.Any(x => x.SettingName == "SendGrid UserName"))
newSettings.Add(new Setting { SettingName = "SendGrid UserName", SettingValue = "" });
if (!settingList.Any(x => x.SettingName == "SendGrid Password"))
newSettings.Add(new Setting { SettingName = "SendGrid Password", SettingValue = "" });
if (newSettings.Any())
context.Settings.AddRange(newSettings);
}
}
} |
Add logging capability to serviceaware | using WebApiToTypeScript.Enums;
using WebApiToTypeScript.Interfaces;
using WebApiToTypeScript.Types;
namespace WebApiToTypeScript
{
public abstract class ServiceAware
{
protected string IHaveQueryParams = WebApiToTypeScript.IHaveQueryParams;
protected string IEndpoint = WebApiToTypeScript.IEndpoint;
protected TypeService TypeService
=> WebApiToTypeScript.TypeService;
protected EnumsService EnumsService
=> WebApiToTypeScript.EnumsService;
protected InterfaceService InterfaceService
=> WebApiToTypeScript.InterfaceService;
public Config.Config Config
=> WebApiToTypeScript.Config;
}
} | using WebApiToTypeScript.Enums;
using WebApiToTypeScript.Interfaces;
using WebApiToTypeScript.Types;
namespace WebApiToTypeScript
{
public abstract class ServiceAware
{
protected string IHaveQueryParams = WebApiToTypeScript.IHaveQueryParams;
protected string IEndpoint = WebApiToTypeScript.IEndpoint;
protected TypeService TypeService
=> WebApiToTypeScript.TypeService;
protected EnumsService EnumsService
=> WebApiToTypeScript.EnumsService;
protected InterfaceService InterfaceService
=> WebApiToTypeScript.InterfaceService;
public Config.Config Config
=> WebApiToTypeScript.Config;
public void LogMessage(string message)
=> WebApiToTypeScript.LogMessages.Add(message);
}
} |
Add groups to the serialization | using System.Net;
using System.Threading.Tasks;
using FlatBuffers;
using InWorldz.Arbiter.Serialization;
using InWorldz.Chrysalis.Util;
namespace InWorldz.Chrysalis.Controllers
{
/// <summary>
/// Handles incoming requests related to geometry
/// </summary>
internal class GeometryController
{
public GeometryController(HttpFrontend frontEnd)
{
frontEnd.AddHandler("POST", "/geometry/h2b", ConvertHalcyonGeomToBabylon);
}
private async Task ConvertHalcyonGeomToBabylon(HttpListenerContext context, HttpListenerRequest request)
{
//halcyon gemoetry is coming in as a primitive flatbuffer object
//as binary in the body. deserialize and convert using the prim exporter
ByteBuffer body = await StreamUtil.ReadStreamFullyAsync(request.InputStream);
var prim = HalcyonPrimitive.GetRootAsHalcyonPrimitive(body);
}
}
} | using System.Net;
using System.Threading.Tasks;
using FlatBuffers;
using InWorldz.Arbiter.Serialization;
using InWorldz.Chrysalis.Util;
namespace InWorldz.Chrysalis.Controllers
{
/// <summary>
/// Handles incoming requests related to geometry
/// </summary>
internal class GeometryController
{
public GeometryController(HttpFrontend frontEnd)
{
frontEnd.AddHandler("POST", "/geometry/hp2b", ConvertHalcyonPrimToBabylon);
frontEnd.AddHandler("POST", "/geometry/hg2b", ConvertHalcyonGroupToBabylon);
}
private async Task ConvertHalcyonPrimToBabylon(HttpListenerContext context, HttpListenerRequest request)
{
//halcyon gemoetry is coming in as a primitive flatbuffer object
//as binary in the body. deserialize and convert using the prim exporter
ByteBuffer body = await StreamUtil.ReadStreamFullyAsync(request.InputStream);
var prim = HalcyonPrimitive.GetRootAsHalcyonPrimitive(body);
}
private async Task ConvertHalcyonGroupToBabylon(HttpListenerContext context, HttpListenerRequest request)
{
//halcyon gemoetry is coming in as a primitive flatbuffer object
//as binary in the body. deserialize and convert using the prim exporter
ByteBuffer body = await StreamUtil.ReadStreamFullyAsync(request.InputStream);
var prim = HalcyonPrimitive.GetRootAsHalcyonPrimitive(body);
}
}
} |
Fix assert hit during OnInstantiated validation | using System;
using ModestTree;
namespace Zenject
{
[NoReflectionBaking]
public class InstantiateCallbackConditionCopyNonLazyBinder : ConditionCopyNonLazyBinder
{
public InstantiateCallbackConditionCopyNonLazyBinder(BindInfo bindInfo)
: base(bindInfo)
{
}
public ConditionCopyNonLazyBinder OnInstantiated(
Action<InjectContext, object> callback)
{
BindInfo.InstantiatedCallback = callback;
return this;
}
public ConditionCopyNonLazyBinder OnInstantiated<T>(
Action<InjectContext, T> callback)
{
// Can't do this here because of factory bindings
//Assert.That(BindInfo.ContractTypes.All(x => x.DerivesFromOrEqual<T>()));
BindInfo.InstantiatedCallback = (ctx, obj) =>
{
Assert.That(obj == null || obj is T,
"Invalid generic argument to OnInstantiated! {0} must be type {1}", obj.GetType(), typeof(T));
callback(ctx, (T)obj);
};
return this;
}
}
}
| using System;
using ModestTree;
namespace Zenject
{
[NoReflectionBaking]
public class InstantiateCallbackConditionCopyNonLazyBinder : ConditionCopyNonLazyBinder
{
public InstantiateCallbackConditionCopyNonLazyBinder(BindInfo bindInfo)
: base(bindInfo)
{
}
public ConditionCopyNonLazyBinder OnInstantiated(
Action<InjectContext, object> callback)
{
BindInfo.InstantiatedCallback = callback;
return this;
}
public ConditionCopyNonLazyBinder OnInstantiated<T>(
Action<InjectContext, T> callback)
{
// Can't do this here because of factory bindings
//Assert.That(BindInfo.ContractTypes.All(x => x.DerivesFromOrEqual<T>()));
BindInfo.InstantiatedCallback = (ctx, obj) =>
{
if (obj is ValidationMarker)
{
Assert.That(ctx.Container.IsValidating);
ValidationMarker marker = obj as ValidationMarker;
Assert.That(marker.MarkedType.DerivesFromOrEqual<T>(),
"Invalid generic argument to OnInstantiated! {0} must be type {1}", marker.MarkedType, typeof(T));
}
else
{
Assert.That(obj == null || obj is T,
"Invalid generic argument to OnInstantiated! {0} must be type {1}", obj.GetType(), typeof(T));
callback(ctx, (T)obj);
}
};
return this;
}
}
}
|
Remove a redundant UpdateLayout invocation | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace DotNetKit.Windows.Documents
{
/// <summary>
/// Provides functions.
/// </summary>
public struct FixedDocumentCreator
{
/// <summary>
/// Converts data contexts to a <see cref="FixedDocument"/>.
/// </summary>
public FixedDocument FromDataContexts(IEnumerable contents, Size pageSize)
{
var isLandscape = pageSize.Width > pageSize.Height;
var mediaSize = isLandscape ? new Size(pageSize.Height, pageSize.Width) : pageSize;
var document = new FixedDocument();
foreach (var content in contents)
{
var presenter =
new ContentPresenter()
{
Content = content,
Width = pageSize.Width,
Height = pageSize.Height,
};
if (isLandscape)
{
presenter.LayoutTransform = new RotateTransform(90.0);
}
var page =
new FixedPage()
{
Width = mediaSize.Width,
Height = mediaSize.Height,
};
page.Children.Add(presenter);
page.Measure(mediaSize);
page.Arrange(new Rect(new Point(0, 0), mediaSize));
page.UpdateLayout();
var pageContent = new PageContent() { Child = page };
document.Pages.Add(pageContent);
}
return document;
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace DotNetKit.Windows.Documents
{
/// <summary>
/// Provides functions.
/// </summary>
public struct FixedDocumentCreator
{
/// <summary>
/// Converts data contexts to a <see cref="FixedDocument"/>.
/// </summary>
public FixedDocument FromDataContexts(IEnumerable contents, Size pageSize)
{
var isLandscape = pageSize.Width > pageSize.Height;
var mediaSize = isLandscape ? new Size(pageSize.Height, pageSize.Width) : pageSize;
var document = new FixedDocument();
foreach (var content in contents)
{
var presenter =
new ContentPresenter()
{
Content = content,
Width = pageSize.Width,
Height = pageSize.Height,
};
if (isLandscape)
{
presenter.LayoutTransform = new RotateTransform(90.0);
}
var page =
new FixedPage()
{
Width = mediaSize.Width,
Height = mediaSize.Height,
};
page.Children.Add(presenter);
var pageContent = new PageContent() { Child = page };
document.Pages.Add(pageContent);
}
return document;
}
}
}
|
Reword taiko easy mod description to fit others better | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModEasy : ModEasy
{
public override string Description => @"Beats move slower, less accuracy required!";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModEasy : ModEasy
{
public override string Description => @"Beats move slower, and less accuracy required!";
}
}
|
Add LayeredHitSamples skin config lookup | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Skinning
{
public enum GlobalSkinConfiguration
{
AnimationFramerate
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Skinning
{
public enum GlobalSkinConfiguration
{
AnimationFramerate,
LayeredHitSounds,
}
}
|
Fix the order of the connect section | using GitHub.Api;
using GitHub.Models;
using GitHub.Services;
using Microsoft.TeamFoundation.Controls;
using System.ComponentModel.Composition;
namespace GitHub.VisualStudio.TeamExplorer.Connect
{
[TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 11)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class GitHubConnectSection1 : GitHubConnectSection
{
public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91";
[ImportingConstructor]
public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager)
: base(apiFactory, holder, manager, 1)
{
}
}
}
| using GitHub.Api;
using GitHub.Models;
using GitHub.Services;
using Microsoft.TeamFoundation.Controls;
using System.ComponentModel.Composition;
namespace GitHub.VisualStudio.TeamExplorer.Connect
{
[TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 10)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class GitHubConnectSection1 : GitHubConnectSection
{
public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91";
[ImportingConstructor]
public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager)
: base(apiFactory, holder, manager, 1)
{
}
}
}
|
Make it harder to accidentally reset prod database | using System;
using AnlabMvc.Models.Roles;
using AnlabMvc.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace AnlabMvc.Controllers
{
[Authorize(Roles = RoleCodes.Admin)]
public class SystemController : ApplicationController
{
private readonly IDbInitializationService _dbInitializationService;
public SystemController(IDbInitializationService dbInitializationService)
{
_dbInitializationService = dbInitializationService;
}
#if DEBUG
public async Task<IActionResult> ResetDb()
{
await _dbInitializationService.RecreateAndInitialize();
return RedirectToAction("LogoutDirect", "Account");
}
#else
public Task<IActionResult> ResetDb()
{
throw new NotImplementedException("WHAT!!! Don't reset DB in Release!");
}
#endif
}
}
| using System;
using AnlabMvc.Models.Roles;
using AnlabMvc.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace AnlabMvc.Controllers
{
[Authorize(Roles = RoleCodes.Admin)]
public class SystemController : ApplicationController
{
private readonly IDbInitializationService _dbInitializationService;
public SystemController(IDbInitializationService dbInitializationService)
{
_dbInitializationService = dbInitializationService;
}
#if DEBUG
public Task<IActionResult> ResetDb()
{
throw new NotImplementedException("Only enable this when working against a local database.");
// await _dbInitializationService.RecreateAndInitialize();
// return RedirectToAction("LogoutDirect", "Account");
}
#else
public Task<IActionResult> ResetDb()
{
throw new NotImplementedException("WHAT!!! Don't reset DB in Release!");
}
#endif
}
}
|
Use HTML helper extension method for outputting an <input type="hidden"/> element | using System.Web.Mvc;
namespace RestfulRouting
{
public static class HtmlHelperExtensions
{
public static MvcHtmlString PutOverrideTag(this HtmlHelper html)
{
return MvcHtmlString.Create("<input type=\"hidden\" name=\"_method\" value=\"put\" />");
}
public static MvcHtmlString DeleteOverrideTag(this HtmlHelper html)
{
return MvcHtmlString.Create("<input type=\"hidden\" name=\"_method\" value=\"delete\" />");
}
}
}
| using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace RestfulRouting
{
public static class HtmlHelperExtensions
{
public static MvcHtmlString PutOverrideTag(this HtmlHelper html)
{
return html.Hidden("_method", "put");
}
public static MvcHtmlString DeleteOverrideTag(this HtmlHelper html)
{
return html.Hidden("_method", "delete");
}
}
}
|
Downgrade version to 0.6.0 again -- only update version upon actual release | 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("SQL Notebook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQL Notebook")]
[assembly: AssemblyCopyright("Copyright © 2016 Brian Luft")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4766090d-0e56-4a24-bde7-3f9fb8d37c80")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
// this is Application.ProductVersion
[assembly: AssemblyFileVersion("0.7.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("SQL Notebook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQL Notebook")]
[assembly: AssemblyCopyright("Copyright © 2016 Brian Luft")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4766090d-0e56-4a24-bde7-3f9fb8d37c80")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
// this is Application.ProductVersion
[assembly: AssemblyFileVersion("0.6.0")]
|
Change Paddle direction to a float. | using UnityEngine;
public class PaddleController : MonoBehaviour {
[SerializeField]
private float _speed;
[SerializeField]
private Planet _planet;
[SerializeField]
private float _orbitAngle;
[SerializeField]
private float _orbitDistance;
public enum MoveDirection {
Left = -1,
None = 0,
Right = 1,
}
public float Speed {
get { return _speed; }
set { _speed = value; }
}
public MoveDirection Direction {
get; set;
}
public Planet Planet {
get { return _planet; }
set { _planet = value; }
}
public float OrbitAngle {
get { return _orbitAngle; }
private set { _orbitAngle = value; }
}
public float OrbitDistance {
get { return _orbitDistance; }
set { _orbitDistance = value; }
}
private void FixedUpdate() {
int direction = (int) Direction;
float anglePerSecond = Speed / Planet.Permieter * direction;
float deltaAngle = Time.fixedDeltaTime * anglePerSecond;
OrbitAngle += deltaAngle;
Vector3 targetPosition, targetFacing;
Planet.SampleOrbit2D( OrbitAngle, OrbitDistance,
out targetPosition, out targetFacing );
transform.forward = targetFacing;
transform.position = targetPosition;
}
}
| using UnityEngine;
public class PaddleController : MonoBehaviour {
[SerializeField]
private float _speed;
[SerializeField]
private Planet _planet;
[SerializeField]
private float _orbitAngle;
[SerializeField]
private float _orbitDistance;
[SerializeField, Range( -1, 1 )]
private float _direction = 0;
public float Speed {
get { return _speed; }
set { _speed = value; }
}
public float Direction {
get { return _direction; }
set { _direction = Mathf.Clamp( value, -1, 1 ) };
}
public Planet Planet {
get { return _planet; }
set { _planet = value; }
}
public float OrbitAngle {
get { return _orbitAngle; }
private set { _orbitAngle = value; }
}
public float OrbitDistance {
get { return _orbitDistance; }
set { _orbitDistance = value; }
}
private void FixedUpdate() {
float anglePerSecond = Speed / Planet.Permieter * Direction;
float deltaAngle = Time.fixedDeltaTime * anglePerSecond;
OrbitAngle += deltaAngle;
Vector3 targetPosition, targetFacing;
Planet.SampleOrbit2D( OrbitAngle, OrbitDistance,
out targetPosition, out targetFacing );
transform.forward = targetFacing;
transform.position = targetPosition;
}
}
|
Add API to get a user's active consultations. | // Copyright 2015 SnapMD, 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.
using System.Net;
using SnapMD.ConnectedCare.Sdk.Wrappers;
namespace SnapMD.ConnectedCare.Sdk
{
public class EncountersApi : ApiCall
{
public EncountersApi(string baseUrl, string bearerToken, string developerId, string apiKey)
: base(baseUrl, new WebClientWrapper(new WebClient()), bearerToken, developerId, apiKey)
{
}
public void UpdateIntakeQuestionnaire(int consultationId, object intakeData)
{
var url = string.Format("v2/patients/consultations/{0}/intake", consultationId);
var result = Put(url, intakeData);
}
}
} | // Copyright 2015 SnapMD, 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.
using System.Net;
using SnapMD.ConnectedCare.ApiModels;
using SnapMD.ConnectedCare.Sdk.Models;
using SnapMD.ConnectedCare.Sdk.Wrappers;
namespace SnapMD.ConnectedCare.Sdk
{
public class EncountersApi : ApiCall
{
public EncountersApi(string baseUrl, string bearerToken, string developerId, string apiKey)
: base(baseUrl, new WebClientWrapper(new WebClient()), bearerToken, developerId, apiKey)
{
}
public void UpdateIntakeQuestionnaire(int consultationId, object intakeData)
{
var url = string.Format("v2/patients/consultations/{0}/intake", consultationId);
var result = Put(url, intakeData);
}
/// <summary>
/// Gets a list of running consultations for the user whether the user is a clinician or a patient.
/// There should be 0 or 1 results, but if there are more, this information can be used for
/// debugging.
/// </summary>
/// <returns></returns>
public ApiResponseV2<PatientConsultationInfo> GetUsersActiveConsultations()
{
const string url = "v2/consultations/running";
var result = MakeCall<ApiResponseV2<PatientConsultationInfo>>(url);
return result;
}
}
} |
Use msbuild path from config.json if present | using System.IO;
using OmniSharp.Solution;
namespace OmniSharp.Build
{
public class BuildCommandBuilder
{
private readonly ISolution _solution;
public BuildCommandBuilder(ISolution solution)
{
_solution = solution;
}
public string Executable
{
get
{
return PlatformService.IsUnix
? "xbuild"
: Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(),
"Msbuild.exe");
}
}
public string Arguments
{
get { return (PlatformService.IsUnix ? "" : "/m ") + "/nologo /v:q /property:GenerateFullPaths=true \"" + _solution.FileName + "\""; }
}
public BuildTargetResponse BuildCommand(BuildTargetRequest req)
{
return new BuildTargetResponse { Command = this.Executable.ApplyPathReplacementsForClient() + " " + this.Arguments + " /target:" + req.Type.ToString() };
}
}
}
| using System.IO;
using OmniSharp.Solution;
namespace OmniSharp.Build
{
public class BuildCommandBuilder
{
private readonly ISolution _solution;
private readonly OmniSharpConfiguration _config;
public BuildCommandBuilder(
ISolution solution,
OmniSharpConfiguration config)
{
_solution = solution;
_config = config;
}
public string Executable
{
get
{
return PlatformService.IsUnix
? "xbuild"
: Path.Combine(
_config.MSBuildPath ?? System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(),
"Msbuild.exe");
}
}
public string Arguments
{
get { return (PlatformService.IsUnix ? "" : "/m ") + "/nologo /v:q /property:GenerateFullPaths=true \"" + _solution.FileName + "\""; }
}
public BuildTargetResponse BuildCommand(BuildTargetRequest req)
{
return new BuildTargetResponse { Command = this.Executable.ApplyPathReplacementsForClient() + " " + this.Arguments + " /target:" + req.Type.ToString() };
}
}
}
|
Fix typo in data object cloning. | using System;
using SQLite;
namespace Toggl.Phoebe.Data.DataObjects
{
[Table ("Project")]
public class ProjectData : CommonData
{
public ProjectData ()
{
}
public ProjectData (ProjectData other) : base (other)
{
Name = other.Name;
Color = other.Color;
IsActive = other.IsActive;
IsBillable = other.IsBillable;
IsPrivate = other.IsBillable;
IsTemplate = other.IsTemplate;
UseTasksEstimate = other.UseTasksEstimate;
WorkspaceId = other.WorkspaceId;
ClientId = other.ClientId;
}
public string Name { get; set; }
public int Color { get; set; }
public bool IsActive { get; set; }
public bool IsBillable { get; set; }
public bool IsPrivate { get; set; }
public bool IsTemplate { get; set; }
public bool UseTasksEstimate { get; set; }
[ForeignRelation (typeof(WorkspaceData))]
public Guid WorkspaceId { get; set; }
[ForeignRelation (typeof(ClientData))]
public Guid? ClientId { get; set; }
}
}
| using System;
using SQLite;
namespace Toggl.Phoebe.Data.DataObjects
{
[Table ("Project")]
public class ProjectData : CommonData
{
public ProjectData ()
{
}
public ProjectData (ProjectData other) : base (other)
{
Name = other.Name;
Color = other.Color;
IsActive = other.IsActive;
IsBillable = other.IsBillable;
IsPrivate = other.IsPrivate;
IsTemplate = other.IsTemplate;
UseTasksEstimate = other.UseTasksEstimate;
WorkspaceId = other.WorkspaceId;
ClientId = other.ClientId;
}
public string Name { get; set; }
public int Color { get; set; }
public bool IsActive { get; set; }
public bool IsBillable { get; set; }
public bool IsPrivate { get; set; }
public bool IsTemplate { get; set; }
public bool UseTasksEstimate { get; set; }
[ForeignRelation (typeof(WorkspaceData))]
public Guid WorkspaceId { get; set; }
[ForeignRelation (typeof(ClientData))]
public Guid? ClientId { get; set; }
}
}
|
Refactor pagination to a common base class |
namespace Acme.Helpers
{
/// <summary>
/// Horizontal alignment options.
/// </summary>
public enum HorizontalAlignment { Left, Right, }
public enum PagerVerticalAlignment { Top, Bottom, Both }
}
|
namespace Acme.Helpers
{
/// <summary>
/// Horizontal alignment options.
/// </summary>
public enum HorizontalAlignment { Left, Right, }
}
|
Set improved ThreadPool values for nancy | using System;
using System.Collections.Generic;
using System.Web;
using Nancy;
using Nancy.ErrorHandling;
namespace NancyBenchmark
{
public class Global : HttpApplication
{
protected void Application_Start()
{
}
}
} | using System;
using System.Collections.Generic;
using System.Web;
using Nancy;
using Nancy.ErrorHandling;
using System.Threading;
namespace NancyBenchmark
{
public class Global : HttpApplication
{
protected void Application_Start()
{
var threads = 40 * Environment.ProcessorCount;
ThreadPool.SetMaxThreads(threads, threads);
ThreadPool.SetMinThreads(threads, threads);
}
}
} |
Add new type of devices | // Copyright (c) 2018 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
namespace Wangkanai.Detection
{
public enum DeviceType
{
Desktop,
Tablet,
Mobile
}
} | // Copyright (c) 2018 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
namespace Wangkanai.Detection
{
public enum DeviceType
{
Desktop,
Tablet,
Mobile,
Tv,
Console,
Car
}
}
|
Make accuracy formatting more consistent | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Utils
{
public static class FormatUtils
{
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// Omits all decimal places when <paramref name="accuracy"/> equals 1d.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this double accuracy) => accuracy == 1 ? "100%" : $"{accuracy:0.00%}";
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// Omits all decimal places when <paramref name="accuracy"/> equals 100m.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this decimal accuracy) => accuracy == 100 ? "100%" : $"{accuracy:0.00}%";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Utils
{
public static class FormatUtils
{
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this double accuracy) => $"{accuracy:0.00%}";
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this decimal accuracy) => $"{accuracy:0.00}%";
}
}
|
Make power status properties abstract | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Utils
{
/// <summary>
/// Provides access to the system's power status.
/// Currently implemented on iOS and Android only.
/// </summary>
public abstract class PowerStatus
{
/// <summary>
/// The maximum battery level considered as low, from 0 to 1.
/// </summary>
public virtual double BatteryCutoff { get; } = 0;
/// <summary>
/// The charge level of the battery, from 0 to 1.
/// </summary>
public virtual double ChargeLevel { get; } = 0;
public virtual bool IsCharging { get; } = false;
/// <summary>
/// Whether the battery is currently low in charge.
/// Returns true if not charging and current charge level is lower than or equal to <see cref="BatteryCutoff"/>.
/// </summary>
public bool IsLowBattery => !IsCharging && ChargeLevel <= BatteryCutoff;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Utils
{
/// <summary>
/// Provides access to the system's power status.
/// Currently implemented on iOS and Android only.
/// </summary>
public abstract class PowerStatus
{
/// <summary>
/// The maximum battery level considered as low, from 0 to 1.
/// </summary>
public abstract double BatteryCutoff { get; }
/// <summary>
/// The charge level of the battery, from 0 to 1.
/// </summary>
public abstract double ChargeLevel { get; }
public abstract bool IsCharging { get; }
/// <summary>
/// Whether the battery is currently low in charge.
/// Returns true if not charging and current charge level is lower than or equal to <see cref="BatteryCutoff"/>.
/// </summary>
public bool IsLowBattery => !IsCharging && ChargeLevel <= BatteryCutoff;
}
}
|
Add New Exception *() saftynet | using RestSharp;
using jRace.PrivateClass.Main;
Namespace Inject {
public class Inject {
file = new jRace.PrivateClass.Main();
brows = new jRace.PrivateClass.Brows();
private main() {
var browser = brows.runproc(get());
brows.getID(browser);
brows.Select(ID);
return(load);
}
load void(){
file.Load(token.Method());
file.Send(token, login);
return(saftynet);
}
}
}
| using RestSharp;
using jRace.PrivateClass.Main;
Namespace Inject {
public class Inject {
file = new jRace.PrivateClass.Main();
brows = new jRace.PrivateClass.Brows();
private main() {
var browser = brows.runproc(get());
var bID = brows.getID(browser());
brows.Select(bID, int);
if(ID = null || ID == 0){
await saftynet(brower);
}
else{
return(load);
}
}
load void(){
file.Load(token.Method());
file.Send(token, login);
return(saftynet);
}
}
}
|
Fix async behavior of console program. | using System;
using System.Net.Http;
using System.Threading.Tasks;
using PortableWordPressApi;
namespace ApiConsole
{
class Program
{
static void Main(string[] args)
{
Task.WhenAll(AsyncMain());
Console.WriteLine("Press any key to close.");
Console.Read();
}
private static async Task AsyncMain()
{
Console.WriteLine("Enter site URL:");
var url = Console.ReadLine();
Console.WriteLine("Searching for API at {0}", url);
var httpClient = new HttpClient();
var discovery = new WordPressApiDiscovery(new Uri(url, UriKind.Absolute), httpClient);
var api = await discovery.DiscoverApiForSite();
Console.WriteLine("Site's API endpoint: {0}", api.ApiRootUri);
}
}
}
| using System;
using System.Net.Http;
using System.Threading.Tasks;
using PortableWordPressApi;
namespace ApiConsole
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(AsyncMain());
Console.WriteLine("Press any key to close.");
Console.Read();
}
private static async Task AsyncMain()
{
Console.WriteLine("Enter site URL:");
var url = Console.ReadLine();
Console.WriteLine("Searching for API at {0}", url);
var httpClient = new HttpClient();
var discovery = new WordPressApiDiscovery(new Uri(url, UriKind.Absolute), httpClient);
var api = await discovery.DiscoverApiForSite();
Console.WriteLine("Site's API endpoint: {0}", api.ApiRootUri);
}
}
}
|
Raise incoming event on the ThreadPool | using System;
using System.ServiceModel;
namespace Nvents.Services.Network
{
[ServiceBehavior(
InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class EventService : IEventService
{
public event EventHandler<EventPublishedEventArgs> EventPublished;
public void Publish(IEvent @event)
{
if (EventPublished != null)
EventPublished(this, new EventPublishedEventArgs(@event));
}
}
}
| using System;
using System.ServiceModel;
using System.Threading;
namespace Nvents.Services.Network
{
[ServiceBehavior(
InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class EventService : IEventService
{
public event EventHandler<EventPublishedEventArgs> EventPublished;
public void Publish(IEvent @event)
{
if (EventPublished == null)
return;
ThreadPool.QueueUserWorkItem(s =>
EventPublished(null, new EventPublishedEventArgs(@event)));
}
}
}
|
Add NET Standard 1.6 API dependency | using Android.App;
using Android.Widget;
using Android.OS;
namespace MatXiTest.Droid
{
[Activity(Label = "MatXiTest", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
}
}
}
| using Android.App;
using Android.Widget;
using Android.OS;
using System.Security.Cryptography;
namespace MatXiTest.Droid
{
[Activity(Label = "MatXiTest", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
ECCurve curve = ECCurve.CreateFromValue("");
}
}
}
|
Add Enabled = true, Exported = false | using System.Collections.Generic;
using Android.Content;
namespace Plugin.FirebasePushNotification
{
[BroadcastReceiver]
public class PushNotificationDeletedReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
}
}
FirebasePushNotificationManager.RegisterDelete(parameters);
}
}
} | using System.Collections.Generic;
using Android.Content;
namespace Plugin.FirebasePushNotification
{
[BroadcastReceiver(Enabled = true, Exported = false)]
public class PushNotificationDeletedReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
}
}
FirebasePushNotificationManager.RegisterDelete(parameters);
}
}
}
|
Fix logic fail with IsNoFlip | using System;
namespace FezEngine.Structure {
public class Level {
public static bool IsNoFlat = false;
public bool orig_get_Flat() {
return false;
}
public bool get_Flat() {
return orig_get_Flat() || !IsNoFlat;
}
}
}
| using System;
namespace FezEngine.Structure {
public class Level {
public static bool IsNoFlat = false;
public bool orig_get_Flat() {
return false;
}
public bool get_Flat() {
return orig_get_Flat() && !IsNoFlat;
}
}
}
|
Include email possibility on server error page | @{
ViewBag.Title = "Er is iets fout gegaan";
}
<div id="top"></div>
<div class="row">
<div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div>
<div class="col-lg-4 col-md-6 col-sm-8 col-xs-8">
<div class="panel panel-default dark">
<div class="panel-heading">
<h1 class="panel-title"><strong>500 Interne Server Fout</strong></h1>
</div>
<p>
<span class="glyphicon glyphicon-heart-empty"></span>
Oeps, sorry, er is iets fout gegaan.<br/><br/>
Er is iets kapot. Als u zo vriendelijk wilt zijn
<a href="https://github.com/erooijak/oogstplanner/issues">
een probleem (issue) aan te maken op onze GitHub
</a>
zullen we er naar kijken.
</p>
</div>
</div>
<div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div>
</div> | @{
ViewBag.Title = "Er is iets fout gegaan";
}
<div id="top"></div>
<div class="row">
<div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div>
<div class="col-lg-4 col-md-6 col-sm-8 col-xs-8">
<div class="panel panel-default dark">
<div class="panel-heading">
<h1 class="panel-title"><strong>500 Interne Server Fout</strong></h1>
</div>
<p>
<span class="glyphicon glyphicon-heart-empty"></span>
Oeps, sorry, er is iets fout gegaan.<br/><br/>
Er is iets kapot. Als u zo vriendelijk wilt zijn
<a href="https://github.com/erooijak/oogstplanner/issues">
een probleem (issue) aan te maken op onze GitHub
</a>
of een mail te sturen naar
<a href="mailto:oogstplanner@gmail.com">
oogstplanner@gmail.com
</a>
zullen we er naar kijken.
</p>
</div>
</div>
<div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div>
</div> |
Check if the project names (new and old one) are the same. | using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using EnvDTE;
using MessageBox = System.Windows.Forms.MessageBox;
namespace Twainsoft.SolutionRenamer.VSPackage.GUI
{
public partial class RenameProjectDialog
{
private Project CurrentProject { get; set; }
public RenameProjectDialog(Project project)
{
InitializeComponent();
CurrentProject = project;
ProjectName.Text = project.Name;
ProjectName.Focus();
ProjectName.SelectAll();
}
public string GetProjectName()
{
return ProjectName.Text.Trim();
}
private void Rename_Click(object sender, RoutedEventArgs e)
{
var directory = new FileInfo(CurrentProject.FullName).Directory;
if (directory == null)
{
throw new InvalidOperationException();
}
var parentDirectory = directory.Parent;
if (parentDirectory == null)
{
throw new InvalidOperationException();
}
// Projects with the same name cannot be in the same folder due to the same folder names.
// Within the same solution it is no problem!
if (Directory.Exists(Path.Combine(parentDirectory.FullName, GetProjectName())))
{
MessageBox.Show(
string.Format(
"The project '{0}' already exists in the solution respectively the file system. Please choose another project name.",
GetProjectName()),
"Project already exists", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
DialogResult = true;
Close();
}
}
}
}
| using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using EnvDTE;
using MessageBox = System.Windows.Forms.MessageBox;
namespace Twainsoft.SolutionRenamer.VSPackage.GUI
{
public partial class RenameProjectDialog
{
private Project CurrentProject { get; set; }
public RenameProjectDialog(Project project)
{
InitializeComponent();
CurrentProject = project;
ProjectName.Text = project.Name;
ProjectName.Focus();
ProjectName.SelectAll();
}
public string GetProjectName()
{
return ProjectName.Text.Trim();
}
private void Rename_Click(object sender, RoutedEventArgs e)
{
var directory = new FileInfo(CurrentProject.FullName).Directory;
if (directory == null)
{
throw new InvalidOperationException();
}
var parentDirectory = directory.Parent;
if (parentDirectory == null)
{
throw new InvalidOperationException();
}
// Projects with the same name cannot be in the same folder due to the same folder names.
// Within the same solution it is no problem!
if (Directory.Exists(Path.Combine(parentDirectory.FullName, GetProjectName())))
{
MessageBox.Show(
string.Format(
"The project '{0}' already exists in the solution respectively the file system. Please choose another project name.",
GetProjectName()),
"Project already exists", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (CurrentProject.Name != GetProjectName())
{
DialogResult = true;
Close();
}
else
{
Close();
}
}
}
}
|
Fix an issue Tooltip does not show on the bottom right edge of the primary display | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CreviceApp.Core.Config
{
public class UserInterfaceConfig
{
public Func<Point, Point> TooltipPositionBinding;
public int TooltipTimeout = 2000;
public int BaloonTimeout = 10000;
public UserInterfaceConfig()
{
this.TooltipPositionBinding = (point) =>
{
var rect = Screen.FromPoint(point).WorkingArea;
return new Point(rect.X + rect.Width, rect.Y + rect.Height);
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CreviceApp.Core.Config
{
public class UserInterfaceConfig
{
public Func<Point, Point> TooltipPositionBinding;
public int TooltipTimeout = 2000;
public int BaloonTimeout = 10000;
public UserInterfaceConfig()
{
this.TooltipPositionBinding = (point) =>
{
var rect = Screen.FromPoint(point).WorkingArea;
return new Point(rect.X + rect.Width - 10, rect.Y + rect.Height - 10);
};
}
}
}
|
Use GoogleCredential.CreateScoped to create test credentials | //
// Copyright 2019 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 Google.Apis.Auth.OAuth2;
using System;
using System.IO;
namespace Google.Solutions.Compute.Test.Env
{
public static class Defaults
{
private const string CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform";
public static readonly string ProjectId = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT");
public static readonly string Zone = "us-central1-a";
public static GoogleCredential GetCredential()
{
var keyFile = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
if (keyFile != null && File.Exists(keyFile))
{
return GoogleCredential.FromFile(keyFile).CreateScoped(CloudPlatformScope);
}
else
{
return GoogleCredential.GetApplicationDefault();
}
}
}
}
| //
// Copyright 2019 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 Google.Apis.Auth.OAuth2;
using System;
using System.IO;
namespace Google.Solutions.Compute.Test.Env
{
public static class Defaults
{
private const string CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform";
public static readonly string ProjectId = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT");
public static readonly string Zone = "us-central1-a";
public static GoogleCredential GetCredential()
{
var credential = GoogleCredential.GetApplicationDefault();
return credential.IsCreateScopedRequired
? credential.CreateScoped(CloudPlatformScope)
: credential;
}
}
}
|
Move to the new StripeBasicService instead of StripeService | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeEphemeralKeyService : StripeService
{
public StripeEphemeralKeyService(string apiKey = null) : base(apiKey) { }
//Sync
public virtual StripeEphemeralKey Create(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null)
{
return Mapper<StripeEphemeralKey>.MapFromJson(
Requestor.PostString(this.ApplyAllParameters(createOptions, Urls.EphemeralKeys, false),
SetupRequestOptions(requestOptions))
);
}
public virtual StripeDeleted Delete(string EphemeralKeyId, StripeRequestOptions requestOptions = null)
{
return Mapper<StripeDeleted>.MapFromJson(
Requestor.Delete(this.ApplyAllParameters(null, $"{Urls.EphemeralKeys}/{EphemeralKeyId}", false),
SetupRequestOptions(requestOptions))
);
}
//Async
public virtual async Task<StripeEphemeralKey> CreateAsync(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Mapper<StripeEphemeralKey>.MapFromJson(
await Requestor.PostStringAsync(this.ApplyAllParameters(createOptions, Urls.EphemeralKeys, false),
SetupRequestOptions(requestOptions),
cancellationToken)
);
}
public virtual async Task<StripeDeleted> DeleteAsync(string EphemeralKeyId, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Mapper<StripeDeleted>.MapFromJson(
await Requestor.DeleteAsync(this.ApplyAllParameters(null, $"{Urls.EphemeralKeys}/{EphemeralKeyId}", false),
SetupRequestOptions(requestOptions),
cancellationToken)
);
}
}
}
| using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeEphemeralKeyService : StripeBasicService<StripeEphemeralKey>
{
public StripeEphemeralKeyService(string apiKey = null) : base(apiKey) { }
// Sync
public virtual StripeEphemeralKey Create(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null)
{
return Post(Urls.EphemeralKeys, requestOptions, createOptions);
}
public virtual StripeDeleted Delete(string keyId, StripeRequestOptions requestOptions = null)
{
return DeleteEntity($"{Urls.EphemeralKeys}/{keyId}", requestOptions);
}
// Async
public virtual Task<StripeEphemeralKey> CreateAsync(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostAsync(Urls.EphemeralKeys, requestOptions, cancellationToken, createOptions);
}
public virtual Task<StripeDeleted> DeleteAsync(string keyId, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteEntityAsync($"{Urls.EphemeralKeys}/{keyId}", requestOptions, cancellationToken);
}
}
}
|
Add PlayerSpaceship to a level | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelManager : MonoBehaviour {
public EnemySpaceShip enemy;
public void SetupLevel() {
LayoutObject();
}
private void LayoutObject() {
Instantiate(enemy, new Vector3(9f, 0f, 0f), Quaternion.identity);
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelManager : MonoBehaviour {
public EnemySpaceShip enemy;
public PlayerSpaceShip player;
public void SetupLevel() {
LayoutObject();
}
private void LayoutObject() {
Instantiate(enemy, new Vector3(9f, 0f, 0f), Quaternion.identity);
Instantiate(player, new Vector3(-9f, 0f, 0f), Quaternion.identity);
}
}
|
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
|
Set JSON as the default (and only) formatter | using System.Web.Http;
namespace Nora
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
}
}
} | using System.Web.Http;
namespace Nora
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
// Remove XML formatter
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
} |
Add implementation of enumerable interface for list responses. | namespace TraktApiSharp.Experimental.Responses
{
using Exceptions;
using System.Collections.Generic;
public class TraktListResponse<TContentType> : ATraktResponse<List<TContentType>>, ITraktResponseHeaders
{
public string SortBy { get; set; }
public string SortHow { get; set; }
public int? UserCount { get; set; }
internal TraktListResponse() : base() { }
internal TraktListResponse(List<TContentType> value) : base(value) { }
internal TraktListResponse(TraktException exception) : base(exception) { }
public static explicit operator List<TContentType>(TraktListResponse<TContentType> response) => response.Value;
public static implicit operator TraktListResponse<TContentType>(List<TContentType> value) => new TraktListResponse<TContentType>(value);
}
}
| namespace TraktApiSharp.Experimental.Responses
{
using Exceptions;
using System.Collections;
using System.Collections.Generic;
public class TraktListResponse<TContentType> : ATraktResponse<List<TContentType>>, ITraktResponseHeaders, IEnumerable<TContentType>
{
public string SortBy { get; set; }
public string SortHow { get; set; }
public int? UserCount { get; set; }
internal TraktListResponse() : base() { }
internal TraktListResponse(List<TContentType> value) : base(value) { }
internal TraktListResponse(TraktException exception) : base(exception) { }
public static explicit operator List<TContentType>(TraktListResponse<TContentType> response) => response.Value;
public static implicit operator TraktListResponse<TContentType>(List<TContentType> value) => new TraktListResponse<TContentType>(value);
public IEnumerator<TContentType> GetEnumerator() => Value.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
Remove request HTTP method from logging | // © Alexander Kozlenko. Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Serilog;
using Serilog.Events;
namespace Anemonis.MicrosoftOffice.AddinHost.Middleware
{
/// <summary>Represents request tracking middleware.</summary>
public sealed class RequestTracingMiddleware : IMiddleware
{
private readonly ILogger _logger;
/// <summary>Initializes a new instance of the <see cref="RequestTracingMiddleware" /> class.</summary>
/// <param name="logger">The logger instance.</param>
/// <exception cref="ArgumentNullException"><paramref name="logger" /> is <see langword="null" />.</exception>
public RequestTracingMiddleware(ILogger logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_logger = logger;
}
async Task IMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
finally
{
var level = context.Response.StatusCode < StatusCodes.Status400BadRequest ? LogEventLevel.Information : LogEventLevel.Error;
_logger.Write(level, "{0} {1} {2}", context.Response.StatusCode, context.Request.Method, context.Request.GetEncodedPathAndQuery());
}
}
}
} | // © Alexander Kozlenko. Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Serilog;
using Serilog.Events;
namespace Anemonis.MicrosoftOffice.AddinHost.Middleware
{
/// <summary>Represents request tracking middleware.</summary>
public sealed class RequestTracingMiddleware : IMiddleware
{
private readonly ILogger _logger;
/// <summary>Initializes a new instance of the <see cref="RequestTracingMiddleware" /> class.</summary>
/// <param name="logger">The logger instance.</param>
/// <exception cref="ArgumentNullException"><paramref name="logger" /> is <see langword="null" />.</exception>
public RequestTracingMiddleware(ILogger logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_logger = logger;
}
async Task IMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
finally
{
var level = context.Response.StatusCode < StatusCodes.Status400BadRequest ? LogEventLevel.Information : LogEventLevel.Error;
_logger.Write(level, "{0} {1}", context.Response.StatusCode, context.Request.GetEncodedPathAndQuery());
}
}
}
} |
Fix test assembly load path | using System.Collections.Generic;
using System.Reflection;
using Shouldly;
using Xunit;
namespace libpolyglot.Tests
{
public class Assembly_tests
{
public static IEnumerable<object[]> TestAssemblies()
{
yield return new object[] { "EmptyVB.dll", Language.Vb };
yield return new object[] { "EmptyCS.dll", Language.CSharp };
yield return new object[] { "AnonymousAsyncVB.dll", Language.Vb };
yield return new object[] { "AnonymousAsyncCS.dll", Language.CSharp };
yield return new object[] { "DynamicCS.dll", Language.CSharp };
yield return new object[] { "EmptyFSharp.dll", Language.FSharp };
}
[Theory]
[MemberData(nameof(TestAssemblies))]
public void When_analyzing(string file, Language expected)
{
var assembly = Assembly.LoadFrom($"TestAssemblies\\{file}");
var analyzer = new AssemblyAnalyzer(assembly);
analyzer.DetectedLanguage.ShouldBe(expected);
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Shouldly;
using Xunit;
namespace libpolyglot.Tests
{
public class Assembly_tests
{
public static IEnumerable<object[]> TestAssemblies()
{
yield return new object[] { "EmptyVB.dll", Language.Vb };
yield return new object[] { "EmptyCS.dll", Language.CSharp };
yield return new object[] { "AnonymousAsyncVB.dll", Language.Vb };
yield return new object[] { "AnonymousAsyncCS.dll", Language.CSharp };
yield return new object[] { "DynamicCS.dll", Language.CSharp };
yield return new object[] { "EmptyFSharp.dll", Language.FSharp };
}
[Theory]
[MemberData(nameof(TestAssemblies))]
public void When_analyzing(string file, Language expected)
{
var assembly = Assembly.LoadFrom($"TestAssemblies{Path.DirectorySeparatorChar}{file}");
var analyzer = new AssemblyAnalyzer(assembly);
analyzer.DetectedLanguage.ShouldBe(expected);
}
}
}
|
Change http request total name to match Prometheus guidelines | namespace Prometheus.HttpExporter.AspNetCore.HttpRequestCount
{
public class HttpRequestCountOptions : HttpExporterOptionsBase
{
public Counter Counter { get; set; } =
Metrics.CreateCounter(DefaultName, DefaultHelp, HttpRequestLabelNames.All);
private const string DefaultName = "aspnet_http_requests_total";
private const string DefaultHelp = "Provides the count of HTTP requests from an ASP.NET application.";
}
} | namespace Prometheus.HttpExporter.AspNetCore.HttpRequestCount
{
public class HttpRequestCountOptions : HttpExporterOptionsBase
{
public Counter Counter { get; set; } =
Metrics.CreateCounter(DefaultName, DefaultHelp, HttpRequestLabelNames.All);
private const string DefaultName = "http_requests_total";
private const string DefaultHelp = "Provides the count of HTTP requests from an ASP.NET application.";
}
} |
Order elements in some classes | using System;
namespace Gma.QrCodeNet.Encoding.Positioning.Stencils
{
internal abstract class PatternStencilBase : BitMatrix
{
protected const bool O = false;
protected const bool X = true;
internal PatternStencilBase(int version)
{
Version = version;
}
public int Version { get; private set; }
public abstract bool[,] Stencil { get; }
public override bool this[int i, int j]
{
get => Stencil[i, j];
set => throw new NotSupportedException();
}
public override int Width => Stencil.GetLength(0);
public override int Height => Stencil.GetLength(1);
public override bool[,] InternalArray => throw new NotImplementedException();
public abstract void ApplyTo(TriStateMatrix matrix);
}
}
| using System;
namespace Gma.QrCodeNet.Encoding.Positioning.Stencils
{
internal abstract class PatternStencilBase : BitMatrix
{
protected const bool O = false;
protected const bool X = true;
internal PatternStencilBase(int version)
{
Version = version;
}
public int Version { get; private set; }
public abstract bool[,] Stencil { get; }
public override int Width => Stencil.GetLength(0);
public override int Height => Stencil.GetLength(1);
public override bool[,] InternalArray => throw new NotImplementedException();
public override bool this[int i, int j]
{
get => Stencil[i, j];
set => throw new NotSupportedException();
}
public abstract void ApplyTo(TriStateMatrix matrix);
}
}
|
Fix point skipped during get points issue | namespace HelixToolkit.Wpf.SharpDX
{
using System;
using System.Collections.Generic;
using HelixToolkit.SharpDX.Shared.Utilities;
[Serializable]
public class PointGeometry3D : Geometry3D
{
public IEnumerable<Geometry3D.Point> Points
{
get
{
for (int i = 0; i < Indices.Count; i += 2)
{
yield return new Point { P0 = Positions[Indices[i]] };
}
}
}
protected override IOctree CreateOctree(OctreeBuildParameter parameter)
{
return new PointGeometryOctree(Positions, parameter);
}
}
}
| namespace HelixToolkit.Wpf.SharpDX
{
using System;
using System.Collections.Generic;
using HelixToolkit.SharpDX.Shared.Utilities;
[Serializable]
public class PointGeometry3D : Geometry3D
{
public IEnumerable<Geometry3D.Point> Points
{
get
{
for (int i = 0; i < Positions.Count; ++i)
{
yield return new Point { P0 = Positions[i] };
}
}
}
protected override IOctree CreateOctree(OctreeBuildParameter parameter)
{
return new PointGeometryOctree(Positions, parameter);
}
}
}
|
Allow to define host address in client | using System;
using System.ServiceModel;
using Service;
namespace Client
{
class Program
{
static void Main(string[] args)
{
var address = new EndpointAddress(new Uri("http://localhost:9000/MyService"));
var binding = new BasicHttpBinding();
var factory = new ChannelFactory<IWcfService>(binding, address);
IWcfService host = factory.CreateChannel();
Console.WriteLine("Please enter some words or press [Esc] to exit the application.");
while (true)
{
var key = Console.ReadKey();
if (key.Key.Equals(ConsoleKey.Escape))
{
return;
}
string input = key.KeyChar.ToString() + Console.ReadLine(); // read input
string output = host.Echo(input); // send to host, receive output
Console.WriteLine(output); // write output
}
}
}
}
| using System;
using System.ServiceModel;
using Service;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter server address: ");
var hostAddress = Console.ReadLine();
var address = new EndpointAddress(new Uri(string.Format("http://{0}:9000/MyService", hostAddress)));
var binding = new BasicHttpBinding();
var factory = new ChannelFactory<IWcfService>(binding, address);
IWcfService host = factory.CreateChannel();
Console.WriteLine("Please enter some words or press [Esc] to exit the application.");
while (true)
{
var key = Console.ReadKey();
if (key.Key.Equals(ConsoleKey.Escape))
{
return;
}
string input = key.KeyChar.ToString() + Console.ReadLine(); // read input
string output = host.Echo(input); // send to host, receive output
Console.WriteLine(output); // write output
}
}
}
}
|
Add PrepaymentID to bank transaction | using System;
namespace XeroApi.Model
{
public class BankTransaction : EndpointModelBase
{
[ItemId]
public Guid? BankTransactionID { get; set; }
public Account BankAccount { get; set; }
public string Type { get; set; }
public string Reference { get; set; }
public string Url { get; set; }
public string ExternalLinkProviderName { get; set; }
public bool IsReconciled { get; set; }
public decimal? CurrencyRate { get; set; }
public Contact Contact { get; set; }
public DateTime? Date { get; set; }
public DateTime? DueDate { get; set; }
public virtual Guid? BrandingThemeID { get; set; }
public virtual string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public virtual LineItems LineItems { get; set; }
public virtual decimal? SubTotal { get; set; }
public virtual decimal? TotalTax { get; set; }
public virtual decimal? Total { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public virtual string CurrencyCode { get; set; }
public DateTime? FullyPaidOnDate { get; set; }
}
public class BankTransactions : ModelList<BankTransaction>
{
}
} | using System;
namespace XeroApi.Model
{
public class BankTransaction : EndpointModelBase
{
[ItemId]
public Guid? BankTransactionID { get; set; }
public Account BankAccount { get; set; }
public string Type { get; set; }
public string Reference { get; set; }
public string Url { get; set; }
public string ExternalLinkProviderName { get; set; }
public bool IsReconciled { get; set; }
public decimal? CurrencyRate { get; set; }
public Contact Contact { get; set; }
public DateTime? Date { get; set; }
public DateTime? DueDate { get; set; }
public virtual Guid? BrandingThemeID { get; set; }
public virtual string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public virtual LineItems LineItems { get; set; }
public virtual decimal? SubTotal { get; set; }
public virtual decimal? TotalTax { get; set; }
public virtual decimal? Total { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public virtual string CurrencyCode { get; set; }
public DateTime? FullyPaidOnDate { get; set; }
public Guid? PrepaymentID { get; set; }
}
public class BankTransactions : ModelList<BankTransaction>
{
}
} |
Fix compilation after sdk api changes | using System;
using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree;
using JetBrains.ReSharper.Psi.Parsing;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.Text;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Yaml.Psi.Parsing
{
public abstract class YamlTokenBase : BindedToBufferLeafElement, IYamlTreeNode, ITokenNode
{
protected YamlTokenBase(NodeType nodeType, IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset)
: base(nodeType, buffer, startOffset, endOffset)
{
}
public override PsiLanguageType Language => LanguageFromParent;
public virtual void Accept(TreeNodeVisitor visitor)
{
visitor.VisitNode(this);
}
public virtual void Accept<TContext>(TreeNodeVisitor<TContext> visitor, TContext context)
{
visitor.VisitNode(this, context);
}
public virtual TResult Accept<TContext, TResult>(TreeNodeVisitor<TContext, TResult> visitor, TContext context)
{
return visitor.VisitNode(this, context);
}
public TokenNodeType GetTokenType() => (TokenNodeType) NodeType;
public override string ToString()
{
var text = GetTextAsBuffer().GetText(new TextRange(0, Math.Min(100, Length)));
return $"{base.ToString()}(type:{NodeType}, text:{text})";
}
}
} | using System;
using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree;
using JetBrains.ReSharper.Psi.Parsing;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.Text;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Yaml.Psi.Parsing
{
public abstract class YamlTokenBase : BoundToBufferLeafElement, IYamlTreeNode, ITokenNode
{
protected YamlTokenBase(NodeType nodeType, IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset)
: base(nodeType, buffer, startOffset, endOffset)
{
}
public override PsiLanguageType Language => LanguageFromParent;
public virtual void Accept(TreeNodeVisitor visitor)
{
visitor.VisitNode(this);
}
public virtual void Accept<TContext>(TreeNodeVisitor<TContext> visitor, TContext context)
{
visitor.VisitNode(this, context);
}
public virtual TResult Accept<TContext, TResult>(TreeNodeVisitor<TContext, TResult> visitor, TContext context)
{
return visitor.VisitNode(this, context);
}
public TokenNodeType GetTokenType() => (TokenNodeType) NodeType;
public override string ToString()
{
var text = GetTextAsBuffer().GetText(new TextRange(0, Math.Min(100, Length)));
return $"{base.ToString()}(type:{NodeType}, text:{text})";
}
}
} |
Allow logger and serializer to be set to null | using System;
using Foundatio.Serializer;
using Microsoft.Extensions.Logging;
namespace Foundatio {
public class SharedOptions {
public ISerializer Serializer { get; set; }
public ILoggerFactory LoggerFactory { get; set; }
}
public class SharedOptionsBuilder<TOption, TBuilder> : OptionsBuilder<TOption>
where TOption : SharedOptions, new()
where TBuilder : SharedOptionsBuilder<TOption, TBuilder> {
public TBuilder Serializer(ISerializer serializer) {
Target.Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); ;
return (TBuilder)this;
}
public TBuilder LoggerFactory(ILoggerFactory loggerFactory) {
Target.LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); ;
return (TBuilder)this;
}
}
}
| using System;
using Foundatio.Serializer;
using Microsoft.Extensions.Logging;
namespace Foundatio {
public class SharedOptions {
public ISerializer Serializer { get; set; }
public ILoggerFactory LoggerFactory { get; set; }
}
public class SharedOptionsBuilder<TOption, TBuilder> : OptionsBuilder<TOption>
where TOption : SharedOptions, new()
where TBuilder : SharedOptionsBuilder<TOption, TBuilder> {
public TBuilder Serializer(ISerializer serializer) {
Target.Serializer = serializer;
return (TBuilder)this;
}
public TBuilder LoggerFactory(ILoggerFactory loggerFactory) {
Target.LoggerFactory = loggerFactory;
return (TBuilder)this;
}
}
}
|
Update score manager to use UI's text | using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace WhoaAlgebraic
{
public class ScoreManager : MonoBehaviour
{
public static int score; // The player's score.
Text text; // Reference to the Text component.
void Awake()
{
// Set up the reference.
text = GetComponent<Text>();
// Reset the score.
score = 0;
}
void Update()
{
// Set the displayed text to be the word "Score" followed by the score value.
text.text = "Score: " + score;
}
}
} | using UnityEngine;
using UnityEngine.UI;
namespace WhoaAlgebraic
{
public class ScoreManager : MonoBehaviour
{
public static int score; // The player's score.
public Text text; // Reference to the Text component.
void Awake()
{
// Reset the score.
score = 0;
}
void Update()
{
// Set the displayed text to be the word "Score" followed by the score value.
text.text = "Score: " + score;
}
}
} |
Update the sample to listen on root addresses instead of a specific path. | using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace Samples.Glitter
{
[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class StaticFilesEndpoint
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/feed")]
public Stream GetFile()
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "Samples.Glitter.feed.html";
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return assembly.GetManifestResourceStream(resourceName);
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace Samples.Glitter
{
[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class StaticFilesEndpoint
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/")]
public Stream GetFile()
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "Samples.Glitter.feed.html";
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return assembly.GetManifestResourceStream(resourceName);
}
}
}
|
Fix test which is incorrect under x64, highlighted by previous commit | using System;
using ClrSpy.Native;
using NUnit.Framework;
namespace ClrSpy.UnitTests.Native
{
[TestFixture]
public class PointerUtilsTests
{
[TestCase(0x07fffffffL, Int32.MaxValue)]
[TestCase(0x080000000L, Int32.MinValue)]
[TestCase(0x000000001L, 1)]
[TestCase(0x000000000L, 0)]
[TestCase(0x0ffffffffL, -1)]
public void CastLongToIntPtr(long longValue, int int32Ptr)
{
Assert.That(PointerUtils.CastLongToIntPtr(longValue), Is.EqualTo(new IntPtr(int32Ptr)));
}
}
}
| using System;
using System.Collections.Generic;
using ClrSpy.Native;
using NUnit.Framework;
namespace ClrSpy.UnitTests.Native
{
[TestFixture]
public class PointerUtilsTests
{
public static IEnumerable<LongToIntPtrCase> LongToIntPtrCases
{
get
{
yield return new LongToIntPtrCase { LongValue = 0x07fffffffL, IntPtrValue = new IntPtr(Int32.MaxValue) };
yield return new LongToIntPtrCase { LongValue = 0x000000001L, IntPtrValue = new IntPtr(1) };
yield return new LongToIntPtrCase { LongValue = 0x000000000L, IntPtrValue = new IntPtr(0) };
if (IntPtr.Size == 8)
{
yield return new LongToIntPtrCase { LongValue = 0x080000000L, IntPtrValue = new IntPtr(0x080000000L) };
yield return new LongToIntPtrCase { LongValue = 0x0ffffffffL, IntPtrValue = new IntPtr(0x0ffffffffL) };
}
if (IntPtr.Size == 4)
{
yield return new LongToIntPtrCase { LongValue = 0x080000000L, IntPtrValue = new IntPtr(Int32.MinValue) };
yield return new LongToIntPtrCase { LongValue = 0x0ffffffffL, IntPtrValue = new IntPtr(-1) };
}
}
}
[TestCaseSource(nameof(LongToIntPtrCases))]
public void CastLongToIntPtr(LongToIntPtrCase testCase)
{
Assert.That(PointerUtils.CastLongToIntPtr(testCase.LongValue), Is.EqualTo(testCase.IntPtrValue));
}
public struct LongToIntPtrCase
{
public long LongValue { get; set; }
public IntPtr IntPtrValue { get; set; }
public override string ToString() => $"{LongValue:X16} -> {IntPtrValue.ToInt64():X16}";
}
}
}
|
Add debugger display attributes for repository actions | using Newtonsoft.Json;
using System.Collections.Generic;
namespace RepoZ.Api.Common.Git
{
public class RepositoryActionConfiguration
{
[JsonProperty("repository-actions")]
public List<RepositoryAction> RepositoryActions { get; set; } = new List<RepositoryAction>();
[JsonProperty("file-associations")]
public List<FileAssociation> FileAssociations { get; set; } = new List<FileAssociation>();
public class RepositoryAction
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("command")]
public string Command { get; set; }
[JsonProperty("executables")]
public List<string> Executables { get; set; } = new List<string>();
[JsonProperty("arguments")]
public string Arguments { get; set; }
[JsonProperty("keys")]
public string Keys { get; set; }
[JsonProperty("active")]
public bool Active { get; set; }
}
public class FileAssociation
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("extension")]
public string Extension { get; set; }
[JsonProperty("executables")]
public List<string> Executables { get; set; } = new List<string>();
[JsonProperty("arguments")]
public string Arguments { get; set; }
[JsonProperty("active")]
public bool Active { get; set; }
}
}
}
| using Newtonsoft.Json;
using System.Collections.Generic;
namespace RepoZ.Api.Common.Git
{
public class RepositoryActionConfiguration
{
[JsonProperty("repository-actions")]
public List<RepositoryAction> RepositoryActions { get; set; } = new List<RepositoryAction>();
[JsonProperty("file-associations")]
public List<FileAssociation> FileAssociations { get; set; } = new List<FileAssociation>();
[System.Diagnostics.DebuggerDisplay("{Name}")]
public class RepositoryAction
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("command")]
public string Command { get; set; }
[JsonProperty("executables")]
public List<string> Executables { get; set; } = new List<string>();
[JsonProperty("arguments")]
public string Arguments { get; set; }
[JsonProperty("keys")]
public string Keys { get; set; }
[JsonProperty("active")]
public bool Active { get; set; }
}
[System.Diagnostics.DebuggerDisplay("{Name}")]
public class FileAssociation
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("extension")]
public string Extension { get; set; }
[JsonProperty("executables")]
public List<string> Executables { get; set; } = new List<string>();
[JsonProperty("arguments")]
public string Arguments { get; set; }
[JsonProperty("active")]
public bool Active { get; set; }
}
}
}
|
Rearrange order of ignoreroutes call | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace NServiceMVC.Examples.Todomvc
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.IgnoreRoute("");
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace NServiceMVC.Examples.Todomvc
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
} |
Remove unused text transform helpers | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Transforms;
namespace osu.Game.Graphics.Sprites
{
public class OsuSpriteText : SpriteText
{
public OsuSpriteText()
{
Shadow = true;
Font = OsuFont.Default;
}
}
public static class OsuSpriteTextTransformExtensions
{
/// <summary>
/// Sets <see cref="SpriteText.Text">Text</see> to a new value after a duration.
/// </summary>
/// <returns>A <see cref="TransformSequence{T}"/> to which further transforms can be added.</returns>
public static TransformSequence<T> TransformTextTo<T>(this T spriteText, string newText, double duration = 0, Easing easing = Easing.None)
where T : OsuSpriteText
=> spriteText.TransformTo(nameof(OsuSpriteText.Text), newText, duration, easing);
/// <summary>
/// Sets <see cref="SpriteText.Text">Text</see> to a new value after a duration.
/// </summary>
/// <returns>A <see cref="TransformSequence{T}"/> to which further transforms can be added.</returns>
public static TransformSequence<T> TransformTextTo<T>(this TransformSequence<T> t, string newText, double duration = 0, Easing easing = Easing.None)
where T : OsuSpriteText
=> t.Append(o => o.TransformTextTo(newText, duration, easing));
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Graphics.Sprites
{
public class OsuSpriteText : SpriteText
{
public OsuSpriteText()
{
Shadow = true;
Font = OsuFont.Default;
}
}
}
|
Fix error when launching missing files | #region
using System.Diagnostics;
using System.IO;
using DesktopWidgets.Classes;
#endregion
namespace DesktopWidgets.Helpers
{
internal static class ProcessHelper
{
public static void Launch(string path, string args = "", string startIn = "",
ProcessWindowStyle style = ProcessWindowStyle.Normal)
{
Launch(new ProcessFile {Path = path, Arguments = args, StartInFolder = startIn, WindowStyle = style});
}
public static void Launch(ProcessFile file)
{
Process.Start(new ProcessStartInfo
{
FileName = file.Path,
Arguments = file.Arguments,
WorkingDirectory = file.StartInFolder,
WindowStyle = file.WindowStyle
});
}
public static void OpenFolder(string path)
{
if (File.Exists(path) || Directory.Exists(path))
Launch("explorer.exe", "/select," + path);
}
}
} | #region
using System.Diagnostics;
using System.IO;
using DesktopWidgets.Classes;
#endregion
namespace DesktopWidgets.Helpers
{
internal static class ProcessHelper
{
public static void Launch(string path, string args = "", string startIn = "",
ProcessWindowStyle style = ProcessWindowStyle.Normal)
{
Launch(new ProcessFile {Path = path, Arguments = args, StartInFolder = startIn, WindowStyle = style});
}
public static void Launch(ProcessFile file)
{
if (string.IsNullOrWhiteSpace(file.Path) || !File.Exists(file.Path))
return;
Process.Start(new ProcessStartInfo
{
FileName = file.Path,
Arguments = file.Arguments,
WorkingDirectory = file.StartInFolder,
WindowStyle = file.WindowStyle
});
}
public static void OpenFolder(string path)
{
if (File.Exists(path) || Directory.Exists(path))
Launch("explorer.exe", "/select," + path);
}
}
} |
Add setter to Proxy property. | #region
using System.Net;
using Tabster.Core.Data.Processing;
using Tabster.Core.Types;
#endregion
namespace Tabster.Core.Searching
{
/// <summary>
/// Tab service which enables searching.
/// </summary>
public interface ISearchService
{
/// <summary>
/// Service name.
/// </summary>
string Name { get; }
/// <summary>
/// Associated parser.
/// </summary>
ITablatureWebpageImporter Parser { get; }
/// <summary>
/// Service flags.
/// </summary>
SearchServiceFlags Flags { get; }
/// <summary>
/// Proxy settings.
/// </summary>
WebProxy Proxy { get; }
/// <summary>
/// Determines whether the service supports ratings.
/// </summary>
bool SupportsRatings { get; }
/// <summary>
/// Queries service and returns results based on search parameters.
/// </summary>
/// <param name="query"> Search query. </param>
SearchResult[] Search(SearchQuery query);
///<summary>
/// Determines whether a specific TabType is supported by the service.
///</summary>
///<param name="type"> The type to check. </param>
///<returns> True if the type is supported by the service; otherwise, False. </returns>
bool SupportsTabType(TabType type);
}
} | #region
using System.Net;
using Tabster.Core.Data.Processing;
using Tabster.Core.Types;
#endregion
namespace Tabster.Core.Searching
{
/// <summary>
/// Tab service which enables searching.
/// </summary>
public interface ISearchService
{
/// <summary>
/// Service name.
/// </summary>
string Name { get; }
/// <summary>
/// Associated parser.
/// </summary>
ITablatureWebpageImporter Parser { get; }
/// <summary>
/// Service flags.
/// </summary>
SearchServiceFlags Flags { get; }
/// <summary>
/// Proxy settings.
/// </summary>
WebProxy Proxy { get; set; }
/// <summary>
/// Determines whether the service supports ratings.
/// </summary>
bool SupportsRatings { get; }
/// <summary>
/// Queries service and returns results based on search parameters.
/// </summary>
/// <param name="query"> Search query. </param>
SearchResult[] Search(SearchQuery query);
///<summary>
/// Determines whether a specific TabType is supported by the service.
///</summary>
///<param name="type"> The type to check. </param>
///<returns> True if the type is supported by the service; otherwise, False. </returns>
bool SupportsTabType(TabType type);
}
} |
Fix test assertion for hostname to ip resolver | using System.Net.Sockets;
using System.Threading.Tasks;
using RapidCore.Network;
using Xunit;
namespace RapidCore.UnitTests.Network
{
public class HostnameToIpResolverTest
{
[Fact]
public async Task HostnameToIpResolver_can_resolveAsync()
{
var resolver = new HostnameToIpResolver();
var ip = await resolver.ResolveToIpv4Async("localhost");
Assert.Equal("127.0.0.1", ip);
}
[Fact]
public async Task HostnameToIpResolve_can_fail()
{
var resolver = new HostnameToIpResolver();
await Assert.ThrowsAsync<SocketException>(async () => await resolver.ResolveToIpv4Async("this-host-is-invalid"));
}
}
}
| using System.Net.Sockets;
using System.Threading.Tasks;
using RapidCore.Network;
using Xunit;
namespace RapidCore.UnitTests.Network
{
public class HostnameToIpResolverTest
{
[Fact]
public async Task HostnameToIpResolver_can_resolveAsync()
{
var resolver = new HostnameToIpResolver();
var ip = await resolver.ResolveToIpv4Async("localhost");
Assert.Equal("127.0.0.1", ip);
}
[Fact]
public async Task HostnameToIpResolve_can_fail()
{
var resolver = new HostnameToIpResolver();
var exception =
await Record.ExceptionAsync(async () => await resolver.ResolveToIpv4Async("this-host-is-invalid"));
Assert.NotNull(exception);
Assert.IsAssignableFrom<SocketException>(exception);
}
}
}
|
Add bundle optimization on release | using System.Web;
using System.Web.Optimization;
namespace Borderlands2GoldendKeys
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryunobt").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/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("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle("~/bundles/site").Include(
"~/Scripts/site.js"));
bundles.Add(new ScriptBundle("~/bundles/ga").Include(
"~/Scripts/ga.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
//"~/Content/bootstrap.css",
"~/Content/bootswatch.slate.min.css",
"~/Content/site.css"));
}
}
}
| using System.Web;
using System.Web.Optimization;
namespace Borderlands2GoldendKeys
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryunobt").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/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("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle("~/bundles/site").Include(
"~/Scripts/site.js"));
bundles.Add(new ScriptBundle("~/bundles/ga").Include(
"~/Scripts/ga.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootswatch.slate.min.css",
"~/Content/site.css"));
#if !DEBUG
BundleTable.EnableOptimizations = true;
#endif
}
}
}
|
Add CanManagePlots on project creation | using System;
namespace JoinRpg.DataModel
{
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global (required by LINQ)
public class ProjectAcl
{
public int ProjectAclId { get; set; }
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public Guid Token { get; set; } = new Guid();
public bool CanChangeFields { get; set; }
public bool CanChangeProjectProperties { get; set; }
public bool IsOwner { get; set; }
public bool CanGrantRights { get; set; }
public bool CanManageClaims { get; set; }
public bool CanEditRoles { get; set; }
public bool CanManageMoney { get; set; }
public bool CanSendMassMails { get; set; }
public bool CanManagePlots { get; set; }
public static ProjectAcl CreateRootAcl(int userId)
{
return new ProjectAcl
{
CanChangeFields = true,
CanChangeProjectProperties = true,
UserId = userId,
IsOwner = true,
CanGrantRights = true,
CanManageClaims = true,
CanEditRoles = true,
CanManageMoney = true,
CanSendMassMails = true
};
}
}
}
| using System;
namespace JoinRpg.DataModel
{
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global (required by LINQ)
public class ProjectAcl
{
public int ProjectAclId { get; set; }
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public Guid Token { get; set; } = new Guid();
public bool CanChangeFields { get; set; }
public bool CanChangeProjectProperties { get; set; }
public bool IsOwner { get; set; }
public bool CanGrantRights { get; set; }
public bool CanManageClaims { get; set; }
public bool CanEditRoles { get; set; }
public bool CanManageMoney { get; set; }
public bool CanSendMassMails { get; set; }
public bool CanManagePlots { get; set; }
public static ProjectAcl CreateRootAcl(int userId)
{
return new ProjectAcl
{
CanChangeFields = true,
CanChangeProjectProperties = true,
UserId = userId,
IsOwner = true,
CanGrantRights = true,
CanManageClaims = true,
CanEditRoles = true,
CanManageMoney = true,
CanSendMassMails = true,
CanManagePlots = true,
};
}
}
}
|
Change raycast provider tests to use PlaymodeTestUtilities instead of TestUtilities | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if !WINDOWS_UWP
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Physics;
using NUnit.Framework;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
namespace Microsoft.MixedReality.Toolkit.Tests.Input
{
class DefaultRaycastProviderTest
{
private DefaultRaycastProvider defaultRaycastProvider;
/// <summary>
/// Validates that when nothing is hit, the default raycast provider doesn't throw an
/// exception and that the MixedRealityRaycastHit is null.
/// </summary>
[UnityTest]
public IEnumerator TestNoHit()
{
// step and layerMasks are set arbitrarily (to something which will not generate a hit).
RayStep step = new RayStep(Vector3.zero, Vector3.up);
LayerMask[] layerMasks = new LayerMask[] { UnityEngine.Physics.DefaultRaycastLayers };
MixedRealityRaycastHit hitInfo;
Assert.IsFalse(defaultRaycastProvider.Raycast(step, layerMasks, out hitInfo));
Assert.IsFalse(hitInfo.raycastValid);
yield return null;
}
[SetUp]
public void SetUp()
{
TestUtilities.InitializeMixedRealityToolkitAndCreateScenes(true);
TestUtilities.InitializePlayspace();
defaultRaycastProvider = new DefaultRaycastProvider(null, null, null);
}
[TearDown]
public void TearDown()
{
TestUtilities.ShutdownMixedRealityToolkit();
}
}
}
#endif | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if !WINDOWS_UWP
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Physics;
using NUnit.Framework;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
namespace Microsoft.MixedReality.Toolkit.Tests.Input
{
class DefaultRaycastProviderTest
{
private DefaultRaycastProvider defaultRaycastProvider;
/// <summary>
/// Validates that when nothing is hit, the default raycast provider doesn't throw an
/// exception and that the MixedRealityRaycastHit is null.
/// </summary>
[UnityTest]
public IEnumerator TestNoHit()
{
// step and layerMasks are set arbitrarily (to something which will not generate a hit).
RayStep step = new RayStep(Vector3.zero, Vector3.up);
LayerMask[] layerMasks = new LayerMask[] { UnityEngine.Physics.DefaultRaycastLayers };
MixedRealityRaycastHit hitInfo;
Assert.IsFalse(defaultRaycastProvider.Raycast(step, layerMasks, out hitInfo));
Assert.IsFalse(hitInfo.raycastValid);
yield return null;
}
[SetUp]
public void SetUp()
{
PlayModeTestUtilities.Setup();
defaultRaycastProvider = new DefaultRaycastProvider(null, null, null);
}
[TearDown]
public void TearDown()
{
PlayModeTestUtilities.TearDown();
}
}
}
#endif |
Fix build error after merge | using System;
using System.Collections.Generic;
using NSaga;
namespace Benchmarking
{
/// <summary>
/// Saga repository only for benchmarking.
/// Does not really store anything
/// </summary>
internal class FastSagaRepository : ISagaRepository
{
private readonly ISagaFactory sagaFactory;
public FastSagaRepository(ISagaFactory sagaFactory)
{
this.sagaFactory = sagaFactory;
}
public TSaga Find<TSaga>(Guid correlationId) where TSaga : class
{
if (correlationId == Program.FirstGuid)
{
return null;
}
var saga = sagaFactory.Resolve<TSaga>();
Reflection.Set(saga, "CorrelationId", correlationId);
return saga;
}
public void Save<TSaga>(TSaga saga) where TSaga : class
{
// nothing
}
public void Complete<TSaga>(TSaga saga) where TSaga : class
{
// nothing
}
public void Complete(Guid correlationId)
{
// nothing
}
}
}
| using System;
using System.Collections.Generic;
using NSaga;
namespace Benchmarking
{
/// <summary>
/// Saga repository only for benchmarking.
/// Does not really store anything
/// </summary>
internal class FastSagaRepository : ISagaRepository
{
private readonly ISagaFactory sagaFactory;
public FastSagaRepository(ISagaFactory sagaFactory)
{
this.sagaFactory = sagaFactory;
}
public TSaga Find<TSaga>(Guid correlationId) where TSaga : class, IAccessibleSaga
{
if (correlationId == Program.FirstGuid)
{
return null;
}
var saga = sagaFactory.ResolveSaga<TSaga>();
Reflection.Set(saga, "CorrelationId", correlationId);
return saga;
}
public void Save<TSaga>(TSaga saga) where TSaga : class, IAccessibleSaga
{
// nothing
}
public void Complete<TSaga>(TSaga saga) where TSaga : class, IAccessibleSaga
{
// nothing
}
public void Complete(Guid correlationId)
{
// nothing
}
}
}
|
Add action "Show Error" option | using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Actions
{
public abstract class ActionBase
{
[DisplayName("Delay")]
public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);
public void Execute()
{
DelayedAction.RunAction((int) Delay.TotalMilliseconds, () =>
{
try
{
ExecuteAction();
}
catch (Exception ex)
{
Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}", image: MessageBoxImage.Error);
}
});
}
public virtual void ExecuteAction()
{
}
}
} | using System;
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Actions
{
public abstract class ActionBase
{
[DisplayName("Delay")]
public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0);
[DisplayName("Show Errors")]
public bool ShowErrors { get; set; } = false;
public void Execute()
{
DelayedAction.RunAction((int) Delay.TotalMilliseconds, () =>
{
try
{
ExecuteAction();
}
catch (Exception ex)
{
if (ShowErrors)
Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}",
image: MessageBoxImage.Error);
}
});
}
public virtual void ExecuteAction()
{
}
}
} |
Clean up some use of Approval tests. | using ApprovalTests.Reporters;
using Gibberish.AST._1_Bare;
using Gibberish.Parsing;
using Gibberish.Tests.ZzTestHelpers;
using NUnit.Framework;
namespace Gibberish.Tests.RecognizeBlockSyntax
{
[TestFixture]
public class InterpretWholeFile
{
[Test, UseReporter(typeof(QuietReporter))]
public void should_accept_multiple_language_constructs()
{
var subject = new RecognizeBlocks();
var input = @"
using language fasm
define.thunk some.name:
pass
define.thunk other.name:
pass
";
var result = subject.GetMatch(input, subject.WholeFile);
//ApprovalTests.Approvals.VerifyJson(result.PrettyPrint());
result.Should()
.BeRecognizedAs(
BasicAst.Statement("using language fasm"),
BasicAst.Block("define.thunk some.name")
.WithBody(b => b.AddStatement("pass")),
BasicAst.Block("define.thunk other.name")
.WithBody(b => b.AddStatement("pass")));
}
}
}
| using ApprovalTests.Reporters;
using Gibberish.AST._1_Bare;
using Gibberish.Parsing;
using Gibberish.Tests.ZzTestHelpers;
using NUnit.Framework;
namespace Gibberish.Tests.RecognizeBlockSyntax
{
[TestFixture]
public class InterpretWholeFile
{
[Test]
public void should_accept_multiple_language_constructs()
{
var subject = new RecognizeBlocks();
var input = @"
using language fasm
define.thunk some.name:
pass
define.thunk other.name:
pass
";
var result = subject.GetMatch(input, subject.WholeFile);
result.Should()
.BeRecognizedAs(
BasicAst.Statement("using language fasm"),
BasicAst.Block("define.thunk some.name")
.WithBody(b => b.AddStatement("pass")),
BasicAst.Block("define.thunk other.name")
.WithBody(b => b.AddStatement("pass")));
}
}
}
|
Add CommandDate so it is deserialized from the JSON response | namespace MultiMiner.MobileMiner.Api
{
public class RemoteCommand
{
public int Id { get; set; }
public string CommandText { get; set; }
}
}
| using System;
namespace MultiMiner.MobileMiner.Api
{
public class RemoteCommand
{
public int Id { get; set; }
public string CommandText { get; set; }
public DateTime CommandDate { get; set; }
}
}
|
Test discovery skips over abstract base classes. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace PCLTesting.Infrastructure
{
public class TestDiscoverer
{
public IEnumerable<Test> DiscoverTests(Assembly assembly)
{
List<Test> ret = new List<Test>();
foreach (Type type in assembly.GetExportedTypes())
{
ret.AddRange(DiscoverTests(type));
}
return ret;
}
public IEnumerable<Test> DiscoverTests(Type type)
{
List<Test> ret = new List<Test>();
foreach (MethodInfo method in type.GetMethods())
{
if (method.GetCustomAttributes(false).Any(
attr => attr.GetType().Name == "TestMethodAttribute"))
{
var test = new Test(method);
ret.Add(test);
}
}
return ret;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace PCLTesting.Infrastructure
{
public class TestDiscoverer
{
public IEnumerable<Test> DiscoverTests(Assembly assembly)
{
List<Test> ret = new List<Test>();
foreach (Type type in assembly.GetExportedTypes().Where(t => !t.IsAbstract))
{
ret.AddRange(DiscoverTests(type));
}
return ret;
}
public IEnumerable<Test> DiscoverTests(Type type)
{
List<Test> ret = new List<Test>();
foreach (MethodInfo method in type.GetMethods())
{
if (method.GetCustomAttributes(false).Any(
attr => attr.GetType().Name == "TestMethodAttribute"))
{
var test = new Test(method);
ret.Add(test);
}
}
return ret;
}
}
}
|
Remove unused code from quick-start guide example project. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;
// static LearnositySDK.Credentials;
namespace LearnosityDemo.Pages
{
public class ItemsAPIDemoModel : PageModel
{
public void OnGet()
{
// prepare all the params
string service = "items";
JsonObject security = new JsonObject();
security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
security.set("domain", LearnositySDK.Credentials.Domain);
security.set("user_id", Uuid.generate());
string secret = LearnositySDK.Credentials.ConsumerSecret;
JsonObject config = new JsonObject();
JsonObject request = new JsonObject();
request.set("user_id", Uuid.generate());
request.set("activity_template_id", "quickstart_examples_activity_template_001");
request.set("session_id", Uuid.generate());
request.set("activity_id", "quickstart_examples_activity_001");
request.set("rendering_type", "assess");
request.set("type", "submit_practice");
request.set("name", "Items API Quickstart");
request.set("config", config);
// Instantiate Init class
Init init = new Init(service, security, secret, request);
// Call the generate() method to retrieve a JavaScript object
ViewData["InitJSON"] = init.generate();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnositySDK.Request;
using LearnositySDK.Utils;
// static LearnositySDK.Credentials;
namespace LearnosityDemo.Pages
{
public class ItemsAPIDemoModel : PageModel
{
public void OnGet()
{
// prepare all the params
string service = "items";
JsonObject security = new JsonObject();
security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey);
security.set("domain", LearnositySDK.Credentials.Domain);
security.set("user_id", Uuid.generate());
string secret = LearnositySDK.Credentials.ConsumerSecret;
//JsonObject config = new JsonObject();
JsonObject request = new JsonObject();
request.set("user_id", Uuid.generate());
request.set("activity_template_id", "quickstart_examples_activity_template_001");
request.set("session_id", Uuid.generate());
request.set("activity_id", "quickstart_examples_activity_001");
request.set("rendering_type", "assess");
request.set("type", "submit_practice");
request.set("name", "Items API Quickstart");
//request.set("config", config);
// Instantiate Init class
Init init = new Init(service, security, secret, request);
// Call the generate() method to retrieve a JavaScript object
ViewData["InitJSON"] = init.generate();
}
}
}
|
Fix memory patterns saving when not playing. | using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfaces;
namespace osu_StreamCompanion.Code.Modules.MapDataGetters.FileMap
{
public class FileMapDataGetter : IModule, IMapDataGetter
{
public bool Started { get; set; }
private readonly FileMapManager _fileMapManager = new FileMapManager();
public void Start(ILogger logger)
{
Started = true;
}
public void SetNewMap(MapSearchResult map)
{
foreach (var s in map.FormatedStrings)
{
var name = s.Name;
if ((s.SaveEvent & map.Action) != 0)
_fileMapManager.Write("SC-" + name, s.GetFormatedPattern());
else
_fileMapManager.Write("SC-" + name, " ");//spaces so object rect displays on obs preview window.
}
}
}
} | using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfaces;
namespace osu_StreamCompanion.Code.Modules.MapDataGetters.FileMap
{
public class FileMapDataGetter : IModule, IMapDataGetter
{
public bool Started { get; set; }
private readonly FileMapManager _fileMapManager = new FileMapManager();
public void Start(ILogger logger)
{
Started = true;
}
public void SetNewMap(MapSearchResult map)
{
foreach (var s in map.FormatedStrings)
{
if(s.IsMemoryFormat) continue;//memory pattern saving is handled elsewhere, not in this codebase.
var name = s.Name;
if ((s.SaveEvent & map.Action) != 0)
_fileMapManager.Write("SC-" + name, s.GetFormatedPattern());
else
_fileMapManager.Write("SC-" + name, " ");//spaces so object rect displays on obs preview window.
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.