Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Make way for the extended information which can be requested using the Show Droplet request. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalOcean.Structs
{
public class Droplet
{
public int id { get; set; }
public string name { get; set; }
public int image_id { get; set; }
public int size_id { get; set; }
public int region_id { get; set; }
public bool backups_active { get; set; }
public string ip_address { get; set; }
public object private_ip_address { get; set; }
public bool locked { get; set; }
public string status { get; set; }
public string created_at { get; set; }
}
public class Droplets
{
public string status { get; set; }
public List<Droplet> droplets { get; set; }
}
}
| using System.Collections.Generic;
namespace DigitalOcean.Structs
{
public class Droplet
{
public int id { get; set; }
public int image_id { get; set; }
public string name { get; set; }
public int region_id { get; set; }
public int size_id { get; set; }
public bool backups_active { get; set; }
public List<object> backups { get; set; } //extended
public List<object> snapshots { get; set; } //extended
public string ip_address { get; set; }
public object private_ip_address { get; set; }
public bool locked { get; set; }
public string status { get; set; }
public string created_at { get; set; }
}
public class Droplets
{
public string status { get; set; }
public List<Droplet> droplets { get; set; }
}
} |
Use Uri's for subdocument file and photos | using MyDocs.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Logic = MyDocs.Common.Model.Logic;
namespace JsonNetDal
{
public class SubDocument
{
public string Title { get; set; }
public string File { get; set; }
public List<string> Photos { get; set; }
public SubDocument() { }
public SubDocument(string title, string file, IEnumerable<string> photos)
{
Title = title;
File = file;
Photos = photos.ToList();
}
public static SubDocument FromLogic(Logic.SubDocument subDocument)
{
return new SubDocument(subDocument.Title, subDocument.File.GetUri().AbsoluteUri, subDocument.Photos.Select(p => p.File.GetUri().AbsoluteUri));
}
public async Task<Logic.SubDocument> ToLogic()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(File));
var photoTasks =
Photos
.Select(p => new Uri(p))
.Select(StorageFile.GetFileFromApplicationUriAsync)
.Select(x => x.AsTask());
var photos = await Task.WhenAll(photoTasks);
return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p)));
}
}
}
| using MyDocs.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Logic = MyDocs.Common.Model.Logic;
namespace JsonNetDal
{
public class SubDocument
{
public string Title { get; set; }
public Uri File { get; set; }
public List<Uri> Photos { get; set; }
public SubDocument() { }
public SubDocument(string title, Uri file, IEnumerable<Uri> photos)
{
Title = title;
File = file;
Photos = photos.ToList();
}
public static SubDocument FromLogic(Logic.SubDocument subDocument)
{
return new SubDocument(subDocument.Title, subDocument.File.GetUri(), subDocument.Photos.Select(p => p.File.GetUri()));
}
public async Task<Logic.SubDocument> ToLogic()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(File);
var photoTasks =
Photos
.Select(StorageFile.GetFileFromApplicationUriAsync)
.Select(x => x.AsTask());
var photos = await Task.WhenAll(photoTasks);
return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p)));
}
}
}
|
Fix major bug when getting event handlers | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading.Tasks;
namespace Cronus.Core.Eventing
{
/// <summary>
/// Represents an in memory event messaging destribution
/// </summary>
public class InMemoryEventBus : AbstractEventBus
{
/// <summary>
/// Publishes the given event to all registered event handlers
/// </summary>
/// <param name="event">An event instance</param>
public override bool Publish(IEvent @event)
{
onPublishEvent(@event);
foreach (var handleMethod in handlers[@event.GetType()])
{
var result = handleMethod(@event);
if (result == false)
return result;
}
onEventPublished(@event);
return true;
}
public override Task<bool> PublishAsync(IEvent @event)
{
return Threading.RunAsync(() => Publish(@event));
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Cronus.Core.Eventing
{
/// <summary>
/// Represents an in memory event messaging destribution
/// </summary>
public class InMemoryEventBus : AbstractEventBus
{
/// <summary>
/// Publishes the given event to all registered event handlers
/// </summary>
/// <param name="event">An event instance</param>
public override bool Publish(IEvent @event)
{
onPublishEvent(@event);
List<Func<IEvent, bool>> eventHandlers;
if (handlers.TryGetValue(@event.GetType(), out eventHandlers))
{
foreach (var handleMethod in eventHandlers)
{
var result = handleMethod(@event);
if (result == false)
return result;
}
}
onEventPublished(@event);
return true;
}
public override Task<bool> PublishAsync(IEvent @event)
{
return Threading.RunAsync(() => Publish(@event));
}
}
} |
Print hello world for k10 project. | #if NET45
using System;
using Microsoft.Owin.Hosting;
namespace MvcSample
{
public class Program
{
const string baseUrl = "http://localhost:9001/";
public static void Main()
{
using (WebApp.Start<Startup>(new StartOptions(baseUrl)))
{
Console.WriteLine("Listening at {0}", baseUrl);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}
}
#endif | using System;
#if NET45
using Microsoft.Owin.Hosting;
#endif
namespace MvcSample
{
public class Program
{
const string baseUrl = "http://localhost:9001/";
public static void Main()
{
#if NET45
using (WebApp.Start<Startup>(new StartOptions(baseUrl)))
{
Console.WriteLine("Listening at {0}", baseUrl);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
#else
Console.WriteLine("Hello World");
#endif
}
}
} |
Add classes for prime numbers | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.WebJobs;
namespace TaskWebJob
{
// To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976
class Program
{
// Please set the following connection strings in app.config for this WebJob to run:
// AzureWebJobsDashboard and AzureWebJobsStorage
static void Main()
{
using (var host = new JobHost())
{
host.Call(typeof(Functions).GetMethod(nameof(Functions.RecordTimeAndSleep)), new { startTime = DateTime.UtcNow });
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.WebJobs;
namespace TaskWebJob
{
// To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976
class Program
{
// Please set the following connection strings in app.config for this WebJob to run:
// AzureWebJobsDashboard and AzureWebJobsStorage
static void Main()
{
using (var host = new JobHost())
{
host.Call(typeof(Functions).GetMethod(nameof(Functions.RecordTimeAndSleep)), new { startTime = DateTime.UtcNow });
}
}
}
public static class PrimeNumbers
{
public static IEnumerable<long> GetPrimeNumbers(long minValue, long maxValue) =>
new[]
{
new
{
primes = new List<long>(),
min = Math.Max(minValue, 2),
max = Math.Max(maxValue, 0),
root_max = maxValue >= 0 ? (long)Math.Sqrt(maxValue) : 0,
}
}
.SelectMany(_ => Enumerable2.Range2(2, Math.Min(_.root_max, _.min - 1))
.Concat(Enumerable2.Range2(_.min, _.max))
.Select(i => new { _.primes, i, root_i = (long)Math.Sqrt(i) }))
.Where(_ => _.primes
.TakeWhile(p => p <= _.root_i)
.All(p => _.i % p != 0))
.Do(_ => _.primes.Add(_.i))
.Select(_ => _.i)
.SkipWhile(i => i < minValue);
}
public static class Enumerable2
{
public static IEnumerable<long> Range2(long minValue, long maxValue)
{
for (var i = minValue; i <= maxValue; i++)
{
yield return i;
}
}
public static IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (var item in source)
{
action(item);
yield return item;
}
}
}
}
|
Add resets when reloading level | /*
----------------------------------------------------------------------
Numenta Platform for Intelligent Computing (NuPIC)
Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
with Numenta, Inc., for a separate license for this software code, the
following terms and conditions apply:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses.
http://numenta.org/licenses/
----------------------------------------------------------------------
*/
using UnityEngine;
using System.Collections;
public class CarCollisions : MonoBehaviour {
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "Boundary") {
Application.LoadLevel(Application.loadedLevel);
}
else if (collision.gameObject.tag == "Finish") {
Application.LoadLevel(Application.loadedLevel + 1);
}
}
}
| /*
----------------------------------------------------------------------
Numenta Platform for Intelligent Computing (NuPIC)
Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
with Numenta, Inc., for a separate license for this software code, the
following terms and conditions apply:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses.
http://numenta.org/licenses/
----------------------------------------------------------------------
*/
using UnityEngine;
using System.Collections;
public class CarCollisions : MonoBehaviour {
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "Boundary") {
API.instance.Reset();
Application.LoadLevel(Application.loadedLevel);
}
else if (collision.gameObject.tag == "Finish") {
API.instance.Reset();
Application.LoadLevel(Application.loadedLevel + 1);
}
}
}
|
Fix huge bug related to instantiation of tolerance | using NBi.Core.ResultSet;
using System;
using System.Globalization;
using System.Linq;
namespace NBi.Core.Scalar.Comparer
{
public class ToleranceFactory
{
public static Tolerance Instantiate(IColumnDefinition columnDefinition)
{
if (columnDefinition.Role != ColumnRole.Value)
throw new ArgumentException("The ColumnDefinition must have have a role defined as 'Value' and is defined as 'Key'", "columnDefinition");
return Instantiate(columnDefinition.Type, columnDefinition.Tolerance);
}
public static Tolerance Instantiate(ColumnType type, string value)
{
if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
return null;
Tolerance tolerance=null;
switch (type)
{
case ColumnType.Text:
tolerance = new TextToleranceFactory().Instantiate(value);
break;
case ColumnType.Numeric:
tolerance = new NumericToleranceFactory().Instantiate(value);
break;
case ColumnType.DateTime:
tolerance = new DateTimeToleranceFactory().Instantiate(value);
break;
case ColumnType.Boolean:
break;
default:
break;
}
return tolerance;
}
public static Tolerance None(ColumnType type)
{
Tolerance tolerance = null;
switch (type)
{
case ColumnType.Text:
tolerance = TextSingleMethodTolerance.None;
break;
case ColumnType.Numeric:
tolerance = NumericAbsoluteTolerance.None;
break;
case ColumnType.DateTime:
tolerance = DateTimeTolerance.None;
break;
case ColumnType.Boolean:
break;
default:
break;
}
return tolerance;
}
}
}
| using NBi.Core.ResultSet;
using System;
using System.Globalization;
using System.Linq;
namespace NBi.Core.Scalar.Comparer
{
public class ToleranceFactory
{
public static Tolerance Instantiate(IColumnDefinition columnDefinition)
{
if (string.IsNullOrEmpty(columnDefinition.Tolerance) || string.IsNullOrWhiteSpace(columnDefinition.Tolerance))
return null;
if (columnDefinition.Role != ColumnRole.Value)
throw new ArgumentException("The ColumnDefinition must have have a role defined as 'Value' and is defined as 'Key'", "columnDefinition");
return Instantiate(columnDefinition.Type, columnDefinition.Tolerance);
}
public static Tolerance Instantiate(ColumnType type, string value)
{
Tolerance tolerance=null;
switch (type)
{
case ColumnType.Text:
tolerance = new TextToleranceFactory().Instantiate(value);
break;
case ColumnType.Numeric:
tolerance = new NumericToleranceFactory().Instantiate(value);
break;
case ColumnType.DateTime:
tolerance = new DateTimeToleranceFactory().Instantiate(value);
break;
case ColumnType.Boolean:
break;
default:
break;
}
return tolerance;
}
public static Tolerance None(ColumnType type)
{
Tolerance tolerance = null;
switch (type)
{
case ColumnType.Text:
tolerance = TextSingleMethodTolerance.None;
break;
case ColumnType.Numeric:
tolerance = NumericAbsoluteTolerance.None;
break;
case ColumnType.DateTime:
tolerance = DateTimeTolerance.None;
break;
case ColumnType.Boolean:
break;
default:
break;
}
return tolerance;
}
}
}
|
Fix Actipro language to construct the correct set of language services | using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using ActiproSoftware.Text.Implementation;
using NQuery.Language.Services.BraceMatching;
namespace NQuery.Language.ActiproWpf
{
public sealed class NQueryLanguage : SyntaxLanguage, IDisposable
{
private readonly CompositionContainer _compositionContainer;
public NQueryLanguage()
: this(GetDefaultCatalog())
{
}
public NQueryLanguage(ComposablePartCatalog catalog)
: base("NQuery")
{
_compositionContainer = new CompositionContainer(catalog);
_compositionContainer.SatisfyImportsOnce(this);
var serviceProviders = _compositionContainer.GetExportedValues<ILanguageServiceRegistrar>();
foreach (var serviceProvider in serviceProviders)
serviceProvider.RegisterServices(this);
}
private static ComposablePartCatalog GetDefaultCatalog()
{
var servicesAssembly = new AssemblyCatalog(typeof (IBraceMatchingService).Assembly);
var thisAssembly = new AssemblyCatalog(typeof (NQueryLanguage).Assembly);
return new AggregateCatalog(servicesAssembly, thisAssembly);
}
public void Dispose()
{
_compositionContainer.Dispose();
}
}
} | using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using ActiproSoftware.Text.Implementation;
using NQuery.Language.Services.BraceMatching;
using NQuery.Language.Wpf;
namespace NQuery.Language.ActiproWpf
{
public sealed class NQueryLanguage : SyntaxLanguage, IDisposable
{
private readonly CompositionContainer _compositionContainer;
public NQueryLanguage()
: this(GetDefaultCatalog())
{
}
public NQueryLanguage(ComposablePartCatalog catalog)
: base("NQuery")
{
_compositionContainer = new CompositionContainer(catalog);
_compositionContainer.SatisfyImportsOnce(this);
var serviceProviders = _compositionContainer.GetExportedValues<ILanguageServiceRegistrar>();
foreach (var serviceProvider in serviceProviders)
serviceProvider.RegisterServices(this);
}
private static ComposablePartCatalog GetDefaultCatalog()
{
var servicesAssembly = new AssemblyCatalog(typeof (IBraceMatchingService).Assembly);
var wpfAssembly = new AssemblyCatalog(typeof(INQueryGlyphService).Assembly);
var thisAssembly = new AssemblyCatalog(typeof (NQueryLanguage).Assembly);
return new AggregateCatalog(servicesAssembly, wpfAssembly, thisAssembly);
}
public void Dispose()
{
_compositionContainer.Dispose();
}
}
} |
Make settings textboxes commit on focus lost | // 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.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OsuTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
};
}
}
| // 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.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OsuTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
CommitOnFocusLost = true,
};
}
}
|
Simplify the .pro file names | // <copyright file="QtCreatorBuilder.cs" company="Mark Final">
// Opus package
// </copyright>
// <summary>QtCreator package</summary>
// <author>Mark Final</author>
[assembly: Opus.Core.DeclareBuilder("QtCreator", typeof(QtCreatorBuilder.QtCreatorBuilder))]
// Automatically generated by Opus v0.20
namespace QtCreatorBuilder
{
public sealed partial class QtCreatorBuilder : Opus.Core.IBuilder
{
public static string GetProFilePath(Opus.Core.DependencyNode node)
{
//string proFileDirectory = System.IO.Path.Combine(node.GetModuleBuildDirectory(), "QMake");
string proFileDirectory = node.GetModuleBuildDirectory();
string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}_{1}.pro", node.UniqueModuleName, node.Target));
Opus.Core.Log.MessageAll("ProFile : '{0}'", proFilePath);
return proFilePath;
}
public static string GetQtConfiguration(Opus.Core.Target target)
{
if (target.Configuration != Opus.Core.EConfiguration.Debug && target.Configuration != Opus.Core.EConfiguration.Optimized)
{
throw new Opus.Core.Exception("QtCreator only supports debug and optimized configurations");
}
string QtCreatorConfiguration = (target.Configuration == Opus.Core.EConfiguration.Debug) ? "debug" : "release";
return QtCreatorConfiguration;
}
}
}
| // <copyright file="QtCreatorBuilder.cs" company="Mark Final">
// Opus package
// </copyright>
// <summary>QtCreator package</summary>
// <author>Mark Final</author>
[assembly: Opus.Core.DeclareBuilder("QtCreator", typeof(QtCreatorBuilder.QtCreatorBuilder))]
// Automatically generated by Opus v0.20
namespace QtCreatorBuilder
{
public sealed partial class QtCreatorBuilder : Opus.Core.IBuilder
{
public static string GetProFilePath(Opus.Core.DependencyNode node)
{
//string proFileDirectory = System.IO.Path.Combine(node.GetModuleBuildDirectory(), "QMake");
string proFileDirectory = node.GetModuleBuildDirectory();
//string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}_{1}.pro", node.UniqueModuleName, node.Target));
string proFilePath = System.IO.Path.Combine(proFileDirectory, System.String.Format("{0}.pro", node.ModuleName));
Opus.Core.Log.MessageAll("ProFile : '{0}'", proFilePath);
return proFilePath;
}
public static string GetQtConfiguration(Opus.Core.Target target)
{
if (target.Configuration != Opus.Core.EConfiguration.Debug && target.Configuration != Opus.Core.EConfiguration.Optimized)
{
throw new Opus.Core.Exception("QtCreator only supports debug and optimized configurations");
}
string QtCreatorConfiguration = (target.Configuration == Opus.Core.EConfiguration.Debug) ? "debug" : "release";
return QtCreatorConfiguration;
}
}
}
|
Add instanceperrequest lifetime scope to all services | using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Zk.Models;
using Zk.Services;
using Zk.Repositories;
namespace Zk
{
public static class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<ZkContext>()
.As<IZkContext>()
.InstancePerRequest();
builder.RegisterType<Repository>();
builder.RegisterType<AuthenticationService>();
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Anonymous);
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Authenticated);
builder.RegisterType<PasswordRecoveryService>();
builder.RegisterType<CalendarService>();
builder.RegisterType<FarmingActionService>();
builder.RegisterType<CropProvider>();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
} | using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Zk.Models;
using Zk.Services;
using Zk.Repositories;
namespace Zk
{
public static class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<ZkContext>()
.As<IZkContext>()
.InstancePerRequest();
builder.RegisterType<Repository>()
.InstancePerRequest();
builder.RegisterType<AuthenticationService>()
.InstancePerRequest();
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Anonymous);
builder.RegisterType<UserService>()
.Keyed<IUserService>(AuthenticatedStatus.Authenticated);
builder.RegisterType<PasswordRecoveryService>()
.InstancePerRequest();
builder.RegisterType<CalendarService>()
.InstancePerRequest();
builder.RegisterType<FarmingActionService>()
.InstancePerRequest();
builder.RegisterType<CropProvider>()
.InstancePerRequest();;
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
} |
Fix incorrect assumption that a workspace is a Visual Studio workspace | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
[ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared]
internal class ProjectTypeLookupService : IProjectTypeLookupService
{
public string GetProjectType(Workspace workspace, ProjectId projectId)
{
if (workspace == null || projectId == null)
{
return string.Empty;
}
var vsWorkspace = workspace as VisualStudioWorkspace;
var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject;
if (aggregatableProject == null)
{
return string.Empty;
}
if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType)))
{
return projectType;
}
return projectType ?? string.Empty;
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
[ExportWorkspaceService(typeof(IProjectTypeLookupService), ServiceLayer.Host), Shared]
internal class ProjectTypeLookupService : IProjectTypeLookupService
{
public string GetProjectType(Workspace workspace, ProjectId projectId)
{
if (!(workspace is VisualStudioWorkspace vsWorkspace) || projectId == null)
{
return string.Empty;
}
var aggregatableProject = vsWorkspace.GetHierarchy(projectId) as IVsAggregatableProject;
if (aggregatableProject == null)
{
return string.Empty;
}
if (ErrorHandler.Succeeded(aggregatableProject.GetAggregateProjectTypeGuids(out var projectType)))
{
return projectType;
}
return projectType ?? string.Empty;
}
}
}
|
Fix for U4-10821, render alt text attribute from grid image editor, or empty string if null (for screen readers) | @model dynamic
@using Umbraco.Web.Templates
@if (Model.value != null)
{
var url = Model.value.image;
if(Model.editor.config != null && Model.editor.config.size != null){
url += "?width=" + Model.editor.config.size.width;
url += "&height=" + Model.editor.config.size.height;
if(Model.value.focalPoint != null){
url += "¢er=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left;
url += "&mode=crop";
}
}
<img src="@url" alt="@Model.value.caption">
if (Model.value.caption != null)
{
<p class="caption">@Model.value.caption</p>
}
}
| @model dynamic
@using Umbraco.Web.Templates
@if (Model.value != null)
{
var url = Model.value.image;
if(Model.editor.config != null && Model.editor.config.size != null){
url += "?width=" + Model.editor.config.size.width;
url += "&height=" + Model.editor.config.size.height;
if(Model.value.focalPoint != null){
url += "¢er=" + Model.value.focalPoint.top +"," + Model.value.focalPoint.left;
url += "&mode=crop";
}
}
var altText = Model.value.altText ?? String.Empty;
<img src="@url" alt="@altText">
if (Model.value.caption != null)
{
<p class="caption">@Model.value.caption</p>
}
}
|
Handle content pages as well | using System;
using Sancho.DOM.XamarinForms;
using Sancho.XAMLParser;
using TabletDesigner.Helpers;
using Xamarin.Forms;
namespace TabletDesigner
{
public interface ILogAccess
{
void Clear();
string Log { get; }
}
public partial class TabletDesignerPage : ContentPage
{
ILogAccess logAccess;
public TabletDesignerPage()
{
InitializeComponent();
logAccess = DependencyService.Get<ILogAccess>();
}
protected override void OnAppearing()
{
base.OnAppearing();
editor.Text = Settings.Xaml;
}
void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
{
try
{
Settings.Xaml = editor.Text;
logAccess.Clear();
var parser = new Parser();
var rootNode = parser.Parse(e.NewTextValue);
rootNode = new ContentNodeProcessor().Process(rootNode);
rootNode = new ExpandedPropertiesProcessor().Process(rootNode);
var view = new XamlDOMCreator().CreateNode(rootNode) as View;
Root.Content = view;
LoggerOutput.Text = logAccess.Log;
LoggerOutput.TextColor = Color.White;
}
catch (Exception ex)
{
LoggerOutput.Text = ex.ToString();
LoggerOutput.TextColor = Color.FromHex("#FF3030");
}
}
}
}
| using System;
using Sancho.DOM.XamarinForms;
using Sancho.XAMLParser;
using TabletDesigner.Helpers;
using Xamarin.Forms;
namespace TabletDesigner
{
public interface ILogAccess
{
void Clear();
string Log { get; }
}
public partial class TabletDesignerPage : ContentPage
{
ILogAccess logAccess;
public TabletDesignerPage()
{
InitializeComponent();
logAccess = DependencyService.Get<ILogAccess>();
}
protected override void OnAppearing()
{
base.OnAppearing();
editor.Text = Settings.Xaml;
}
void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
{
try
{
Settings.Xaml = editor.Text;
logAccess.Clear();
var parser = new Parser();
var rootNode = parser.Parse(e.NewTextValue);
rootNode = new ContentNodeProcessor().Process(rootNode);
rootNode = new ExpandedPropertiesProcessor().Process(rootNode);
var dom = new XamlDOMCreator().CreateNode(rootNode);
if (dom is View)
Root.Content = (View)dom;
else if (dom is ContentPage)
Root.Content = ((ContentPage)dom).Content;
LoggerOutput.Text = logAccess.Log;
LoggerOutput.TextColor = Color.White;
}
catch (Exception ex)
{
LoggerOutput.Text = ex.ToString();
LoggerOutput.TextColor = Color.FromHex("#FF3030");
}
}
}
}
|
Fix hoisting of null initializers | using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.NRefactory.CSharp;
namespace JSIL {
public class DeclarationHoister : ContextTrackingVisitor<object> {
public readonly BlockStatement Output;
public VariableDeclarationStatement Statement = null;
public readonly HashSet<string> HoistedNames = new HashSet<string>();
public DeclarationHoister (DecompilerContext context, BlockStatement output)
: base(context) {
Output = output;
}
public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) {
if (Statement == null) {
Statement = new VariableDeclarationStatement();
Output.Add(Statement);
}
foreach (var variable in variableDeclarationStatement.Variables) {
if (!HoistedNames.Contains(variable.Name)) {
Statement.Variables.Add(new VariableInitializer(
variable.Name
));
HoistedNames.Add(variable.Name);
}
}
var replacement = new BlockStatement();
foreach (var variable in variableDeclarationStatement.Variables) {
replacement.Add(new ExpressionStatement(new AssignmentExpression {
Left = new IdentifierExpression(variable.Name),
Right = variable.Initializer.Clone()
}));
}
if (replacement.Statements.Count == 1) {
var firstChild = replacement.FirstChild;
firstChild.Remove();
variableDeclarationStatement.ReplaceWith(firstChild);
} else if (replacement.Statements.Count > 1) {
variableDeclarationStatement.ReplaceWith(replacement);
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.NRefactory.CSharp;
namespace JSIL {
public class DeclarationHoister : ContextTrackingVisitor<object> {
public readonly BlockStatement Output;
public VariableDeclarationStatement Statement = null;
public readonly HashSet<string> HoistedNames = new HashSet<string>();
public DeclarationHoister (DecompilerContext context, BlockStatement output)
: base(context) {
Output = output;
}
public override object VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, object data) {
if (Statement == null) {
Statement = new VariableDeclarationStatement();
Output.Add(Statement);
}
foreach (var variable in variableDeclarationStatement.Variables) {
if (!HoistedNames.Contains(variable.Name)) {
Statement.Variables.Add(new VariableInitializer(
variable.Name
));
HoistedNames.Add(variable.Name);
}
}
var replacement = new BlockStatement();
foreach (var variable in variableDeclarationStatement.Variables) {
if (variable.IsNull)
continue;
if (variable.Initializer.IsNull)
continue;
replacement.Add(new ExpressionStatement(new AssignmentExpression {
Left = new IdentifierExpression(variable.Name),
Right = variable.Initializer.Clone()
}));
}
if (replacement.Statements.Count == 1) {
var firstChild = replacement.FirstChild;
firstChild.Remove();
variableDeclarationStatement.ReplaceWith(firstChild);
} else if (replacement.Statements.Count > 1) {
variableDeclarationStatement.ReplaceWith(replacement);
} else {
variableDeclarationStatement.Remove();
}
return null;
}
}
}
|
Fix codepath where the property is a value type but the weakreference has been collected. | using Avalonia.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avalonia.Data.Core
{
internal abstract class SettableNode : ExpressionNode
{
public bool SetTargetValue(object value, BindingPriority priority)
{
if (ShouldNotSet(value))
{
return true;
}
return SetTargetValueCore(value, priority);
}
private bool ShouldNotSet(object value)
{
if (PropertyType == null)
{
return false;
}
if (PropertyType.IsValueType)
{
return LastValue?.Target.Equals(value) ?? false;
}
return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value);
}
protected abstract bool SetTargetValueCore(object value, BindingPriority priority);
public abstract Type PropertyType { get; }
}
}
| using Avalonia.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avalonia.Data.Core
{
internal abstract class SettableNode : ExpressionNode
{
public bool SetTargetValue(object value, BindingPriority priority)
{
if (ShouldNotSet(value))
{
return true;
}
return SetTargetValueCore(value, priority);
}
private bool ShouldNotSet(object value)
{
if (PropertyType == null)
{
return false;
}
if (PropertyType.IsValueType)
{
return LastValue?.Target != null && LastValue.Target.Equals(value);
}
return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value);
}
protected abstract bool SetTargetValueCore(object value, BindingPriority priority);
public abstract Type PropertyType { get; }
}
}
|
Revert "fix(logging): 🐛 try yet another AppInsights config" | using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace FilterLists.SharedKernel.Logging
{
public static class HostRunner
{
public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default)
{
_ = host ?? throw new ArgumentNullException(nameof(host));
InitializeLogger(host);
try
{
if (runPreHostAsync != null)
{
Log.Information("Initializing pre-host");
await runPreHostAsync();
}
Log.Information("Initializing host");
await host.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
throw;
}
finally
{
Log.CloseAndFlush();
}
}
private static void InitializeLogger(IHost host)
{
var hostEnvironment = host.Services.GetRequiredService<IHostEnvironment>();
Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration
.ReadFrom.Configuration(host.Services.GetRequiredService<IConfiguration>())
.Enrich.WithProperty("Application", hostEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", hostEnvironment.EnvironmentName)
.WriteTo.Conditional(
_ => !hostEnvironment.IsProduction(),
sc => sc.Console().WriteTo.Debug())
.WriteTo.Conditional(
_ => hostEnvironment.IsProduction(),
sc => sc.ApplicationInsights(
host.Services.GetRequiredService<TelemetryConfiguration>(),
TelemetryConverter.Traces))
.CreateLogger();
}
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace FilterLists.SharedKernel.Logging
{
public static class HostRunner
{
public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default)
{
_ = host ?? throw new ArgumentNullException(nameof(host));
Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration
.WriteTo.Conditional(
_ => host.Services.GetService<IHostEnvironment>().IsProduction(),
c => c.ApplicationInsights(
TelemetryConfiguration.CreateDefault(),
TelemetryConverter.Traces))
.CreateLogger();
try
{
if (runPreHostAsync != null)
{
Log.Information("Initializing pre-host");
await runPreHostAsync();
}
Log.Information("Initializing host");
await host.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
throw;
}
finally
{
Log.CloseAndFlush();
}
}
}
}
|
Fix import tag to have correct namespace | using System;
using System.Xml;
namespace FluentNHibernate.Mapping
{
public class ImportPart : IMappingPart
{
private readonly Cache<string, string> attributes = new Cache<string, string>();
private readonly Type importType;
public ImportPart(Type importType)
{
this.importType = importType;
}
public void SetAttribute(string name, string value)
{
attributes.Store(name, value);
}
public void SetAttributes(Attributes attrs)
{
foreach (var key in attrs.Keys)
{
SetAttribute(key, attrs[key]);
}
}
public void Write(XmlElement classElement, IMappingVisitor visitor)
{
var importElement = classElement.AddElement("import")
.WithAtt("class", importType.AssemblyQualifiedName);
attributes.ForEachPair((name, value) => importElement.WithAtt(name, value));
}
public void As(string alternativeName)
{
SetAttribute("rename", alternativeName);
}
public int Level
{
get { return 1; }
}
public PartPosition Position
{
get { return PartPosition.First; }
}
}
} | using System;
using System.Xml;
namespace FluentNHibernate.Mapping
{
public class ImportPart : IMappingPart
{
private readonly Cache<string, string> attributes = new Cache<string, string>();
private readonly Type importType;
public ImportPart(Type importType)
{
this.importType = importType;
}
public void SetAttribute(string name, string value)
{
attributes.Store(name, value);
}
public void SetAttributes(Attributes attrs)
{
foreach (var key in attrs.Keys)
{
SetAttribute(key, attrs[key]);
}
}
public void Write(XmlElement classElement, IMappingVisitor visitor)
{
var importElement = classElement.AddElement("import")
.WithAtt("class", importType.AssemblyQualifiedName)
.WithAtt("xmlns", "urn:nhibernate-mapping-2.2");
attributes.ForEachPair((name, value) => importElement.WithAtt(name, value));
}
public void As(string alternativeName)
{
SetAttribute("rename", alternativeName);
}
public int Level
{
get { return 1; }
}
public PartPosition Position
{
get { return PartPosition.First; }
}
}
} |
Modify PropertyMetadata for correct overloading | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Xaml.Behaviors;
namespace Monitorian.Core.Views.Behaviors
{
public class FocusElementAction : TriggerAction<DependencyObject>
{
public UIElement TargetElement
{
get { return (UIElement)GetValue(TargetElementProperty); }
set { SetValue(TargetElementProperty, value); }
}
public static readonly DependencyProperty TargetElementProperty =
DependencyProperty.Register(
"TargetElement",
typeof(UIElement),
typeof(FocusElementAction),
new PropertyMetadata(null));
protected override void Invoke(object parameter)
{
if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused)
return;
TargetElement.Focus();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Xaml.Behaviors;
namespace Monitorian.Core.Views.Behaviors
{
public class FocusElementAction : TriggerAction<DependencyObject>
{
public UIElement TargetElement
{
get { return (UIElement)GetValue(TargetElementProperty); }
set { SetValue(TargetElementProperty, value); }
}
public static readonly DependencyProperty TargetElementProperty =
DependencyProperty.Register(
"TargetElement",
typeof(UIElement),
typeof(FocusElementAction),
new PropertyMetadata(default(UIElement)));
protected override void Invoke(object parameter)
{
if ((TargetElement is null) || !TargetElement.Focusable || TargetElement.IsFocused)
return;
TargetElement.Focus();
}
}
} |
Disable UnityEvent workaround since it is broken in Full Inspector | #if !NO_UNITY
using System;
using UnityEngine;
using UnityEngine.Events;
namespace FullSerializer {
partial class fsConverterRegistrar {
public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
}
}
namespace FullSerializer.Internal.Converters {
// The standard FS reflection converter has started causing Unity to crash when processing
// UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
// instead.
//
// We have to support legacy serialization formats so importing works as expected.
public class UnityEvent_Converter : fsConverter {
public override bool CanProcess(Type type) {
return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
}
public override bool RequestCycleSupport(Type storageType) {
return false;
}
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
Type objectType = (Type)instance;
fsResult result = fsResult.Success;
instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
return result;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
fsResult result = fsResult.Success;
serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
return result;
}
}
}
#endif | #if !NO_UNITY
using System;
using UnityEngine;
using UnityEngine.Events;
namespace FullSerializer {
partial class fsConverterRegistrar {
// Disable the converter for the time being. Unity's JsonUtility API cannot be called from
// within a C# ISerializationCallbackReceiver callback.
// public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter;
}
}
namespace FullSerializer.Internal.Converters {
// The standard FS reflection converter has started causing Unity to crash when processing
// UnityEvent. We can send the serialization through JsonUtility which appears to work correctly
// instead.
//
// We have to support legacy serialization formats so importing works as expected.
public class UnityEvent_Converter : fsConverter {
public override bool CanProcess(Type type) {
return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false;
}
public override bool RequestCycleSupport(Type storageType) {
return false;
}
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
Type objectType = (Type)instance;
fsResult result = fsResult.Success;
instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType);
return result;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
fsResult result = fsResult.Success;
serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance));
return result;
}
}
}
#endif |
Include first & last names for recipients | using System.Collections.Generic;
using Newtonsoft.Json;
using SurveyMonkey.Enums;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class Recipient : IPageableContainer
{
public long? Id { get; set; }
public long? SurveyId { get; set; }
internal string Href { get; set; }
public string Email { get; set; }
public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; }
public MessageStatus? MailStatus { get; set; }
public Dictionary<string, string> CustomFields { get; set; }
public string SurveyLink { get; set; }
public string RemoveLink { get; set; }
public Dictionary<string, string> ExtraFields { get; set; }
}
} | using System.Collections.Generic;
using Newtonsoft.Json;
using SurveyMonkey.Enums;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class Recipient : IPageableContainer
{
public long? Id { get; set; }
public long? SurveyId { get; set; }
internal string Href { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public RecipientSurveyResponseStatus? SurveyResponseStatus { get; set; }
public MessageStatus? MailStatus { get; set; }
public Dictionary<string, string> CustomFields { get; set; }
public string SurveyLink { get; set; }
public string RemoveLink { get; set; }
public Dictionary<string, string> ExtraFields { get; set; }
}
} |
Make brstm instead of dsp. Encode adpcm channels in parallel | using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Encode.Adpcm;
using DspAdpcm.Encode.Adpcm.Formats;
using DspAdpcm.Encode.Pcm;
using DspAdpcm.Encode.Pcm.Formats;
namespace DspAdpcm.Cli
{
public static class DspAdpcmCli
{
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: dspenc <wavin> <dspout>\n");
return 0;
}
IPcmStream wave;
try
{
using (var file = new FileStream(args[0], FileMode.Open))
{
wave = new Wave(file).AudioStream;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return -1;
}
Stopwatch watch = new Stopwatch();
watch.Start();
IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcm(wave);
watch.Stop();
Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond.");
var dsp = new Dsp(adpcm);
using (var stream = File.Open(args[1], FileMode.Create))
foreach (var b in dsp.GetFile())
stream.WriteByte(b);
return 0;
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using DspAdpcm.Encode.Adpcm;
using DspAdpcm.Encode.Adpcm.Formats;
using DspAdpcm.Encode.Pcm;
using DspAdpcm.Encode.Pcm.Formats;
namespace DspAdpcm.Cli
{
public static class DspAdpcmCli
{
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: dspadpcm <wavIn> <brstmOut>\n");
return 0;
}
IPcmStream wave;
try
{
using (var file = new FileStream(args[0], FileMode.Open))
{
wave = new Wave(file).AudioStream;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return -1;
}
Stopwatch watch = new Stopwatch();
watch.Start();
IAdpcmStream adpcm = Encode.Adpcm.Encode.PcmToAdpcmParallel(wave);
watch.Stop();
Console.WriteLine($"DONE! {adpcm.NumSamples} samples processed\n");
Console.WriteLine($"Time elapsed: {watch.Elapsed.TotalSeconds}");
Console.WriteLine($"Processed {(adpcm.NumSamples / watch.Elapsed.TotalMilliseconds):N} samples per milisecond.");
var brstm = new Brstm(adpcm);
using (var stream = File.Open(args[1], FileMode.Create))
foreach (var b in brstm.GetFile())
stream.WriteByte(b);
return 0;
}
}
}
|
Add raw message sending, requires xdotool | using System.Collections.Generic;
using System.Linq;
namespace SkypeSharp {
/// <summary>
/// Class representing a Skype CHAT object
/// </summary>
public class Chat : SkypeObject {
/// <summary>
/// List of users in this chat
/// </summary>
public IEnumerable<User> Users {
get {
string[] usernames = GetProperty("MEMBERS").Split(' ');
return usernames.Select(u => new User(Skype, u));
}
}
/// <summary>
/// List of chatmembers, useful for changing roles
/// Skype broke this so it probably doesn't work
/// </summary>
public IEnumerable<ChatMember> ChatMembers {
get {
string[] members = GetProperty("MEMBEROBJECTS").Split(' ');
return members.Select(m => new ChatMember(Skype, m));
}
}
public Chat(Skype skype, string id) : base(skype, id, "CHAT") {}
/// <summary>
/// Send a message to this chat
/// </summary>
/// <param name="text">Text to send</param>
public void Send(string text) {
Skype.Send("CHATMESSAGE " + ID + " " + text);
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace SkypeSharp {
/// <summary>
/// Class representing a Skype CHAT object
/// </summary>
public class Chat : SkypeObject {
/// <summary>
/// List of users in this chat
/// </summary>
public IEnumerable<User> Users {
get {
string[] usernames = GetProperty("MEMBERS").Split(' ');
return usernames.Select(u => new User(Skype, u));
}
}
/// <summary>
/// List of chatmembers, useful for changing roles
/// Skype broke this so it probably doesn't work
/// </summary>
public IEnumerable<ChatMember> ChatMembers {
get {
string[] members = GetProperty("MEMBEROBJECTS").Split(' ');
return members.Select(m => new ChatMember(Skype, m));
}
}
public Chat(Skype skype, string id) : base(skype, id, "CHAT") {}
/// <summary>
/// Send a message to this chat
/// </summary>
/// <param name="text">Text to send</param>
public void Send(string text) {
Skype.Send("CHATMESSAGE " + ID + " " + text);
}
/// <summary>
/// Uses xdotool to attempt to send skype a message
/// </summary>
/// <param name="text"></param>
public void SendRaw(string text) {
Skype.Send("OPEN CHAT " + ID);
Process p = new Process();
p.StartInfo.FileName = "/usr/bin/xdotool";
p.StartInfo.Arguments = String.Format("search --name skype type \"{0}\"", text.Replace("\"", "\\\""));
p.Start();
p.WaitForExit();
p.StartInfo.Arguments = "search --name skype key ctrl+shift+Return";
p.Start();
p.WaitForExit();
}
}
} |
Change the target to get working on build server | using System;
namespace SeleniumExtension.SauceLabs
{
public class SauceDriverKeys
{
public static string SAUCELABS_USERNAME
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME", EnvironmentVariableTarget.User);
if(string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME");
return userName;
}
}
public static string SAUCELABS_ACCESSKEY
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY", EnvironmentVariableTarget.User);
if (string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY");
return userName;
}
}
}
}
| using System;
namespace SeleniumExtension.SauceLabs
{
public class SauceDriverKeys
{
public static string SAUCELABS_USERNAME
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_USERNAME");
if(string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_USERNAME");
return userName;
}
}
public static string SAUCELABS_ACCESSKEY
{
get
{
var userName = Environment.GetEnvironmentVariable("SAUCELABS_ACCESSKEY");
if (string.IsNullOrEmpty(userName))
throw new Exception("Missing environment variable, name: SAUCELABS_ACCESSKEY");
return userName;
}
}
}
}
|
Add clock Face and Window classes. Draw a line. Setting FG color is TODO. | using System;
using Gtk;
namespace gtksharp_clock
{
class MainClass
{
public static void Main(string[] args)
{
Application.Init();
MainWindow win = new MainWindow();
win.Show();
Application.Run();
}
}
}
| using System;
using Gtk;
// http://www.mono-project.com/docs/gui/gtksharp/widgets/widget-colours/
namespace gtksharp_clock
{
class MainClass
{
public static void Main(string[] args)
{
Application.Init();
ClockWindow win = new ClockWindow ();
win.Show();
Application.Run();
}
}
class ClockWindow : Window
{
public ClockWindow() : base("ClockWindow")
{
SetDefaultSize(250, 200);
SetPosition(WindowPosition.Center);
ClockFace cf = new ClockFace();
Gdk.Color black = new Gdk.Color();
Gdk.Color.Parse("black", ref black);
Gdk.Color grey = new Gdk.Color();
Gdk.Color.Parse("grey", ref grey);
this.ModifyBg(StateType.Normal, grey);
cf.ModifyBg(StateType.Normal, grey);
this.ModifyFg(StateType.Normal, black);
cf.ModifyFg(StateType.Normal, black);
this.DeleteEvent += DeleteWindow;
Add(cf);
ShowAll();
}
static void DeleteWindow(object obj, DeleteEventArgs args)
{
Application.Quit();
}
}
class ClockFace : DrawingArea
{
public ClockFace() : base()
{
this.SetSizeRequest(600, 600);
this.ExposeEvent += OnExposed;
}
public void OnExposed(object o, ExposeEventArgs args)
{
Gdk.Color black = new Gdk.Color();
Gdk.Color.Parse("black", ref black);
this.ModifyFg(StateType.Normal, black);
this.GdkWindow.DrawLine(this.Style.BaseGC(StateType.Normal), 0, 0, 400, 300);
}
}
}
|
Document and clean up the binding code | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RabidWarren.Collections.Generic
{
public static class Enumerable
{
public static Multimap<TKey, TElement> ToMultimap<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector)
{
var map = new Multimap<TKey, TElement>();
foreach (var entry in source)
{
map.Add(keySelector(entry), elementSelector(entry));
}
return map;
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="Enumerable.cs" company="Ron Parker">
// Copyright 2014 Ron Parker
// </copyright>
// <summary>
// Provides an extension method for converting IEnumerables to Multimaps.
// </summary>
// -----------------------------------------------------------------------
namespace RabidWarren.Collections.Generic
{
using System;
using System.Collections.Generic;
/// <summary>
/// Contains extension methods for <see cref="System.Collections.Generic.IEnumerable{TSource}"/>.
/// </summary>
public static class Enumerable
{
/// <summary>
/// Converts the source to an <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>.
/// </summary>
/// <returns>The <see cref="RabidWarren.Collections.Generic.Multimap{TSource, TKey, TValue}"/>.</returns>
/// <param name="source">The source.</param>
/// <param name="keySelector">The key selector.</param>
/// <param name="valueSelector">The value selector.</param>
/// <typeparam name="TSource">The source type.</typeparam>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The the value type.</typeparam>
public static Multimap<TKey, TValue> ToMultimap<TSource, TKey, TValue>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TValue> valueSelector)
{
var map = new Multimap<TKey, TValue>();
foreach (var entry in source)
{
map.Add(keySelector(entry), valueSelector(entry));
}
return map;
}
}
}
|
Remove semicolons from poll page | <!DOCTYPE html>
<html ng-app="VoteOn-Poll">
<head>
<title>Vote On</title>
<meta name="viewport" content="initial-scale=1">
@Styles.Render("~/Bundles/StyleLib/AngularMaterial")
@Styles.Render("~/Bundles/StyleLib/FontAwesome")
@Styles.Render("~/Bundles/VotingStyle")
</head>
<body>
<div layout="column" flex layout-fill>
<toolbar></toolbar>
<div ng-view></div>
</div>
@Scripts.Render("~/Bundles/ScriptLib/JQuery");
@Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR");
@Scripts.Render("~/Bundles/ScriptLib/Angular")
@Scripts.Render("~/Bundles/ScriptLib/AngularAnimate")
@Scripts.Render("~/Bundles/ScriptLib/AngularAria")
@Scripts.Render("~/Bundles/ScriptLib/AngularMaterial")
@Scripts.Render("~/Bundles/ScriptLib/AngularMessages")
@Scripts.Render("~/Bundles/ScriptLib/AngularRoute")
@Scripts.Render("~/Bundles/ScriptLib/AngularCharts")
@Scripts.Render("~/Bundles/ScriptLib/AngularSignalR")
@Scripts.Render("~/Bundles/ScriptLib/ngStorage")
@Scripts.Render("~/Bundles/ScriptLib/moment")
@Scripts.Render("~/Bundles/Script")
</body>
</html> | <!DOCTYPE html>
<html ng-app="VoteOn-Poll">
<head>
<title>Vote On</title>
<meta name="viewport" content="initial-scale=1">
@Styles.Render("~/Bundles/StyleLib/AngularMaterial")
@Styles.Render("~/Bundles/StyleLib/FontAwesome")
@Styles.Render("~/Bundles/VotingStyle")
</head>
<body>
<div layout="column" flex layout-fill>
<toolbar></toolbar>
<div ng-view></div>
</div>
@Scripts.Render("~/Bundles/ScriptLib/JQuery")
@Scripts.Render("~/Bundles/ScriptLib/JQuerySignalR")
@Scripts.Render("~/Bundles/ScriptLib/Angular")
@Scripts.Render("~/Bundles/ScriptLib/AngularAnimate")
@Scripts.Render("~/Bundles/ScriptLib/AngularAria")
@Scripts.Render("~/Bundles/ScriptLib/AngularMaterial")
@Scripts.Render("~/Bundles/ScriptLib/AngularMessages")
@Scripts.Render("~/Bundles/ScriptLib/AngularRoute")
@Scripts.Render("~/Bundles/ScriptLib/AngularCharts")
@Scripts.Render("~/Bundles/ScriptLib/AngularSignalR")
@Scripts.Render("~/Bundles/ScriptLib/ngStorage")
@Scripts.Render("~/Bundles/ScriptLib/moment")
@Scripts.Render("~/Bundles/Script")
</body>
</html> |
Fix taiko difficulty adjust scroll speed being shown with too low precision | // 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 osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModDifficultyAdjust : ModDifficultyAdjust
{
[SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))]
public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable
{
Precision = 0.05f,
MinValue = 0.25f,
MaxValue = 4,
ReadCurrentFromDifficulty = _ => 1,
};
public override string SettingDescription
{
get
{
string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N1}";
return string.Join(", ", new[]
{
base.SettingDescription,
scrollSpeed
}.Where(s => !string.IsNullOrEmpty(s)));
}
}
protected override void ApplySettings(BeatmapDifficulty difficulty)
{
base.ApplySettings(difficulty);
if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value;
}
}
}
| // 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 osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModDifficultyAdjust : ModDifficultyAdjust
{
[SettingSource("Scroll Speed", "Adjust a beatmap's set scroll speed", LAST_SETTING_ORDER + 1, SettingControlType = typeof(DifficultyAdjustSettingsControl))]
public DifficultyBindable ScrollSpeed { get; } = new DifficultyBindable
{
Precision = 0.05f,
MinValue = 0.25f,
MaxValue = 4,
ReadCurrentFromDifficulty = _ => 1,
};
public override string SettingDescription
{
get
{
string scrollSpeed = ScrollSpeed.IsDefault ? string.Empty : $"Scroll x{ScrollSpeed.Value:N2}";
return string.Join(", ", new[]
{
base.SettingDescription,
scrollSpeed
}.Where(s => !string.IsNullOrEmpty(s)));
}
}
protected override void ApplySettings(BeatmapDifficulty difficulty)
{
base.ApplySettings(difficulty);
if (ScrollSpeed.Value != null) difficulty.SliderMultiplier *= ScrollSpeed.Value.Value;
}
}
}
|
Add startup value for the slider | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Timing;
using osu.Framework.Configuration;
namespace osu.Game.Screens.Play.ReplaySettings
{
public class PlaybackSettings : ReplayGroup
{
protected override string Title => @"playback";
public IAdjustableClock AdjustableClock { set; get; }
private readonly ReplaySliderBar<double> sliderbar;
public PlaybackSettings()
{
Child = sliderbar = new ReplaySliderBar<double>
{
LabelText = "Playback speed",
Bindable = new BindableDouble
{
Default = 1,
MinValue = 0.5,
MaxValue = 2
},
};
}
protected override void LoadComplete()
{
base.LoadComplete();
if (AdjustableClock == null)
return;
var clockRate = AdjustableClock.Rate;
sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Timing;
using osu.Framework.Configuration;
namespace osu.Game.Screens.Play.ReplaySettings
{
public class PlaybackSettings : ReplayGroup
{
protected override string Title => @"playback";
public IAdjustableClock AdjustableClock { set; get; }
private readonly ReplaySliderBar<double> sliderbar;
public PlaybackSettings()
{
Child = sliderbar = new ReplaySliderBar<double>
{
LabelText = "Playback speed",
Bindable = new BindableDouble(1)
{
Default = 1,
MinValue = 0.5,
MaxValue = 2
},
};
}
protected override void LoadComplete()
{
base.LoadComplete();
if (AdjustableClock == null)
return;
var clockRate = AdjustableClock.Rate;
sliderbar.Bindable.ValueChanged += rateMultiplier => AdjustableClock.Rate = clockRate * rateMultiplier;
}
}
}
|
Change name of the property for the status transition to match the API too | using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeStatusTransitions : StripeEntity
{
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("canceled")]
public DateTime? Canceled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("fulfiled")]
public DateTime? Fulfilled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("paid")]
public DateTime? Paid { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("returned")]
public DateTime? Returned { get; set; }
}
}
| using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeStatusTransitions : StripeEntity
{
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("canceled")]
public DateTime? Canceled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("fulfiled")]
public DateTime? Fulfiled { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("paid")]
public DateTime? Paid { get; set; }
[JsonConverter(typeof(StripeDateTimeConverter))]
[JsonProperty("returned")]
public DateTime? Returned { get; set; }
}
}
|
Add new createInstance overloads to scriptbuilderfactory.cs to support scriptbuildersettings args | using System;
using System.Collections.Generic;
using System.Reflection;
namespace Acklann.Daterpillar.TextTransformation
{
public class ScriptBuilderFactory
{
public ScriptBuilderFactory()
{
LoadAssemblyTypes();
}
public IScriptBuilder CreateInstance(string name)
{
try { return (IScriptBuilder)Activator.CreateInstance(Type.GetType(_scriptBuilderTypes[name.ToLower()])); }
catch (KeyNotFoundException) { return new NullScriptBuilder(); }
}
public IScriptBuilder CreateInstance(ConnectionType connectionType)
{
return CreateInstance(string.Concat(connectionType, _targetInterface));
}
#region Private Members
private string _targetInterface = nameof(IScriptBuilder).Substring(1);
private IDictionary<string, string> _scriptBuilderTypes = new Dictionary<string, string>();
private void LoadAssemblyTypes()
{
Assembly thisAssembly = Assembly.Load(new AssemblyName(typeof(IScriptBuilder).GetTypeInfo().Assembly.FullName));
foreach (var typeInfo in thisAssembly.DefinedTypes)
if (typeInfo.IsPublic && !typeInfo.IsInterface && !typeInfo.IsAbstract && typeof(IScriptBuilder).GetTypeInfo().IsAssignableFrom(typeInfo))
{
_scriptBuilderTypes.Add(typeInfo.Name.ToLower(), typeInfo.FullName);
}
}
#endregion Private Members
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
namespace Acklann.Daterpillar.TextTransformation
{
public class ScriptBuilderFactory
{
public ScriptBuilderFactory()
{
LoadAssemblyTypes();
}
public IScriptBuilder CreateInstance(string name)
{
return CreateInstance(name, ScriptBuilderSettings.Default);
}
public IScriptBuilder CreateInstance(string name, ScriptBuilderSettings settings)
{
try { return (IScriptBuilder)Activator.CreateInstance(Type.GetType(_scriptBuilderTypes[name.ToLower()]), settings); }
catch (KeyNotFoundException) { return new NullScriptBuilder(); }
}
public IScriptBuilder CreateInstance(ConnectionType connectionType)
{
return CreateInstance(string.Concat(connectionType, _targetInterface), ScriptBuilderSettings.Default);
}
public IScriptBuilder CreateInstance(ConnectionType connectionType, ScriptBuilderSettings settings)
{
return CreateInstance(string.Concat(connectionType, _targetInterface), settings);
}
#region Private Members
private string _targetInterface = nameof(IScriptBuilder).Substring(1);
private IDictionary<string, string> _scriptBuilderTypes = new Dictionary<string, string>();
private void LoadAssemblyTypes()
{
Assembly thisAssembly = Assembly.Load(new AssemblyName(typeof(IScriptBuilder).GetTypeInfo().Assembly.FullName));
foreach (var typeInfo in thisAssembly.DefinedTypes)
if (typeInfo.IsPublic && !typeInfo.IsInterface && !typeInfo.IsAbstract && typeof(IScriptBuilder).GetTypeInfo().IsAssignableFrom(typeInfo))
{
_scriptBuilderTypes.Add(typeInfo.Name.ToLower(), typeInfo.FullName);
}
}
#endregion Private Members
}
} |
Fix EOI emails are not sent | using System.Threading.Tasks;
using System.Web.Http;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
using CroquetAustralia.Domain.Services.Queues;
namespace CroquetAustralia.WebApi.Controllers
{
[RoutePrefix("tournament-entry")]
public class TournamentEntryController : ApiController
{
private readonly IEventsQueue _eventsQueue;
public TournamentEntryController(IEventsQueue eventsQueue)
{
_eventsQueue = eventsQueue;
}
[HttpPost]
[Route("add-entry")]
public async Task AddEntryAsync(SubmitEntry command)
{
var entrySubmitted = command.ToEntrySubmitted();
await _eventsQueue.AddMessageAsync(entrySubmitted);
}
[HttpPost]
[Route("payment-received")]
public async Task PaymentReceivedAsync(ReceivePayment command)
{
// todo: extension method command.MapTo<EntrySubmitted>
var @event = new PaymentReceived(command.EntityId, command.PaymentMethod);
await _eventsQueue.AddMessageAsync(@event);
}
}
} | using System;
using System.Threading.Tasks;
using System.Web.Http;
using CroquetAustralia.Domain.Features.TournamentEntry;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
using CroquetAustralia.Domain.Services.Queues;
namespace CroquetAustralia.WebApi.Controllers
{
[RoutePrefix("tournament-entry")]
public class TournamentEntryController : ApiController
{
private readonly IEventsQueue _eventsQueue;
public TournamentEntryController(IEventsQueue eventsQueue)
{
_eventsQueue = eventsQueue;
}
[HttpPost]
[Route("add-entry")]
public async Task AddEntryAsync(SubmitEntry command)
{
// todo: allow javascript to send null
if (command.PaymentMethod.HasValue && (int)command.PaymentMethod.Value == -1)
{
command.PaymentMethod = null;
}
var entrySubmitted = command.ToEntrySubmitted();
await _eventsQueue.AddMessageAsync(entrySubmitted);
}
[HttpPost]
[Route("payment-received")]
public async Task PaymentReceivedAsync(ReceivePayment command)
{
// todo: extension method command.MapTo<EntrySubmitted>
var @event = new PaymentReceived(command.EntityId, command.PaymentMethod);
await _eventsQueue.AddMessageAsync(@event);
}
}
} |
Add a root state type | using System.Xml.Serialization;
namespace DevelopmentInProgress.DipState
{
public enum DipStateType
{
[XmlEnum("1")]
Standard = 1,
[XmlEnum("2")]
Auto = 3
}
} | using System.Xml.Serialization;
namespace DevelopmentInProgress.DipState
{
public enum DipStateType
{
[XmlEnum("1")]
Standard = 1,
[XmlEnum("2")]
Auto = 2,
[XmlEnum("3")]
Root = 3
}
} |
Fix broken tests getting items from the valid root | namespace Sitecore.FakeDb.Serialization.Tests.Deserialize
{
using System.Linq;
using Xunit;
[Trait("Deserialize", "Deserializing a tree of items")]
public class DeserializeTree : DeserializeTestBase
{
public DeserializeTree()
{
this.Db.Add(new DsDbItem(SerializationId.SampleTemplateFolder, true)
{
ParentID = TemplateIDs.TemplateFolder
});
}
[Fact(DisplayName = "Deserializes templates in tree")]
public void DeserializesTemplates()
{
Assert.NotNull(this.Db.Database.GetTemplate(SerializationId.SampleItemTemplate));
}
[Fact(DisplayName = "Deserializes items in tree")]
public void DeserializesItems()
{
var nonTemplateItemCount =
this.Db.Database.GetItem(TemplateIDs.TemplateFolder)
.Axes.GetDescendants()
.Count(x =>
x.TemplateID != TemplateIDs.Template &&
x.TemplateID != TemplateIDs.TemplateSection &&
x.TemplateID != TemplateIDs.TemplateField);
Assert.Equal(5, nonTemplateItemCount);
}
}
} | namespace Sitecore.FakeDb.Serialization.Tests.Deserialize
{
using System.Linq;
using Xunit;
[Trait("Deserialize", "Deserializing a tree of items")]
public class DeserializeTree : DeserializeTestBase
{
public DeserializeTree()
{
this.Db.Add(new DsDbItem(SerializationId.SampleTemplateFolder, true)
{
ParentID = TemplateIDs.TemplateFolder
});
}
[Fact(DisplayName = "Deserializes templates in tree")]
public void DeserializesTemplates()
{
Assert.NotNull(this.Db.Database.GetTemplate(SerializationId.SampleItemTemplate));
}
[Fact(DisplayName = "Deserializes items in tree")]
public void DeserializesItems()
{
var nonTemplateItemCount =
this.Db.Database.GetItem(ItemIDs.TemplateRoot)
.Axes.GetDescendants()
.Count(x =>
x.TemplateID != TemplateIDs.Template &&
x.TemplateID != TemplateIDs.TemplateSection &&
x.TemplateID != TemplateIDs.TemplateField);
Assert.Equal(5, nonTemplateItemCount);
}
}
} |
Change the plugin library load path | using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;
namespace PluginLoader.Tests
{
public class Plugins_Tests
{
[Fact]
public void PluginsFoundFromLibsFolder()
{
// Arrange
var path = @"..\..\..\..\LAN\bin\Debug\netstandard1.3";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.NotEmpty(plugins);
}
[Fact]
public void PluginsNotFoundFromCurrentFolder()
{
// Arrange
var path = @".";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.Empty(plugins);
}
}
}
| using PluginContracts;
using System;
using System.Collections.Generic;
using Xunit;
namespace PluginLoader.Tests
{
public class Plugins_Tests
{
[Fact]
public void PluginsFoundFromLibsFolder()
{
// Arrange
var path = @"..\..\..\..\Libs";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.NotEmpty(plugins);
}
[Fact]
public void PluginsNotFoundFromCurrentFolder()
{
// Arrange
var path = @".";
// Act
var plugins = Plugins<IPluginV1>.Load(path);
// Assert
Assert.Empty(plugins);
}
}
}
|
Remove trailing slash from base URL | using System.Web;
using System.Web.Mvc;
namespace SimpleMvcSitemap
{
class BaseUrlProvider : IBaseUrlProvider
{
public string GetBaseUrl(HttpContextBase httpContext)
{
//http://stackoverflow.com/a/1288383/205859
HttpRequestBase request = httpContext.Request;
return string.Format("{0}://{1}{2}", request.Url.Scheme,
request.Url.Authority,
UrlHelper.GenerateContentUrl("~", httpContext));
}
}
} | using System.Web;
using System.Web.Mvc;
namespace SimpleMvcSitemap
{
class BaseUrlProvider : IBaseUrlProvider
{
public string GetBaseUrl(HttpContextBase httpContext)
{
//http://stackoverflow.com/a/1288383/205859
HttpRequestBase request = httpContext.Request;
return string.Format("{0}://{1}{2}", request.Url.Scheme,
request.Url.Authority,
UrlHelper.GenerateContentUrl("~", httpContext))
.TrimEnd('/');
}
}
} |
Test Fetcher.Login POSTs with correct values | using System.Collections.Specialized;
using System.Text;
using Moq;
using NUnit.Framework;
namespace LastPass.Test
{
[TestFixture]
class FetcherTest
{
[Test]
public void Login()
{
var webClient = new Mock<IWebClient>();
webClient
.Setup(x => x.UploadValues(It.Is<string>(s => s == "https://lastpass.com/login.php"),
It.IsAny<NameValueCollection>()))
.Returns(Encoding.UTF8.GetBytes(""))
.Verifiable();
new Fetcher("username", "password").Login(webClient.Object);
webClient.Verify();
}
}
}
| using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Moq;
using NUnit.Framework;
namespace LastPass.Test
{
[TestFixture]
class FetcherTest
{
[Test]
public void Login()
{
const string url = "https://lastpass.com/login.php";
const string username = "username";
const string password = "password";
var expectedValues = new NameValueCollection
{
{"method", "mobile"},
{"web", "1"},
{"xml", "1"},
{"username", username},
{"hash", "e379d972c3eb59579abe3864d850b5f54911544adfa2daf9fb53c05d30cdc985"},
{"iterations", "1"}
};
var webClient = new Mock<IWebClient>();
webClient
.Setup(x => x.UploadValues(It.Is<string>(s => s == url),
It.Is<NameValueCollection>(v => AreEqual(v, expectedValues))))
.Returns(Encoding.UTF8.GetBytes(""))
.Verifiable();
new Fetcher(username, password).Login(webClient.Object);
webClient.Verify();
}
private static bool AreEqual(NameValueCollection a, NameValueCollection b)
{
return a.AllKeys.OrderBy(s => s).SequenceEqual(b.AllKeys.OrderBy(s => s)) &&
a.AllKeys.All(s => a[s] == b[s]);
}
}
}
|
Use range check for floating point | using System;
using NUnit.Framework;
using FluentAssertions;
using SketchSolve;
using System.Linq;
namespace SketchSolve.Spec
{
[TestFixture()]
public class Solver
{
[Test()]
public void HorizontalConstraintShouldWork ()
{
var parameters = new Parameter[]{
new Parameter(0),
new Parameter(1),
new Parameter(2),
new Parameter(3)
};
var points = new point[]{
new point(){x = parameters[0], y = parameters[1]},
new point(){x = parameters[2], y = parameters[3]},
};
var lines = new line[]{
new line(){p1 = points[0], p2 = points[1]}
};
var cons = new constraint[] {
new constraint(){
type =ConstraintEnum.horizontal,
line1 = lines[0]
}
};
var r = SketchSolve.Solver.solve(parameters, cons, true);
points [0].y.Value.Should ().Be (points[1].y.Value);
points [0].x.Value.Should ().NotBe (points[1].x.Value);
}
}
}
| using System;
using NUnit.Framework;
using FluentAssertions;
using SketchSolve;
using System.Linq;
namespace SketchSolve.Spec
{
[TestFixture()]
public class Solver
{
[Test()]
public void HorizontalConstraintShouldWork ()
{
var parameters = new Parameter[]{
new Parameter(0),
new Parameter(1),
new Parameter(2),
new Parameter(3)
};
var points = new point[]{
new point(){x = parameters[0], y = parameters[1]},
new point(){x = parameters[2], y = parameters[3]},
};
var lines = new line[]{
new line(){p1 = points[0], p2 = points[1]}
};
var cons = new constraint[] {
new constraint(){
type =ConstraintEnum.horizontal,
line1 = lines[0]
}
};
var r = SketchSolve.Solver.solve(parameters, cons, true);
points [0].y.Value.Should ().BeInRange (points[1].y.Value-0.001, points[1].y.Value+0.001);
points [0].x.Value.Should ().NotBe (points[1].x.Value);
}
}
}
|
Add reference to source of debug lookup method | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace osu.Framework.Development
{
public static class DebugUtils
{
public static bool IsDebugBuild => is_debug_build.Value;
private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() => Assembly.GetExecutingAssembly().GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled));
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace osu.Framework.Development
{
public static class DebugUtils
{
public static bool IsDebugBuild => is_debug_build.Value;
private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() =>
// https://stackoverflow.com/a/2186634
Assembly.GetExecutingAssembly().GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled)
);
}
}
|
Use string in stead of HashSet - much faster | using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class AnyParser : IParser<InlineString>
{
public AnyParser(string significantChars)
{
SignificantChars = string.IsNullOrEmpty(significantChars) ? new HashSet<char>(significantChars) : null;
}
public HashSet<char> SignificantChars { get; private set; }
public string StartsWithChars { get { return null; } }
public InlineString Parse(ParserContext context, Subject subject)
{
if (SignificantChars != null)
{
var chars = subject.TakeWhile(c => !SignificantChars.Contains(c));
if (chars.Any())
{
return new InlineString(chars);
}
}
return new InlineString(subject.Take());
}
}
}
| using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class AnyParser : IParser<InlineString>
{
public AnyParser(string significantChars)
{
SignificantChars = significantChars;
}
public string SignificantChars { get; private set; }
public string StartsWithChars { get { return null; } }
public InlineString Parse(ParserContext context, Subject subject)
{
if (SignificantChars != null)
{
var chars = subject.TakeWhile(c => !SignificantChars.Contains(c));
if (chars.Any())
{
return new InlineString(chars);
}
}
return new InlineString(subject.Take());
}
}
}
|
Add settings buttons to allow temporarily blocking realm access | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Framework.Platform;
using osu.Game.Database;
using osu.Game.Localisation;
namespace osu.Game.Overlays.Settings.Sections.DebugSettings
{
public class MemorySettings : SettingsSubsection
{
protected override LocalisableString Header => DebugSettingsStrings.MemoryHeader;
[BackgroundDependencyLoader]
private void load(GameHost host, RealmContextFactory realmFactory)
{
Children = new Drawable[]
{
new SettingsButton
{
Text = DebugSettingsStrings.ClearAllCaches,
Action = host.Collect
},
new SettingsButton
{
Text = DebugSettingsStrings.CompactRealm,
Action = () =>
{
// Blocking operations implicitly causes a Compact().
using (realmFactory.BlockAllOperations())
{
}
}
},
};
}
}
}
| // 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.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Framework.Platform;
using osu.Game.Database;
using osu.Game.Localisation;
namespace osu.Game.Overlays.Settings.Sections.DebugSettings
{
public class MemorySettings : SettingsSubsection
{
protected override LocalisableString Header => DebugSettingsStrings.MemoryHeader;
[BackgroundDependencyLoader]
private void load(GameHost host, RealmContextFactory realmFactory)
{
SettingsButton blockAction;
SettingsButton unblockAction;
Children = new Drawable[]
{
new SettingsButton
{
Text = DebugSettingsStrings.ClearAllCaches,
Action = host.Collect
},
new SettingsButton
{
Text = DebugSettingsStrings.CompactRealm,
Action = () =>
{
// Blocking operations implicitly causes a Compact().
using (realmFactory.BlockAllOperations())
{
}
}
},
blockAction = new SettingsButton
{
Text = "Block realm",
},
unblockAction = new SettingsButton
{
Text = "Unblock realm",
},
};
blockAction.Action = () =>
{
var blocking = realmFactory.BlockAllOperations();
blockAction.Enabled.Value = false;
// As a safety measure, unblock after 10 seconds.
// This is to handle the case where a dev may block, but then something on the update thread
// accesses realm and blocks for eternity.
Task.Factory.StartNew(() =>
{
Thread.Sleep(10000);
unblock();
});
unblockAction.Action = unblock;
void unblock()
{
blocking?.Dispose();
blocking = null;
Scheduler.Add(() =>
{
blockAction.Enabled.Value = true;
unblockAction.Action = null;
});
}
};
}
}
}
|
Add ignore_case and expand properties to synonym filter | using Newtonsoft.Json;
using System.Collections.Generic;
namespace Nest
{
public class SynonymTokenFilter : TokenFilterSettings
{
public SynonymTokenFilter() : base("synonym")
{
}
[JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)]
public string SynonymsPath { get; set; }
[JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)]
public string Format { get; set; }
[JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)]
public IEnumerable<string> Synonyms { get; set; }
}
}
| using Newtonsoft.Json;
using System.Collections.Generic;
namespace Nest
{
public class SynonymTokenFilter : TokenFilterSettings
{
public SynonymTokenFilter() : base("synonym")
{
}
[JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)]
public string SynonymsPath { get; set; }
[JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)]
public string Format { get; set; }
[JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)]
public IEnumerable<string> Synonyms { get; set; }
[JsonProperty("ignore_case", NullValueHandling = NullValueHandling.Ignore)]
public bool? IgnoreCase { get; set; }
[JsonProperty("expand", NullValueHandling = NullValueHandling.Ignore)]
public bool? Expand { get; set; }
}
}
|
Fix missing object reference error. | /* Copyright (c) 2016 Kevin Fischer
*
* This Source Code Form is subject to the terms of the MIT License.
* If a copy of the license was not distributed with this file,
* You can obtain one at https://opensource.org/licenses/MIT. */
using UnityEngine;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace HexMapEngine {
public class HexMap : ScriptableObject {
List<HexData> _hexData;
public ReadOnlyCollection<HexData> HexData {
get { return _hexData.AsReadOnly(); }
}
Dictionary<Hex, HexData> _map;
public void SetHexData(List<HexData> hexData) {
_hexData = hexData;
_map = new Dictionary<Hex, HexData>();
foreach (HexData data in hexData) {
_map.Add(data.position, data);
}
}
public HexData Get(Hex position) {
HexData result;
_map.TryGetValue(position, out result);
return result;
}
}
}
| /* Copyright (c) 2016 Kevin Fischer
*
* This Source Code Form is subject to the terms of the MIT License.
* If a copy of the license was not distributed with this file,
* You can obtain one at https://opensource.org/licenses/MIT. */
using UnityEngine;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace HexMapEngine {
public class HexMap : ScriptableObject {
List<HexData> _hexData = new List<HexData>();
public ReadOnlyCollection<HexData> HexData {
get { return _hexData.AsReadOnly(); }
}
Dictionary<Hex, HexData> _map;
public void SetHexData(List<HexData> hexData) {
_hexData = hexData;
_map = new Dictionary<Hex, HexData>();
foreach (HexData data in hexData) {
_map.Add(data.position, data);
}
}
public HexData Get(Hex position) {
HexData result;
_map.TryGetValue(position, out result);
return result;
}
}
}
|
Set IsBusy immediately, so there is no chance to run the command more than once. | using AvalonStudio.Extensibility;
using ReactiveUI;
using Splat;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class ClosedWalletViewModel : WalletViewModelBase
{
public ClosedWalletViewModel(Wallet wallet) : base(wallet)
{
OpenWalletCommand = ReactiveCommand.CreateFromTask(async () =>
{
try
{
var global = Locator.Current.GetService<Global>();
if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None))
{
return;
}
await global.WalletManager.StartWalletAsync(Wallet);
}
catch (Exception e)
{
NotificationHelpers.Error($"Error loading Wallet: {Title}");
Logger.LogError(e.Message);
}
}, this.WhenAnyValue(x => x.IsBusy).Select(x => !x));
}
public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; }
}
}
| using AvalonStudio.Extensibility;
using ReactiveUI;
using Splat;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class ClosedWalletViewModel : WalletViewModelBase
{
public ClosedWalletViewModel(Wallet wallet) : base(wallet)
{
OpenWalletCommand = ReactiveCommand.CreateFromTask(async () =>
{
IsBusy = true;
try
{
var global = Locator.Current.GetService<Global>();
if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None))
{
return;
}
await global.WalletManager.StartWalletAsync(Wallet);
}
catch (Exception e)
{
NotificationHelpers.Error($"Error loading Wallet: {Title}");
Logger.LogError(e.Message);
}
}, this.WhenAnyValue(x => x.IsBusy).Select(x => !x));
}
public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; }
}
}
|
Add support for creating a bounded channel in helper | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reactive.Linq;
using System.Threading.Channels;
namespace SignalRSamples
{
public static class ObservableExtensions
{
public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable)
{
// This sample shows adapting an observable to a ChannelReader without
// back pressure, if the connection is slower than the producer, memory will
// start to increase.
// If the channel is unbounded, TryWrite will return false and effectively
// drop items.
// The other alternative is to use a bounded channel, and when the limit is reached
// block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended
var channel = Channel.CreateUnbounded<T>();
var disposable = observable.Subscribe(
value => channel.Writer.TryWrite(value),
error => channel.Writer.TryComplete(error),
() => channel.Writer.TryComplete());
// Complete the subscription on the reader completing
channel.Reader.Completion.ContinueWith(task => disposable.Dispose());
return channel.Reader;
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reactive.Linq;
using System.Threading.Channels;
namespace SignalRSamples
{
public static class ObservableExtensions
{
public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable, int? maxBufferSize = null)
{
// This sample shows adapting an observable to a ChannelReader without
// back pressure, if the connection is slower than the producer, memory will
// start to increase.
// If the channel is bounded, TryWrite will return false and effectively
// drop items.
// The other alternative is to use a bounded channel, and when the limit is reached
// block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended and isn't shown here.
var channel = maxBufferSize != null ? Channel.CreateBounded<T>(maxBufferSize.Value) : Channel.CreateUnbounded<T>();
var disposable = observable.Subscribe(
value => channel.Writer.TryWrite(value),
error => channel.Writer.TryComplete(error),
() => channel.Writer.TryComplete());
// Complete the subscription on the reader completing
channel.Reader.Completion.ContinueWith(task => disposable.Dispose());
return channel.Reader;
}
}
} |
Add scheduling of events to occur later on the timeline | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Describes a series of domain events
/// </summary>
public interface ITimeline : IFluent
{
void Append(TimelinePosition cause, IReadOnlyList<Event> events);
Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow;
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Describes a series of domain events
/// </summary>
public interface ITimeline : IFluent
{
void Append(TimelinePosition cause, Many<Event> events);
void AppendLater(DateTime when, Many<Event> events);
Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow;
}
} |
Enable JS in the browser so the user can authorize the app | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
using Repository.Internal;
using static Repository.Internal.Verify;
namespace Repository
{
[Activity(Label = "Sign In")]
public class SignInActivity : Activity
{
private sealed class LoginSuccessListener : WebViewClient
{
private readonly string _callbackUrl;
internal LoginSuccessListener(string callbackUrl)
{
_callbackUrl = NotNull(callbackUrl);
}
public override void OnPageFinished(WebView view, string url)
{
if (url.StartsWith(_callbackUrl, StringComparison.Ordinal))
{
// TODO: Start some activity?
}
}
}
private WebView _signInWebView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.SignIn);
_signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView);
var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url));
_signInWebView.LoadUrl(url);
var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl));
_signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl));
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
using Repository.Internal;
using static Repository.Internal.Verify;
namespace Repository
{
[Activity(Label = "Sign In")]
public class SignInActivity : Activity
{
private sealed class LoginSuccessListener : WebViewClient
{
private readonly string _callbackUrl;
internal LoginSuccessListener(string callbackUrl)
{
_callbackUrl = NotNull(callbackUrl);
}
public override void OnPageFinished(WebView view, string url)
{
if (url.StartsWith(_callbackUrl, StringComparison.Ordinal))
{
// TODO: Start some activity?
}
}
}
private WebView _signInWebView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.SignIn);
_signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView);
// GitHub needs JS enabled to un-grey the authorization button
_signInWebView.Settings.JavaScriptEnabled = true;
var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url));
_signInWebView.LoadUrl(url);
var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl));
_signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl));
}
}
} |
Update Setting Values for OAuth2 setting | using System;
using UnityEngine;
namespace CloudBread.OAuth
{
public class OAuth2Setting : ScriptableObject
{
static bool _useFacebook;
static public string FaceBookRedirectAddress;
static bool _useGooglePlay;
public static string GooglePlayRedirectAddress;
static bool _useKaKao;
public static string KakaoRedirectAddress;
public OAuth2Setting ()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
namespace CloudBread.OAuth
{
public class OAuth2Setting : ScriptableObject
{
private const string SettingAssetName = "CBOAuth2Setting";
private const string SettingsPath = "CloudBread/Resources";
private const string SettingsAssetExtension = ".asset";
// Facebook
private bool _useFacebook = false;
static public bool UseFacebook
{
get { return Instance._useFacebook; }
set { Instance._useFacebook = value; }
}
private string _facebookRedirectAddress = ".auth/login/facebook";
static public string FacebookRedirectAddress
{
get { return Instance._facebookRedirectAddress; }
set { Instance._facebookRedirectAddress = value; }
}
// GoogePlay
public bool _useGooglePlay = false;
static public bool UseGooglePlay
{
get { return instance._useGooglePlay; }
set { Instance._useGooglePlay = value; }
}
public string _googleRedirectAddress = "aaaa";
static public string GoogleRedirectAddress
{
get { return instance._googleRedirectAddress; }
set { Instance._googleRedirectAddress = value; }
}
// KaKao
private bool _useKaKao = false;
public bool UseKaKao
{
get { return Instance._useKaKao; }
set { Instance._useKaKao = value; }
}
public static string KakaoRedirectAddress;
private static OAuth2Setting instance = null;
public static OAuth2Setting Instance
{
get
{
if (instance == null)
{
instance = Resources.Load(SettingAssetName) as OAuth2Setting;
if (instance == null)
{
// If not found, autocreate the asset object.
instance = ScriptableObject.CreateInstance<OAuth2Setting>();
#if UNITY_EDITOR
string properPath = Path.Combine(Application.dataPath, SettingsPath);
if (!Directory.Exists(properPath))
{
Directory.CreateDirectory(properPath);
}
string fullPath = Path.Combine(
Path.Combine("Assets", SettingsPath),
SettingAssetName + SettingsAssetExtension);
AssetDatabase.CreateAsset(instance, fullPath);
#endif
}
}
return instance;
}
}
}
}
|
Fix invalid JSON caused by localized decimal mark | using System;
using Newtonsoft.Json;
namespace Glimpse.Internal
{
public class TimeSpanConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var result = 0.0;
var convertedNullable = value as TimeSpan?;
if (convertedNullable.HasValue)
{
result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2);
}
writer.WriteRawValue(result.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?);
}
}
}
| using System;
using System.Globalization;
using Newtonsoft.Json;
namespace Glimpse.Internal
{
public class TimeSpanConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var result = 0.0;
var convertedNullable = value as TimeSpan?;
if (convertedNullable.HasValue)
{
result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2);
}
writer.WriteRawValue(result.ToString(CultureInfo.InvariantCulture));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?);
}
}
}
|
Add members property to collection | using Newtonsoft.Json;
namespace Digirati.IIIF.Model.Types
{
public class Collection : IIIFPresentationBase
{
[JsonProperty(Order = 100, PropertyName = "collections")]
public Collection[] Collections { get; set; }
[JsonProperty(Order = 101, PropertyName = "manifests")]
public Manifest[] Manifests { get; set; }
public override string Type
{
get { return "sc:Collection"; }
}
}
}
| using Newtonsoft.Json;
namespace Digirati.IIIF.Model.Types
{
public class Collection : IIIFPresentationBase
{
[JsonProperty(Order = 100, PropertyName = "collections")]
public Collection[] Collections { get; set; }
[JsonProperty(Order = 101, PropertyName = "manifests")]
public Manifest[] Manifests { get; set; }
[JsonProperty(Order = 111, PropertyName = "members")]
public IIIFPresentationBase[] Members { get; set; }
public override string Type
{
get { return "sc:Collection"; }
}
}
}
|
Remove unnecessary using's, add comment | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NutPackerLib
{
public class OriginalNameAttribute : Attribute
{
public string Name { get; private set; }
public OriginalNameAttribute(string name)
{
Name = name;
}
}
}
| using System;
namespace NutPackerLib
{
/// <summary>
/// Original name of something.
/// </summary>
public class OriginalNameAttribute : Attribute
{
public string Name { get; private set; }
public OriginalNameAttribute(string name)
{
Name = name;
}
}
}
|
Increase project version number to 0.14.0 | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.13.0")]
[assembly: AssemblyFileVersion("0.13.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.14.0")]
[assembly: AssemblyFileVersion("0.14.0")]
|
Add spaces into displayed Palette Insight Agent service name | using Topshelf;
namespace PaletteInsightAgentService
{
/// <summary>
/// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us.
/// </summary>
internal class PaletteInsightAgentService
{
// Service name & description.
private const string ServiceName = "PaletteInsightAgent";
private const string ServiceDisplayname = "PaletteInsightAgent";
private const string ServiceDescription = "Tableau Server performance monitor";
// Service recovery attempt timings, in minutes.
private const int RecoveryFirstAttempt = 0;
private const int RecoverySecondAttempt = 1;
private const int RecoveryThirdAttempt = 5;
// Service recovery reset period, in days.
private const int RecoveryResetPeriod = 1;
/// <summary>
/// Main entry point for the service layer.
/// </summary>
public static void Main()
{
// configure service parameters
HostFactory.Run(hostConfigurator =>
{
hostConfigurator.SetServiceName(ServiceName);
hostConfigurator.SetDescription(ServiceDescription);
hostConfigurator.SetDisplayName(ServiceDisplayname);
hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper());
hostConfigurator.RunAsLocalSystem();
hostConfigurator.StartAutomaticallyDelayed();
hostConfigurator.UseNLog();
hostConfigurator.EnableServiceRecovery(r =>
{
r.RestartService(RecoveryFirstAttempt);
r.RestartService(RecoverySecondAttempt);
r.RestartService(RecoveryThirdAttempt);
r.OnCrashOnly();
r.SetResetPeriod(RecoveryResetPeriod);
});
});
}
}
} | using Topshelf;
namespace PaletteInsightAgentService
{
/// <summary>
/// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us.
/// </summary>
internal class PaletteInsightAgentService
{
// Service name & description.
private const string ServiceName = "PaletteInsightAgent";
private const string ServiceDisplayname = "Palette Insight Agent";
private const string ServiceDescription = "Tableau Server performance monitor";
// Service recovery attempt timings, in minutes.
private const int RecoveryFirstAttempt = 0;
private const int RecoverySecondAttempt = 1;
private const int RecoveryThirdAttempt = 5;
// Service recovery reset period, in days.
private const int RecoveryResetPeriod = 1;
/// <summary>
/// Main entry point for the service layer.
/// </summary>
public static void Main()
{
// configure service parameters
HostFactory.Run(hostConfigurator =>
{
hostConfigurator.SetServiceName(ServiceName);
hostConfigurator.SetDescription(ServiceDescription);
hostConfigurator.SetDisplayName(ServiceDisplayname);
hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper());
hostConfigurator.RunAsLocalSystem();
hostConfigurator.StartAutomaticallyDelayed();
hostConfigurator.UseNLog();
hostConfigurator.EnableServiceRecovery(r =>
{
r.RestartService(RecoveryFirstAttempt);
r.RestartService(RecoverySecondAttempt);
r.RestartService(RecoveryThirdAttempt);
r.OnCrashOnly();
r.SetResetPeriod(RecoveryResetPeriod);
});
});
}
}
} |
Fix for buildtypeid case mismatch | using System.Linq;
using System.Text;
using TeamCitySharp;
using TeamCitySharp.Locators;
namespace DTMF.Logic
{
public class TeamCity
{
public static bool IsRunning(StringBuilder sb, string appName)
{
//remove prefix and suffixes from app names so same app can go to multiple places
appName = appName.Replace(".Production", "");
appName = appName.Replace(".Development", "");
appName = appName.Replace(".Staging", "");
appName = appName.Replace(".Test", "");
//skip if not configured
if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false;
//Check for running builds
var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]);
client.ConnectAsGuest();
var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds());
if (builds.Any(f=>f.BuildTypeId.Contains(appName)))
{
Utilities.AppendAndSend(sb, "Build in progress. Sync disabled");
//foreach (var build in builds)
//{
// Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>");
//}
return true;
}
return false;
}
}
} | using System.Linq;
using System.Text;
using TeamCitySharp;
using TeamCitySharp.Locators;
namespace DTMF.Logic
{
public class TeamCity
{
public static bool IsRunning(StringBuilder sb, string appName)
{
//remove prefix and suffixes from app names so same app can go to multiple places
appName = appName.Replace(".Production", "");
appName = appName.Replace(".Development", "");
appName = appName.Replace(".Staging", "");
appName = appName.Replace(".Test", "");
//skip if not configured
if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false;
//Check for running builds
var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]);
client.ConnectAsGuest();
var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds());
if (builds.Any(f=>f.BuildTypeId.ToLower().Contains(appName.ToLower())))
{
Utilities.AppendAndSend(sb, "Build in progress. Sync disabled");
//foreach (var build in builds)
//{
// Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>");
//}
return true;
}
return false;
}
}
} |
Add `AssemblyCompany`, `AssemblyCopyright` and `AssemblyProduct` attributes to the assembly. | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: NeutralResourcesLanguage("en-us")] | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: NeutralResourcesLanguage("en-us")]
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyProduct("Microsoft ASP.NET Core")] |
Replace Xna's Clamp method with our own. | using System;
namespace ChamberLib
{
public static class MathHelper
{
public static int RoundToInt(this float x)
{
return (int)Math.Round(x);
}
public static float ToRadians(this float degrees)
{
return degrees * 0.01745329251994f; // pi / 180
}
public static float ToDegrees( this float radians)
{
return radians * 57.2957795130823f; // 180 / pi
}
public static float Clamp(this float value, float min, float max)
{
return Math.Max(Math.Min(value, max), min);
}
}
}
| using System;
namespace ChamberLib
{
public static class MathHelper
{
public static int RoundToInt(this float x)
{
return (int)Math.Round(x);
}
public static float ToRadians(this float degrees)
{
return degrees * 0.01745329251994f; // pi / 180
}
public static float ToDegrees( this float radians)
{
return radians * 57.2957795130823f; // 180 / pi
}
public static float Clamp(this float value, float min, float max)
{
if (value > max)
return max;
if (value < min)
return min;
return value;
}
}
}
|
Fix Zap mod dedicated server. | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2009, mEthLab Interactive
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Package overrides to initialize the mod.
package Zap {
function displayHelp()
{
Parent::displayHelp();
}
function parseArgs()
{
Parent::parseArgs();
}
function onStart()
{
Parent::onStart();
echo("\n--------- Initializing MOD: Zap ---------");
exec("./server.cs");
}
function onExit()
{
Parent::onExit();
}
}; // package Zap
activatePackage(Zap);
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2009, mEthLab Interactive
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Package overrides to initialize the mod.
package Zap {
function displayHelp()
{
Parent::displayHelp();
}
function parseArgs()
{
Parent::parseArgs();
}
function onStart()
{
echo("\n--------- Initializing MOD: Zap ---------");
exec("./server.cs");
Parent::onStart();
}
function onExit()
{
Parent::onExit();
}
}; // package Zap
activatePackage(Zap);
|
Use DomainCustomization rather than AutoMoqCustomization directly | using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Xunit;
namespace AppHarbor.Tests
{
public class AutoCommandDataAttribute : AutoDataAttribute
{
public AutoCommandDataAttribute()
: base(new Fixture().Customize(new AutoMoqCustomization()))
{
}
}
}
| using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Xunit;
namespace AppHarbor.Tests
{
public class AutoCommandDataAttribute : AutoDataAttribute
{
public AutoCommandDataAttribute()
: base(new Fixture().Customize(new DomainCustomization()))
{
}
}
}
|
Fix SliderTest.SlideHorizontally on Win 10 | namespace Gu.Wpf.UiAutomation
{
using System.Windows.Automation;
public class Thumb : UiElement
{
public Thumb(AutomationElement automationElement)
: base(automationElement)
{
}
public TransformPattern TransformPattern => this.AutomationElement.TransformPattern();
/// <summary>
/// Moves the slider horizontally.
/// </summary>
/// <param name="distance">+ for right, - for left.</param>
public void SlideHorizontally(int distance)
{
Mouse.DragHorizontally(MouseButton.Left, this.Bounds.Center(), distance);
}
/// <summary>
/// Moves the slider vertically.
/// </summary>
/// <param name="distance">+ for down, - for up.</param>
public void SlideVertically(int distance)
{
Mouse.DragVertically(MouseButton.Left, this.Bounds.Center(), distance);
}
}
}
| namespace Gu.Wpf.UiAutomation
{
using System.Windows;
using System.Windows.Automation;
public class Thumb : UiElement
{
private const int DragSpeed = 500;
public Thumb(AutomationElement automationElement)
: base(automationElement)
{
}
public TransformPattern TransformPattern => this.AutomationElement.TransformPattern();
/// <summary>
/// Moves the slider horizontally.
/// </summary>
/// <param name="distance">+ for right, - for left.</param>
public void SlideHorizontally(int distance)
{
var cp = this.GetClickablePoint();
Mouse.Drag(MouseButton.Left, cp, cp + new Vector(distance, 0), DragSpeed);
Wait.UntilInputIsProcessed();
}
/// <summary>
/// Moves the slider vertically.
/// </summary>
/// <param name="distance">+ for down, - for up.</param>
public void SlideVertically(int distance)
{
var cp = this.GetClickablePoint();
Mouse.Drag(MouseButton.Left, cp, cp + new Vector(0, distance), DragSpeed);
Wait.UntilInputIsProcessed();
}
}
}
|
Use less confusing placeholder icon for YAML | using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.Settings;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Resources;
using JetBrains.ReSharper.Psi.Parsing;
using JetBrains.Text;
using JetBrains.UI.Icons;
namespace JetBrains.ReSharper.Plugins.Yaml.Psi
{
[ProjectFileType(typeof(YamlProjectFileType))]
public class YamlProjectFileLanguageService : ProjectFileLanguageService
{
private readonly YamlSupport myYamlSupport;
public YamlProjectFileLanguageService(YamlSupport yamlSupport)
: base(YamlProjectFileType.Instance)
{
myYamlSupport = yamlSupport;
}
public override ILexerFactory GetMixedLexerFactory(ISolution solution, IBuffer buffer, IPsiSourceFile sourceFile = null)
{
var languageService = YamlLanguage.Instance.LanguageService();
return languageService?.GetPrimaryLexerFactory();
}
protected override PsiLanguageType PsiLanguageType
{
get
{
var yamlLanguage = (PsiLanguageType) YamlLanguage.Instance ?? UnknownLanguage.Instance;
return myYamlSupport.IsParsingEnabled.Value ? yamlLanguage : UnknownLanguage.Instance;
}
}
// TODO: Proper icon!
public override IconId Icon => PsiCSharpThemedIcons.Csharp.Id;
}
} | using JetBrains.Application.UI.Icons.Special.ThemedIcons;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
using JetBrains.ReSharper.Plugins.Yaml.Settings;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Parsing;
using JetBrains.Text;
using JetBrains.UI.Icons;
namespace JetBrains.ReSharper.Plugins.Yaml.Psi
{
[ProjectFileType(typeof(YamlProjectFileType))]
public class YamlProjectFileLanguageService : ProjectFileLanguageService
{
private readonly YamlSupport myYamlSupport;
public YamlProjectFileLanguageService(YamlSupport yamlSupport)
: base(YamlProjectFileType.Instance)
{
myYamlSupport = yamlSupport;
}
public override ILexerFactory GetMixedLexerFactory(ISolution solution, IBuffer buffer, IPsiSourceFile sourceFile = null)
{
var languageService = YamlLanguage.Instance.LanguageService();
return languageService?.GetPrimaryLexerFactory();
}
protected override PsiLanguageType PsiLanguageType
{
get
{
var yamlLanguage = (PsiLanguageType) YamlLanguage.Instance ?? UnknownLanguage.Instance;
return myYamlSupport.IsParsingEnabled.Value ? yamlLanguage : UnknownLanguage.Instance;
}
}
// TODO: Proper icon!
public override IconId Icon => SpecialThemedIcons.Placeholder.Id;
}
} |
Add registration options for definition request | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class DefinitionRequest
{
public static readonly
RequestType<TextDocumentPosition, Location[], object, object> Type =
RequestType<TextDocumentPosition, Location[], object, object>.Create("textDocument/definition");
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class DefinitionRequest
{
public static readonly
RequestType<TextDocumentPosition, Location[], object, TextDocumentRegistrationOptions> Type =
RequestType<TextDocumentPosition, Location[], object, TextDocumentRegistrationOptions>.Create("textDocument/definition");
}
}
|
Fix having the wrong Index name in migration CuratedFeedPackageUniqueness.Down() | namespace NuGetGallery.Migrations
{
using System.Data.Entity.Migrations;
public partial class CuratedFeedPackageUniqueness : DbMigration
{
public override void Up()
{
// ADD uniqueness constraint - as an Index, since it seems reasonable to look up curated package entries by their feed + registration
CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration");
}
public override void Down()
{
// REMOVE uniqueness constraint
DropIndex("CuratedPackages", "IX_CuratedPackage_CuratedFeedAndPackageRegistration");
}
}
}
| namespace NuGetGallery.Migrations
{
using System.Data.Entity.Migrations;
public partial class CuratedFeedPackageUniqueness : DbMigration
{
public override void Up()
{
// ADD uniqueness constraint - as an Index, since it seems reasonable to look up curated package entries by their feed + registration
CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration");
}
public override void Down()
{
// REMOVE uniqueness constraint
DropIndex("CuratedPackages", "IX_CuratedFeed_PackageRegistration");
}
}
}
|
Add an implementation IEqualityComparer<Type> to ensure the .Distinct call in the Locate() method works as expected. | using System;
using System.Linq;
using System.Reflection;
using Mongo.Migration.Extensions;
using Mongo.Migration.Migrations.Adapters;
namespace Mongo.Migration.Migrations.Locators
{
internal class TypeMigrationDependencyLocator<TMigrationType> : MigrationLocator<TMigrationType>
where TMigrationType: class, IMigration
{
private readonly IContainerProvider _containerProvider;
public TypeMigrationDependencyLocator(IContainerProvider containerProvider)
{
_containerProvider = containerProvider;
}
public override void Locate()
{
var migrationTypes =
(from assembly in Assemblies
from type in assembly.GetTypes()
where typeof(TMigrationType).IsAssignableFrom(type) && !type.IsAbstract
select type).Distinct();
Migrations = migrationTypes.Select(GetMigrationInstance).ToMigrationDictionary();
}
private TMigrationType GetMigrationInstance(Type type)
{
ConstructorInfo constructor = type.GetConstructors()[0];
if(constructor != null)
{
object[] args = constructor
.GetParameters()
.Select(o => o.ParameterType)
.Select(o => _containerProvider.GetInstance(o))
.ToArray();
return Activator.CreateInstance(type, args) as TMigrationType;
}
return Activator.CreateInstance(type) as TMigrationType;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Mongo.Migration.Extensions;
using Mongo.Migration.Migrations.Adapters;
namespace Mongo.Migration.Migrations.Locators
{
internal class TypeMigrationDependencyLocator<TMigrationType> : MigrationLocator<TMigrationType>
where TMigrationType: class, IMigration
{
private class TypeComparer : IEqualityComparer<Type>
{
public bool Equals(Type x, Type y)
{
return x.AssemblyQualifiedName == y.AssemblyQualifiedName;
}
public int GetHashCode(Type obj)
{
return obj.AssemblyQualifiedName.GetHashCode();
}
}
private readonly IContainerProvider _containerProvider;
public TypeMigrationDependencyLocator(IContainerProvider containerProvider)
{
_containerProvider = containerProvider;
}
public override void Locate()
{
var migrationTypes =
(from assembly in Assemblies
from type in assembly.GetTypes()
where typeof(TMigrationType).IsAssignableFrom(type) && !type.IsAbstract
select type).Distinct(new TypeComparer());
Migrations = migrationTypes.Select(GetMigrationInstance).ToMigrationDictionary();
}
private TMigrationType GetMigrationInstance(Type type)
{
ConstructorInfo constructor = type.GetConstructors()[0];
if(constructor != null)
{
object[] args = constructor
.GetParameters()
.Select(o => o.ParameterType)
.Select(o => _containerProvider.GetInstance(o))
.ToArray();
return Activator.CreateInstance(type, args) as TMigrationType;
}
return Activator.CreateInstance(type) as TMigrationType;
}
}
} |
Fix bug where prop was not serialized | using System;
using OpenStardriveServer.Domain.Systems.Standard;
namespace OpenStardriveServer.Domain.Systems.Propulsion.Engines;
public record EnginesState : StandardSystemBaseState
{
public int CurrentSpeed { get; init; }
public EngineSpeedConfig SpeedConfig { get; init; }
public int CurrentHeat { get; init; }
public EngineHeatConfig HeatConfig { get; init; }
public SpeedPowerRequirement[] SpeedPowerRequirements = Array.Empty<SpeedPowerRequirement>();
}
public record EngineSpeedConfig
{
public int MaxSpeed { get; init; }
public int CruisingSpeed { get; init; }
}
public record EngineHeatConfig
{
public int PoweredHeat { get; init; }
public int CruisingHeat { get; init; }
public int MaxHeat { get; init; }
public int MinutesAtMaxSpeed { get; init; }
public int MinutesToCoolDown { get; init; }
}
public record SpeedPowerRequirement
{
public int Speed { get; init; }
public int PowerNeeded { get; init; }
} | using System;
using OpenStardriveServer.Domain.Systems.Standard;
namespace OpenStardriveServer.Domain.Systems.Propulsion.Engines;
public record EnginesState : StandardSystemBaseState
{
public int CurrentSpeed { get; init; }
public EngineSpeedConfig SpeedConfig { get; init; }
public int CurrentHeat { get; init; }
public EngineHeatConfig HeatConfig { get; init; }
public SpeedPowerRequirement[] SpeedPowerRequirements { get; init; } = Array.Empty<SpeedPowerRequirement>();
}
public record EngineSpeedConfig
{
public int MaxSpeed { get; init; }
public int CruisingSpeed { get; init; }
}
public record EngineHeatConfig
{
public int PoweredHeat { get; init; }
public int CruisingHeat { get; init; }
public int MaxHeat { get; init; }
public int MinutesAtMaxSpeed { get; init; }
public int MinutesToCoolDown { get; init; }
}
public record SpeedPowerRequirement
{
public int Speed { get; init; }
public int PowerNeeded { get; init; }
} |
Add overloads to exception to take in the Reason | using System;
namespace RapidCore.Locking
{
public class DistributedAppLockException : Exception
{
public DistributedAppLockException()
{
}
public DistributedAppLockException(string message)
: base(message)
{
}
public DistributedAppLockException(string message, Exception inner)
: base(message, inner)
{
}
public DistributedAppLockExceptionReason Reason { get; set; }
}
} | using System;
namespace RapidCore.Locking
{
public class DistributedAppLockException : Exception
{
public DistributedAppLockException()
{
}
public DistributedAppLockException(string message)
: base(message)
{
}
public DistributedAppLockException(string message, DistributedAppLockExceptionReason reason)
: base(message)
{
Reason = reason;
}
public DistributedAppLockException(string message, Exception inner)
: base(message, inner)
{
}
public DistributedAppLockException(string message, Exception inner, DistributedAppLockExceptionReason reason)
: base(message, inner)
{
Reason = reason;
}
public DistributedAppLockExceptionReason Reason { get; set; }
}
} |
Use floats across the camera calculations /2 > 0.5f | using UnityEngine;
namespace HoloToolkit.Unity
{
public static class CameraExtensions
{
/// <summary>
/// Get the horizontal FOV from the stereo camera
/// </summary>
/// <returns></returns>
public static float GetHorizontalFieldOfViewRadians(this Camera camera)
{
float horizontalFovRadians = 2 * Mathf.Atan(Mathf.Tan((camera.fieldOfView * Mathf.Deg2Rad) / 2) * camera.aspect);
return horizontalFovRadians;
}
/// <summary>
/// Returns if a point will be rendered on the screen in either eye
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public static bool IsInFOV(this Camera camera, Vector3 position)
{
float verticalFovHalf = camera.fieldOfView / 2;
float horizontalFovHalf = camera.GetHorizontalFieldOfViewRadians() * Mathf.Rad2Deg / 2;
Vector3 deltaPos = position - camera.transform.position;
Vector3 headDeltaPos = MathUtils.TransformDirectionFromTo(null, camera.transform, deltaPos).normalized;
float yaw = Mathf.Asin(headDeltaPos.x) * Mathf.Rad2Deg;
float pitch = Mathf.Asin(headDeltaPos.y) * Mathf.Rad2Deg;
return (Mathf.Abs(yaw) < horizontalFovHalf && Mathf.Abs(pitch) < verticalFovHalf);
}
}
} | using UnityEngine;
namespace HoloToolkit.Unity
{
public static class CameraExtensions
{
/// <summary>
/// Get the horizontal FOV from the stereo camera
/// </summary>
/// <returns></returns>
public static float GetHorizontalFieldOfViewRadians(this Camera camera)
{
float horizontalFovRadians = 2f * Mathf.Atan(Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad * 0.5f) * camera.aspect);
return horizontalFovRadians;
}
/// <summary>
/// Returns if a point will be rendered on the screen in either eye
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public static bool IsInFOV(this Camera camera, Vector3 position)
{
float verticalFovHalf = camera.fieldOfView * 0.5f;
float horizontalFovHalf = camera.GetHorizontalFieldOfViewRadians() * Mathf.Rad2Deg * 0.5f;
Vector3 deltaPos = position - camera.transform.position;
Vector3 headDeltaPos = MathUtils.TransformDirectionFromTo(null, camera.transform, deltaPos).normalized;
float yaw = Mathf.Asin(headDeltaPos.x) * Mathf.Rad2Deg;
float pitch = Mathf.Asin(headDeltaPos.y) * Mathf.Rad2Deg;
return (Mathf.Abs(yaw) < horizontalFovHalf && Mathf.Abs(pitch) < verticalFovHalf);
}
}
} |
Fix Dictionary type to be more useful | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace compiler.middleend.ir
{
class ParseResult
{
public Operand Operand { get; set; }
public List<Instruction> Instructions { get; set; }
public Dictionary<SsaVariable, Instruction> VarTable { get; set; }
public ParseResult()
{
Operand = null;
Instructions = null;
VarTable = new Dictionary<SsaVariable, Instruction>();
}
public ParseResult(Dictionary<SsaVariable, Instruction> symTble )
{
Operand = null;
Instructions = null;
VarTable = new Dictionary<SsaVariable, Instruction>(symTble);
}
public ParseResult(Operand pOperand, List<Instruction> pInstructions, Dictionary<SsaVariable, Instruction> pSymTble)
{
Operand = pOperand;
Instructions = new List<Instruction>(pInstructions);
VarTable = new Dictionary<SsaVariable, Instruction>(pSymTble);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace compiler.middleend.ir
{
class ParseResult
{
public Operand Operand { get; set; }
public List<Instruction> Instructions { get; set; }
public Dictionary<int, SsaVariable> VarTable { get; set; }
public ParseResult()
{
Operand = null;
Instructions = null;
VarTable = new Dictionary<int, SsaVariable>();
}
public ParseResult(Dictionary<int, SsaVariable> symTble )
{
Operand = null;
Instructions = null;
VarTable = new Dictionary<int, SsaVariable>(symTble);
}
public ParseResult(Operand pOperand, List<Instruction> pInstructions, Dictionary<int, SsaVariable> pSymTble)
{
Operand = pOperand;
Instructions = new List<Instruction>(pInstructions);
VarTable = new Dictionary<int, SsaVariable>(pSymTble);
}
}
}
|
Fix random power use when cooldown | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PowerRandom : BaseSpecialPower {
[SerializeField] private List<BaseSpecialPower> powers;
private BaseSpecialPower activePower = null;
protected override void Start() {
base.Start();
activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower;
}
protected override void Activate() {
StartCoroutine(WaitForDestroy());
}
protected override void Update() {
if(activePower.mana > 0) {
base.Update();
}
}
IEnumerator WaitForDestroy() {
yield return null;
while(activePower.coolDownTimer > 0) {
yield return null;
}
float currentMana = activePower.mana;
DestroyImmediate(activePower.gameObject);
activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower;
yield return null;
activePower.mana = currentMana;
yield return null;
EventDispatcher.DispatchEvent(Events.SPECIAL_POWER_USED, activePower); //to activate the UI
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PowerRandom : BaseSpecialPower {
[SerializeField] private List<BaseSpecialPower> powers;
private BaseSpecialPower activePower = null;
protected override void Start() {
base.Start();
activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower;
}
protected override void Activate() {
if(activePower.coolDownTimer <= 0)
StartCoroutine(WaitForDestroy());
}
protected override void Update() {
if(activePower.mana > 0) {
base.Update();
}
}
IEnumerator WaitForDestroy() {
yield return null;
while(activePower.coolDownTimer > 0) {
yield return null;
}
float currentMana = activePower.mana;
Debug.Log(currentMana);
DestroyImmediate(activePower.gameObject);
activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower;
yield return null;
activePower.mana = currentMana;
yield return null;
EventDispatcher.DispatchEvent(Events.SPECIAL_POWER_USED, activePower); //to activate the UI
}
}
|
Improve ToString when Id is null | using System.Collections.Generic;
using System.Xml.Linq;
using JetBrains.Annotations;
namespace Dasher.Schemata
{
public interface IWriteSchema
{
/// <summary>
/// Creates a deep copy of this schema within <paramref name="collection"/>.
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
IWriteSchema CopyTo(SchemaCollection collection);
}
public interface IReadSchema
{
bool CanReadFrom(IWriteSchema writeSchema, bool strict);
/// <summary>
/// Creates a deep copy of this schema within <paramref name="collection"/>.
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
IReadSchema CopyTo(SchemaCollection collection);
}
public abstract class Schema
{
internal abstract IEnumerable<Schema> Children { get; }
public override bool Equals(object obj)
{
var other = obj as Schema;
return other != null && Equals(other);
}
public abstract bool Equals(Schema other);
public override int GetHashCode() => ComputeHashCode();
protected abstract int ComputeHashCode();
}
/// <summary>For complex, union and enum.</summary>
public abstract class ByRefSchema : Schema
{
[CanBeNull]
internal string Id { get; set; }
internal abstract XElement ToXml();
public override string ToString() => Id;
}
/// <summary>For primitive, nullable, list, dictionary, tuple, empty.</summary>
public abstract class ByValueSchema : Schema
{
internal abstract string MarkupValue { get; }
public override string ToString() => MarkupValue;
}
} | using System.Collections.Generic;
using System.Xml.Linq;
using JetBrains.Annotations;
namespace Dasher.Schemata
{
public interface IWriteSchema
{
/// <summary>
/// Creates a deep copy of this schema within <paramref name="collection"/>.
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
IWriteSchema CopyTo(SchemaCollection collection);
}
public interface IReadSchema
{
bool CanReadFrom(IWriteSchema writeSchema, bool strict);
/// <summary>
/// Creates a deep copy of this schema within <paramref name="collection"/>.
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
IReadSchema CopyTo(SchemaCollection collection);
}
public abstract class Schema
{
internal abstract IEnumerable<Schema> Children { get; }
public override bool Equals(object obj)
{
var other = obj as Schema;
return other != null && Equals(other);
}
public abstract bool Equals(Schema other);
public override int GetHashCode() => ComputeHashCode();
protected abstract int ComputeHashCode();
}
/// <summary>For complex, union and enum.</summary>
public abstract class ByRefSchema : Schema
{
[CanBeNull]
internal string Id { get; set; }
internal abstract XElement ToXml();
public override string ToString() => Id ?? GetType().Name;
}
/// <summary>For primitive, nullable, list, dictionary, tuple, empty.</summary>
public abstract class ByValueSchema : Schema
{
internal abstract string MarkupValue { get; }
public override string ToString() => MarkupValue;
}
} |
Support full range of comparison operators instead of IndexOf | namespace Sitecore.SharedSource.MobileDeviceDetector.Rules.Conditions
{
using System;
using System.Web;
using Sitecore.Diagnostics;
using Sitecore.Rules;
using Sitecore.Rules.Conditions;
/// <summary>
/// UserAgentCondition
/// </summary>
/// <typeparam name="T"></typeparam>
public class UserAgentCondition<T> : StringOperatorCondition<T> where T : RuleContext
{
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public string Value { get; set; }
/// <summary>
/// Executes the specified rule context.
/// </summary>
/// <param name="ruleContext">The rule context.</param>
/// <returns>Returns value indicating whether Device UserAgent matches Value or not</returns>
protected override bool Execute(T ruleContext)
{
Assert.ArgumentNotNull(ruleContext, "ruleContext");
string str = this.Value ?? string.Empty;
var userAgent = HttpContext.Current.Request.UserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
return userAgent.IndexOf(str, StringComparison.OrdinalIgnoreCase) >= 0;
}
return false;
}
}
}
| namespace Sitecore.SharedSource.MobileDeviceDetector.Rules.Conditions
{
using System;
using System.Web;
using Sitecore.Diagnostics;
using Sitecore.Rules;
using Sitecore.Rules.Conditions;
/// <summary>
/// UserAgentCondition
/// </summary>
/// <typeparam name="T"></typeparam>
public class UserAgentCondition<T> : StringOperatorCondition<T> where T : RuleContext
{
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public string Value { get; set; }
/// <summary>
/// Executes the specified rule context.
/// </summary>
/// <param name="ruleContext">The rule context.</param>
/// <returns>Returns value indicating whether Device UserAgent matches Value or not</returns>
protected override bool Execute(T ruleContext)
{
Assert.ArgumentNotNull(ruleContext, "ruleContext");
string str = this.Value ?? string.Empty;
var userAgent = HttpContext.Current.Request.UserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
return Compare(str, userAgent);
}
return false;
}
}
}
|
Revert "Rewrite folder write permission check to hopefully make it more reliable" | using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
namespace TweetDck.Core.Utils{
static class WindowsUtils{
public static bool CheckFolderPermission(string path, FileSystemRights right){
try{
AuthorizationRuleCollection collection = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(NTAccount));
foreach(FileSystemAccessRule rule in collection){
if ((rule.FileSystemRights & right) == right){
return true;
}
}
return false;
}
catch{
return false;
}
}
public static Process StartProcess(string file, string arguments, bool runElevated){
ProcessStartInfo processInfo = new ProcessStartInfo{
FileName = file,
Arguments = arguments
};
if (runElevated){
processInfo.Verb = "runas";
}
return Process.Start(processInfo);
}
}
}
| using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
namespace TweetDck.Core.Utils{
static class WindowsUtils{
public static bool CheckFolderPermission(string path, FileSystemRights right){
try{
AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity.Groups == null){
return false;
}
bool accessAllow = false, accessDeny = false;
foreach(FileSystemAccessRule rule in rules.Cast<FileSystemAccessRule>().Where(rule => identity.Groups.Contains(rule.IdentityReference) && (right & rule.FileSystemRights) == right)){
switch(rule.AccessControlType){
case AccessControlType.Allow: accessAllow = true; break;
case AccessControlType.Deny: accessDeny = true; break;
}
}
return accessAllow && !accessDeny;
}
catch{
return false;
}
}
public static Process StartProcess(string file, string arguments, bool runElevated){
ProcessStartInfo processInfo = new ProcessStartInfo{
FileName = file,
Arguments = arguments
};
if (runElevated){
processInfo.Verb = "runas";
}
return Process.Start(processInfo);
}
}
}
|
Fix typo in OnboardingRead and add SettlementsRead | namespace Mollie.Api.Models.Connect {
public static class AppPermissions {
public const string PaymentsRead = "payments.read";
public const string PaymentsWrite = "payments.write";
public const string RefundsRead = "refunds.read";
public const string RefundsWrite = "refunds.write";
public const string CustomersRead = "customers.read";
public const string CustomersWrite = "customers.write";
public const string MandatesRead = "mandates.read";
public const string MandatesWrite = "mandates.write";
public const string SubscriptionsRead = "subscriptions.read";
public const string SubscriptionsWrite = "subscriptions.write";
public const string ProfilesRead = "profiles.read";
public const string ProfilesWrite = "profiles.write";
public const string InvoicesRead = "invoices.read";
public const string OrdersRead = "orders.read";
public const string OrdersWrite = "orders.write";
public const string ShipmentsRead = "shipments.read";
public const string ShipmentsWrite = "shipments.write";
public const string OrganizationRead = "organizations.read";
public const string OrganizationWrite = "organizations.write";
public const string OnboardingRead = "onboarding.write";
public const string OnboardingWrite = "onboarding.write";
}
}
| namespace Mollie.Api.Models.Connect {
public static class AppPermissions {
public const string PaymentsRead = "payments.read";
public const string PaymentsWrite = "payments.write";
public const string RefundsRead = "refunds.read";
public const string RefundsWrite = "refunds.write";
public const string CustomersRead = "customers.read";
public const string CustomersWrite = "customers.write";
public const string MandatesRead = "mandates.read";
public const string MandatesWrite = "mandates.write";
public const string SubscriptionsRead = "subscriptions.read";
public const string SubscriptionsWrite = "subscriptions.write";
public const string ProfilesRead = "profiles.read";
public const string ProfilesWrite = "profiles.write";
public const string InvoicesRead = "invoices.read";
public const string OrdersRead = "orders.read";
public const string OrdersWrite = "orders.write";
public const string ShipmentsRead = "shipments.read";
public const string ShipmentsWrite = "shipments.write";
public const string OrganizationRead = "organizations.read";
public const string OrganizationWrite = "organizations.write";
public const string OnboardingRead = "onboarding.read";
public const string OnboardingWrite = "onboarding.write";
public const string SettlementsRead = "settlements.read";
}
}
|
Add warning message to ensure user is running the Azure Emulator | namespace Endjin.Cancelable.Demo
{
#region Using Directives
using System;
using System.Threading;
using System.Threading.Tasks;
using Endjin.Contracts;
using Endjin.Core.Composition;
using Endjin.Core.Container;
#endregion
public class Program
{
public static void Main(string[] args)
{
ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait();
var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>();
var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045";
cancelable.CreateToken(cancellationToken);
cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait();
Console.WriteLine("Press Any Key to Exit!");
Console.ReadKey();
}
private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken)
{
int counter = 0;
while (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T"));
await Task.Delay(TimeSpan.FromSeconds(1));
counter++;
if (counter == 15)
{
Console.WriteLine("Long Running Process Ran to Completion!");
break;
}
}
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Long Running Process was Cancelled!");
}
}
}
} | namespace Endjin.Cancelable.Demo
{
#region Using Directives
using System;
using System.Threading;
using System.Threading.Tasks;
using Endjin.Contracts;
using Endjin.Core.Composition;
using Endjin.Core.Container;
#endregion
public class Program
{
public static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Ensure you are running the Azure Storage Emulator!");
Console.ResetColor();
ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait();
var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>();
var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045";
cancelable.CreateToken(cancellationToken);
cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait();
Console.WriteLine("Press Any Key to Exit!");
Console.ReadKey();
}
private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken)
{
int counter = 0;
while (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T"));
await Task.Delay(TimeSpan.FromSeconds(1));
counter++;
if (counter == 15)
{
Console.WriteLine("Long Running Process Ran to Completion!");
break;
}
}
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Long Running Process was Cancelled!");
}
}
}
} |
Add input param. logger and get test string from cmd line | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions;
using Microsoft.Azure.WebJobs.Host;
using OutgoingHttpRequestWebJobsExtension;
namespace ExtensionsSample
{
public static class Program
{
public static void Main(string[] args)
{
var config = new JobHostConfiguration();
config.UseDevelopmentSettings();
config.UseOutgoingHttpRequests();
var host = new JobHost(config);
var method = typeof(Program).GetMethod("MyCoolMethod");
host.Call(method);
}
public static void MyCoolMethod(
[OutgoingHttpRequest(@"http://requestb.in/19xvbmc1")] TextWriter writer)
{
writer.Write("Test sring sent to OutgoingHttpRequest!");
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using Microsoft.Azure.WebJobs;
using OutgoingHttpRequestWebJobsExtension;
namespace ExtensionsSample
{
public static class Program
{
public static void Main(string[] args)
{
string inputString = args.Length > 0 ? args[0] : "Some test string";
var config = new JobHostConfiguration();
config.UseDevelopmentSettings();
config.UseOutgoingHttpRequests();
var host = new JobHost(config);
var method = typeof(Program).GetMethod("MyCoolMethod");
host.Call(method, new Dictionary<string, object>
{
{"input", inputString }
});
}
public static void MyCoolMethod(
string input,
[OutgoingHttpRequest(@"http://requestb.in/19xvbmc1")] TextWriter writer,
TextWriter logger)
{
logger.Write(input);
writer.Write(input);
}
}
} |
Tweak skybox rotation direction and speed | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace ShiftDrive {
/// <summary>
/// Contains static utilities to render a skybox.
/// </summary>
internal static class Skybox {
private static float rotation;
private static bool idleRotation;
public static void SetIdleRotation(bool enabled) {
idleRotation = enabled;
}
public static void Draw(GraphicsDevice graphicsDevice) {
// Use the unlit shader to render a skybox.
Effect fx = Assets.fxUnlit; // shortcut
fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) *
Matrix.CreateLookAt(new Vector3(0f, -0.2f, 2f), new Vector3(0, 0, 0),
Vector3.Up) * SDGame.Inst.Projection);
fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]);
foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) {
foreach (ModelMeshPart part in mesh.MeshParts) {
part.Effect = fx;
}
fx.CurrentTechnique.Passes[0].Apply();
mesh.Draw();
}
}
public static void Update(GameTime gameTime) {
if (!idleRotation) return;
rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.05);
while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi;
}
}
}
| /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace ShiftDrive {
/// <summary>
/// Contains static utilities to render a skybox.
/// </summary>
internal static class Skybox {
private static float rotation;
private static bool idleRotation;
public static void SetIdleRotation(bool enabled) {
idleRotation = enabled;
}
public static void Draw(GraphicsDevice graphicsDevice) {
// Use the unlit shader to render a skybox.
Effect fx = Assets.fxUnlit; // shortcut
fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) * Matrix.CreateRotationZ(rotation) *
Matrix.CreateLookAt(new Vector3(0f, -0.25f, 2f), new Vector3(0, 0, 0),
Vector3.Up) * SDGame.Inst.Projection);
fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]);
foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) {
foreach (ModelMeshPart part in mesh.MeshParts) {
part.Effect = fx;
}
fx.CurrentTechnique.Passes[0].Apply();
mesh.Draw();
}
}
public static void Update(GameTime gameTime) {
if (!idleRotation) return;
rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.04);
while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi;
}
}
}
|
Update nullable annotations in Experiments folder | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists";
public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache";
}
}
| // 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.
#nullable enable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists";
public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache";
}
}
|
Throw a CommandException if no hostname is specified | using System;
namespace AppHarbor.Commands
{
public class AddHostnameCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
private readonly IAppHarborClient _appharborClient;
public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
{
_applicationConfiguration = applicationConfiguration;
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| using System;
namespace AppHarbor.Commands
{
public class AddHostnameCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
private readonly IAppHarborClient _appharborClient;
public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
{
_applicationConfiguration = applicationConfiguration;
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
if (arguments.Length == 0)
{
throw new CommandException("No hostname was specified");
}
throw new NotImplementedException();
}
}
}
|
Fix for wrong keys when using python binding | namespace Winium.Desktop.Driver.CommandExecutors
{
internal class SendKeysToElementExecutor : CommandExecutorBase
{
#region Methods
protected override string DoImpl()
{
var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString();
var text = this.ExecutedCommand.Parameters["value"].First.ToString();
var element = this.Automator.Elements.GetRegisteredElement(registeredKey);
element.SetText(text);
return this.JsonResponse();
}
#endregion
}
}
| namespace Winium.Desktop.Driver.CommandExecutors
{
internal class SendKeysToElementExecutor : CommandExecutorBase
{
#region Methods
protected override string DoImpl()
{
var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString();
var text = string.Join(string.Empty, this.ExecutedCommand.Parameters["value"]);
var element = this.Automator.Elements.GetRegisteredElement(registeredKey);
element.SetText(text);
return this.JsonResponse();
}
#endregion
}
}
|
Update RobotName name test to be more restrictive | using Xunit;
public class RobotNameTest
{
private readonly Robot robot = new Robot();
[Fact]
public void Robot_has_a_name()
{
Assert.Matches(@"[A-Z]{2}\d{3}", robot.Name);
}
[Fact(Skip = "Remove to run test")]
public void Name_is_the_same_each_time()
{
Assert.Equal(robot.Name, robot.Name);
}
[Fact(Skip = "Remove to run test")]
public void Different_robots_have_different_names()
{
var robot2 = new Robot();
Assert.NotEqual(robot2.Name, robot.Name);
}
[Fact(Skip = "Remove to run test")]
public void Can_reset_the_name()
{
var originalName = robot.Name;
robot.Reset();
Assert.NotEqual(originalName, robot.Name);
}
} | using Xunit;
public class RobotNameTest
{
private readonly Robot robot = new Robot();
[Fact]
public void Robot_has_a_name()
{
Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name);
}
[Fact(Skip = "Remove to run test")]
public void Name_is_the_same_each_time()
{
Assert.Equal(robot.Name, robot.Name);
}
[Fact(Skip = "Remove to run test")]
public void Different_robots_have_different_names()
{
var robot2 = new Robot();
Assert.NotEqual(robot2.Name, robot.Name);
}
[Fact(Skip = "Remove to run test")]
public void Can_reset_the_name()
{
var originalName = robot.Name;
robot.Reset();
Assert.NotEqual(originalName, robot.Name);
}
}
|
Fix bug in album gain calculation. | using System;
using System.Linq;
namespace NReplayGain
{
/// <summary>
/// Contains ReplayGain data for an album.
/// </summary>
public class AlbumGain
{
private GainData albumData;
public AlbumGain()
{
this.albumData = new GainData();
}
/// <summary>
/// After calculating the ReplayGain data for an album, call this to append the data to the album.
/// </summary>
public void AppendTrackData(TrackGain trackGain)
{
int[] sourceAccum = trackGain.gainData.Accum;
for (int i = 0; i < sourceAccum.Length; ++i)
{
this.albumData.Accum[i] = sourceAccum[i];
}
this.albumData.PeakSample = Math.Max(this.albumData.PeakSample, trackGain.gainData.PeakSample);
}
/// <summary>
/// Returns the normalization gain for the entire album in decibels.
/// </summary>
public double GetGain()
{
return ReplayGain.AnalyzeResult(this.albumData.Accum);
}
/// <summary>
/// Returns the peak album value, normalized to the [0,1] interval.
/// </summary>
public double GetPeak()
{
return this.albumData.PeakSample / ReplayGain.MAX_SAMPLE_VALUE;
}
}
}
| using System;
using System.Linq;
namespace NReplayGain
{
/// <summary>
/// Contains ReplayGain data for an album.
/// </summary>
public class AlbumGain
{
private GainData albumData;
public AlbumGain()
{
this.albumData = new GainData();
}
/// <summary>
/// After calculating the ReplayGain data for an album, call this to append the data to the album.
/// </summary>
public void AppendTrackData(TrackGain trackGain)
{
int[] sourceAccum = trackGain.gainData.Accum;
for (int i = 0; i < sourceAccum.Length; ++i)
{
this.albumData.Accum[i] += sourceAccum[i];
}
this.albumData.PeakSample = Math.Max(this.albumData.PeakSample, trackGain.gainData.PeakSample);
}
/// <summary>
/// Returns the normalization gain for the entire album in decibels.
/// </summary>
public double GetGain()
{
return ReplayGain.AnalyzeResult(this.albumData.Accum);
}
/// <summary>
/// Returns the peak album value, normalized to the [0,1] interval.
/// </summary>
public double GetPeak()
{
return this.albumData.PeakSample / ReplayGain.MAX_SAMPLE_VALUE;
}
}
}
|
Fix route matching for typed-in urls | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Routing;
namespace wwwplatform.Extensions
{
public class SitePageRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string path = httpContext.Request.Url.AbsolutePath;
string controller = path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First();
var controllers = Assembly.GetExecutingAssembly().DefinedTypes.Where(t => t.Name.EndsWith("Controller") && t.Name.StartsWith(controller));
return controllers.Count() == 0;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Routing;
namespace wwwplatform.Extensions
{
public class SitePageRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string path = httpContext.Request.Url.AbsolutePath;
string controller = path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First();
var controllers = Assembly.GetExecutingAssembly().DefinedTypes.Where(t => t.Name.EndsWith("Controller") && t.Name.StartsWith(controller, StringComparison.InvariantCultureIgnoreCase));
return controllers.Count() == 0;
}
}
}
|
Add a constructor that only requires messages. | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Qowaiv.ComponentModel
{
/// <summary>Represents a result of a validation, executed command, etcetera.</summary>
public class Result<T> : Result
{
/// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary>
/// <param name="data">
/// The data related to the result.
/// </param>
public Result(T data) : this(data, Enumerable.Empty<ValidationResult>()) { }
/// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary>
/// <param name="data">
/// The data related to the result.
/// </param>
/// <param name="messages">
/// The messages related to the result.
/// </param>
public Result(T data, IEnumerable<ValidationResult> messages) : base(messages)
{
Data = data;
}
/// <summary>Gets the data related to result.</summary>
public T Data { get; }
/// <summary>Implicitly casts the <see cref="Result"/> to the type of the related model.</summary>
public static implicit operator T(Result<T> result) => result == null ? default(T) : result.Data;
/// <summary>Implicitly casts a model to the <see cref="Result"/>.</summary>
public static explicit operator Result<T>(T model) => new Result<T>(model);
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Qowaiv.ComponentModel
{
/// <summary>Represents a result of a validation, executed command, etcetera.</summary>
public class Result<T> : Result
{
/// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary>
public Result(IEnumerable<ValidationResult> messages) : this(default(T), messages) { }
/// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary>
/// <param name="data">
/// The data related to the result.
/// </param>
public Result(T data) : this(data, Enumerable.Empty<ValidationResult>()) { }
/// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary>
/// <param name="data">
/// The data related to the result.
/// </param>
/// <param name="messages">
/// The messages related to the result.
/// </param>
public Result(T data, IEnumerable<ValidationResult> messages) : base(messages)
{
Data = data;
}
/// <summary>Gets the data related to result.</summary>
public T Data { get; }
/// <summary>Implicitly casts a model to the <see cref="Result"/>.</summary>
public static implicit operator Result<T>(T model) => new Result<T>(model);
/// <summary>Explicitly casts the <see cref="Result"/> to the type of the related model.</summary>
public static explicit operator T(Result<T> result) => result == null ? default(T) : result.Data;
}
}
|
Update break colour to not look like kiai time | // 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.Game.Beatmaps.Timing;
using osu.Game.Graphics;
using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// The part of the timeline that displays breaks in the song.
/// </summary>
public class BreakPart : TimelinePart
{
protected override void LoadBeatmap(EditorBeatmap beatmap)
{
base.LoadBeatmap(beatmap);
foreach (var breakPeriod in beatmap.Breaks)
Add(new BreakVisualisation(breakPeriod));
}
private class BreakVisualisation : DurationVisualisation
{
public BreakVisualisation(BreakPeriod breakPeriod)
: base(breakPeriod.StartTime, breakPeriod.EndTime)
{
}
[BackgroundDependencyLoader]
private void load(OsuColour colours) => Colour = colours.Yellow;
}
}
}
| // 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.Game.Beatmaps.Timing;
using osu.Game.Graphics;
using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// The part of the timeline that displays breaks in the song.
/// </summary>
public class BreakPart : TimelinePart
{
protected override void LoadBeatmap(EditorBeatmap beatmap)
{
base.LoadBeatmap(beatmap);
foreach (var breakPeriod in beatmap.Breaks)
Add(new BreakVisualisation(breakPeriod));
}
private class BreakVisualisation : DurationVisualisation
{
public BreakVisualisation(BreakPeriod breakPeriod)
: base(breakPeriod.StartTime, breakPeriod.EndTime)
{
}
[BackgroundDependencyLoader]
private void load(OsuColour colours) => Colour = colours.GreyCarmineLight;
}
}
}
|
Remove no longer necessary comment | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
namespace osu.Framework.Graphics.Shaders
{
/// <summary>
/// A mapping of a global uniform to many shaders which need to receive updates on a change.
/// </summary>
internal class UniformMapping<T> : IUniformMapping
where T : struct
{
public T Value;
public List<GlobalUniform<T>> LinkedUniforms = new List<GlobalUniform<T>>();
public string Name { get; }
public UniformMapping(string name)
{
Name = name;
}
public void LinkShaderUniform(IUniform uniform)
{
var typedUniform = (GlobalUniform<T>)uniform;
typedUniform.UpdateValue(this);
LinkedUniforms.Add(typedUniform);
}
public void UnlinkShaderUniform(IUniform uniform)
{
var typedUniform = (GlobalUniform<T>)uniform;
LinkedUniforms.Remove(typedUniform);
}
public void UpdateValue(ref T newValue)
{
Value = newValue;
// Iterate by index to remove an enumerator allocation
// ReSharper disable once ForCanBeConvertedToForeach
for (int i = 0; i < LinkedUniforms.Count; i++)
LinkedUniforms[i].UpdateValue(this);
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
namespace osu.Framework.Graphics.Shaders
{
/// <summary>
/// A mapping of a global uniform to many shaders which need to receive updates on a change.
/// </summary>
internal class UniformMapping<T> : IUniformMapping
where T : struct
{
public T Value;
public List<GlobalUniform<T>> LinkedUniforms = new List<GlobalUniform<T>>();
public string Name { get; }
public UniformMapping(string name)
{
Name = name;
}
public void LinkShaderUniform(IUniform uniform)
{
var typedUniform = (GlobalUniform<T>)uniform;
typedUniform.UpdateValue(this);
LinkedUniforms.Add(typedUniform);
}
public void UnlinkShaderUniform(IUniform uniform)
{
var typedUniform = (GlobalUniform<T>)uniform;
LinkedUniforms.Remove(typedUniform);
}
public void UpdateValue(ref T newValue)
{
Value = newValue;
for (int i = 0; i < LinkedUniforms.Count; i++)
LinkedUniforms[i].UpdateValue(this);
}
}
}
|
Document a promise to reintroduce the DocumentText get | // Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.HtmlBrowser
{
public interface IWebBrowser
{
bool CanGoBack { get; }
bool CanGoForward { get; }
string DocumentText { set; }
string DocumentTitle { get; }
bool Focused { get; }
bool IsBusy { get; }
bool IsWebBrowserContextMenuEnabled { get; set; }
string StatusText { get; }
Uri Url { get; set; }
bool GoBack();
bool GoForward();
void Navigate(string urlString);
void Navigate(Uri url);
void Refresh();
void Refresh(WebBrowserRefreshOption opt);
void Stop();
void ScrollLastElementIntoView();
object NativeBrowser { get; }
}
} | // Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.HtmlBrowser
{
public interface IWebBrowser
{
bool CanGoBack { get; }
bool CanGoForward { get; }
/// <summary>
/// Set of the DocumentText will load the given string content into the browser.
/// If a get for DocumentText proves necessary Jason promises to write the reflective
/// gecko implementation.
/// </summary>
string DocumentText { set; }
string DocumentTitle { get; }
bool Focused { get; }
bool IsBusy { get; }
bool IsWebBrowserContextMenuEnabled { get; set; }
string StatusText { get; }
Uri Url { get; set; }
bool GoBack();
bool GoForward();
void Navigate(string urlString);
void Navigate(Uri url);
void Refresh();
void Refresh(WebBrowserRefreshOption opt);
void Stop();
void ScrollLastElementIntoView();
object NativeBrowser { get; }
}
} |
Test coverage for viewing a simple type member conversion in a mapping plan | namespace AgileObjects.AgileMapper.UnitTests
{
using System.Collections.Generic;
using Shouldly;
using TestClasses;
using Xunit;
public class WhenViewingMappingPlans
{
[Fact]
public void ShouldIncludeASimpleTypeMemberMapping()
{
var plan = Mapper
.GetPlanFor<PublicField<string>>()
.ToANew<PublicProperty<string>>();
plan.ShouldContain("instance.Value = omc.Source.Value;");
}
[Fact]
public void ShouldIncludeAComplexTypeMemberMapping()
{
var plan = Mapper
.GetPlanFor<PersonViewModel>()
.ToANew<Person>();
plan.ShouldContain("instance.Name = omc.Source.Name;");
plan.ShouldContain("instance.Line1 = omc.Source.AddressLine1;");
}
[Fact]
public void ShouldIncludeASimpleTypeEnumerableMemberMapping()
{
var plan = Mapper
.GetPlanFor<PublicProperty<int[]>>()
.ToANew<PublicField<IEnumerable<int>>>();
plan.ShouldContain("omc.Source.ForEach");
plan.ShouldContain("instance.Add");
}
}
}
| namespace AgileObjects.AgileMapper.UnitTests
{
using System;
using System.Collections.Generic;
using Shouldly;
using TestClasses;
using Xunit;
public class WhenViewingMappingPlans
{
[Fact]
public void ShouldIncludeASimpleTypeMemberMapping()
{
var plan = Mapper
.GetPlanFor<PublicField<string>>()
.ToANew<PublicProperty<string>>();
plan.ShouldContain("instance.Value = omc.Source.Value;");
}
[Fact]
public void ShouldIncludeAComplexTypeMemberMapping()
{
var plan = Mapper
.GetPlanFor<PersonViewModel>()
.ToANew<Person>();
plan.ShouldContain("instance.Name = omc.Source.Name;");
plan.ShouldContain("instance.Line1 = omc.Source.AddressLine1;");
}
[Fact]
public void ShouldIncludeASimpleTypeEnumerableMemberMapping()
{
var plan = Mapper
.GetPlanFor<PublicProperty<int[]>>()
.ToANew<PublicField<IEnumerable<int>>>();
plan.ShouldContain("omc.Source.ForEach");
plan.ShouldContain("instance.Add");
}
[Fact]
public void ShouldIncludeASimpleTypeMemberConversion()
{
var plan = Mapper
.GetPlanFor<PublicProperty<Guid>>()
.ToANew<PublicField<string>>();
plan.ShouldContain("omc.Source.Value.ToString(");
}
}
}
|
Refactor to make steps of protocol clearer | using System;
namespace BitCommitment
{
/// <summary>
/// A class to perform bit commitment. It does not care what the input is; it's just a
/// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way
/// function method for committing bits
/// </summary>
public class BitCommitmentProvider
{
public byte[] AliceRandBytes1 { get; set; }
public byte[] AliceRandBytes2 { get; set; }
public byte[] AliceMessageBytesBytes { get; set; }
public BitCommitmentProvider(byte[] one, byte[] two, byte[] messageBytes)
{
AliceRandBytes1 = one;
AliceRandBytes2 = two;
AliceMessageBytesBytes = messageBytes;
}
public byte[] BitCommitMessage()
{
throw new NotImplementedException();
}
}
}
| using System;
namespace BitCommitment
{
/// <summary>
/// A class to perform bit commitment. It does not care what the input is; it's just a
/// facility for exchanging bit commitment messages. Based on Bruce Schneier's RandBytes1-way
/// function method for committing bits
/// </summary>
public class BitCommitmentProvider
{
public byte[] AliceRandBytes1 { get; set; }
public byte[] AliceRandBytes2 { get; set; }
public byte[] AliceBytesToCommitBytesToCommit { get; set; }
public BitCommitmentProvider(byte[] randBytes1,
byte[] randBytes2,
byte[] bytesToCommit)
{
AliceRandBytes1 = randBytes1;
AliceRandBytes2 = randBytes2;
AliceBytesToCommitBytesToCommit = bytesToCommit;
}
public byte[] BitCommitMessage()
{
throw new NotImplementedException();
}
}
}
|
Implement IParser on method syntax builder. | using System.Dynamic;
using BobTheBuilder.ArgumentStore;
namespace BobTheBuilder.Syntax
{
public class DynamicBuilder<T> : DynamicBuilderBase<T> where T: class
{
public DynamicBuilder(IArgumentStore argumentStore) : base(argumentStore) { }
public override bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result)
{
ParseMembersFromMethodName(binder, args);
result = this;
return true;
}
private void ParseMembersFromMethodName(InvokeMemberBinder binder, object[] args)
{
var memberName = binder.Name.Replace("With", "");
argumentStore.SetMemberNameAndValue(memberName, args[0]);
}
}
} | using System.Dynamic;
using BobTheBuilder.ArgumentStore;
namespace BobTheBuilder.Syntax
{
public class DynamicBuilder<T> : DynamicBuilderBase<T>, IParser where T: class
{
public DynamicBuilder(IArgumentStore argumentStore) : base(argumentStore) { }
public override bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result)
{
Parse(binder, args);
result = this;
return true;
}
public bool Parse(InvokeMemberBinder binder, object[] args)
{
var memberName = binder.Name.Replace("With", "");
argumentStore.SetMemberNameAndValue(memberName, args[0]);
return true;
}
}
} |
Make send try policy more aggressive | using System;
using Abc.Zebus.Util;
namespace Abc.Zebus.Transport
{
public class ZmqSocketOptions : IZmqSocketOptions
{
public ZmqSocketOptions()
{
ReadTimeout = 300.Milliseconds();
SendHighWaterMark = 20000;
SendTimeout = 1000.Milliseconds();
SendRetriesBeforeSwitchingToClosedState = 5;
ClosedStateDuration = 15.Seconds();
ReceiveHighWaterMark = 20000;
}
public TimeSpan ReadTimeout { set; get; }
public int SendHighWaterMark { get; set; }
public TimeSpan SendTimeout { get; set; }
public int SendRetriesBeforeSwitchingToClosedState { get; set; }
public TimeSpan ClosedStateDuration { get; set; }
public int ReceiveHighWaterMark { get; set; }
}
} | using System;
using Abc.Zebus.Util;
namespace Abc.Zebus.Transport
{
public class ZmqSocketOptions : IZmqSocketOptions
{
public ZmqSocketOptions()
{
ReadTimeout = 300.Milliseconds();
SendHighWaterMark = 20000;
SendTimeout = 100.Milliseconds();
SendRetriesBeforeSwitchingToClosedState = 2;
ClosedStateDuration = 15.Seconds();
ReceiveHighWaterMark = 20000;
}
public TimeSpan ReadTimeout { set; get; }
public int SendHighWaterMark { get; set; }
public TimeSpan SendTimeout { get; set; }
public int SendRetriesBeforeSwitchingToClosedState { get; set; }
public TimeSpan ClosedStateDuration { get; set; }
public int ReceiveHighWaterMark { get; set; }
}
} |
Fix popups for Google & Apple sign-in | using CefSharp;
using CefSharp.Handler;
using TweetDuck.Controls;
using TweetDuck.Utils;
namespace TweetDuck.Browser.Handling.General {
sealed class CustomLifeSpanHandler : LifeSpanHandler {
private static bool IsPopupAllowed(string url) {
return url.StartsWith("https://twitter.com/teams/authorize?");
}
public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl) {
switch (targetDisposition) {
case WindowOpenDisposition.NewBackgroundTab:
case WindowOpenDisposition.NewForegroundTab:
case WindowOpenDisposition.NewPopup when !IsPopupAllowed(targetUrl):
case WindowOpenDisposition.NewWindow:
browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl));
return true;
default:
return false;
}
}
protected override bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) {
newBrowser = null;
return HandleLinkClick(browserControl, targetDisposition, targetUrl);
}
protected override bool DoClose(IWebBrowser browserControl, IBrowser browser) {
return false;
}
}
}
| using System;
using CefSharp;
using CefSharp.Handler;
using TweetDuck.Controls;
using TweetDuck.Utils;
namespace TweetDuck.Browser.Handling.General {
sealed class CustomLifeSpanHandler : LifeSpanHandler {
private static bool IsPopupAllowed(string url) {
return url.StartsWith("https://twitter.com/teams/authorize?", StringComparison.Ordinal) ||
url.StartsWith("https://accounts.google.com/", StringComparison.Ordinal) ||
url.StartsWith("https://appleid.apple.com/", StringComparison.Ordinal);
}
public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl) {
switch (targetDisposition) {
case WindowOpenDisposition.NewBackgroundTab:
case WindowOpenDisposition.NewForegroundTab:
case WindowOpenDisposition.NewPopup when !IsPopupAllowed(targetUrl):
case WindowOpenDisposition.NewWindow:
browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl));
return true;
default:
return false;
}
}
protected override bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) {
newBrowser = null;
return HandleLinkClick(browserControl, targetDisposition, targetUrl);
}
protected override bool DoClose(IWebBrowser browserControl, IBrowser browser) {
return false;
}
}
}
|
Remove use of obsolete property. | using System;
using Faithlife.Build;
internal static class Build
{
public static int Main(string[] args) => BuildRunner.Execute(args, build =>
{
build.AddDotNetTargets(
new DotNetBuildSettings
{
NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"),
DocsSettings = new DotNetDocsSettings
{
GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""),
GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"),
SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src",
},
SourceLinkSettings = SourceLinkSettings.Default,
});
});
}
| using System;
using Faithlife.Build;
internal static class Build
{
public static int Main(string[] args) => BuildRunner.Execute(args, build =>
{
build.AddDotNetTargets(
new DotNetBuildSettings
{
NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"),
DocsSettings = new DotNetDocsSettings
{
GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""),
GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"),
SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src",
},
});
});
}
|
Set auto-incrementing file version, starting with 0.1, since we're at alpha stage | using System.Resources;
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("CallMeMaybe")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("CallMeMaybe")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Resources;
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("CallMeMaybe")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("CallMeMaybe")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.1.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
|
Fix fault with subcommand server attribute | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
using JetBrains.Annotations;
namespace Booma.Proxy
{
/// <summary>
/// Marks the 0x60 command server payload with the associated operation code.
/// Should be marked on <see cref="BlockNetworkCommandEventServerPayload"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed class SubCommand60ServerAttribute : WireDataContractBaseLinkAttribute
{
/// <inheritdoc />
public SubCommand60ServerAttribute(SubCommand60OperationCode opCode)
: base((int)opCode, typeof(BlockNetworkCommandEventClientPayload))
{
if(!Enum.IsDefined(typeof(SubCommand60OperationCode), opCode)) throw new InvalidEnumArgumentException(nameof(opCode), (int)opCode, typeof(SubCommand60OperationCode));
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
using JetBrains.Annotations;
namespace Booma.Proxy
{
/// <summary>
/// Marks the 0x60 command server payload with the associated operation code.
/// Should be marked on <see cref="BlockNetworkCommandEventServerPayload"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed class SubCommand60ServerAttribute : WireDataContractBaseLinkAttribute
{
/// <inheritdoc />
public SubCommand60ServerAttribute(SubCommand60OperationCode opCode)
: base((int)opCode, typeof(BlockNetworkCommandEventServerPayload))
{
if(!Enum.IsDefined(typeof(SubCommand60OperationCode), opCode)) throw new InvalidEnumArgumentException(nameof(opCode), (int)opCode, typeof(SubCommand60OperationCode));
}
}
}
|
Use full path to source folder | using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Web.Deployment;
namespace WAWSDeploy
{
public class WebDeployHelper
{
public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile)
{
var sourceBaseOptions = new DeploymentBaseOptions();
DeploymentBaseOptions destBaseOptions;
string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions);
Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile));
// Publish the content to the remote site
using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions))
{
// Note: would be nice to have an async flavor of this API...
return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions());
}
}
private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions)
{
var document = XDocument.Load(path);
var profile = document.Descendants("publishProfile").First();
string siteName = profile.Attribute("msdeploySite").Value;
deploymentBaseOptions = new DeploymentBaseOptions
{
ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName),
UserName = profile.Attribute("userName").Value,
Password = profile.Attribute("userPWD").Value,
AuthenticationType = "Basic"
};
return siteName;
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Web.Deployment;
namespace WAWSDeploy
{
public class WebDeployHelper
{
public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile)
{
contentPath = Path.GetFullPath(contentPath);
var sourceBaseOptions = new DeploymentBaseOptions();
DeploymentBaseOptions destBaseOptions;
string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions);
Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile));
// Publish the content to the remote site
using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions))
{
// Note: would be nice to have an async flavor of this API...
return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions());
}
}
private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions)
{
var document = XDocument.Load(path);
var profile = document.Descendants("publishProfile").First();
string siteName = profile.Attribute("msdeploySite").Value;
deploymentBaseOptions = new DeploymentBaseOptions
{
ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName),
UserName = profile.Attribute("userName").Value,
Password = profile.Attribute("userPWD").Value,
AuthenticationType = "Basic"
};
return siteName;
}
}
}
|
Allow access to standalone queue storage | using System;
using System.IO;
using System.Linq;
namespace LightBlue.Standalone
{
public class StandaloneAzureStorage : IAzureStorage
{
public const string DevelopmentAccountName = "dev";
private readonly string _storageAccountDirectory;
public StandaloneAzureStorage(string connectionString)
{
var storageAccountName = ExtractAccountName(connectionString);
_storageAccountDirectory = Path.Combine(StandaloneEnvironment.LightBlueDataDirectory, storageAccountName);
Directory.CreateDirectory(_storageAccountDirectory);
}
public IAzureBlobStorageClient CreateAzureBlobStorageClient()
{
return new StandaloneAzureBlobStorageClient(_storageAccountDirectory);
}
public IAzureQueueStorageClient CreateAzureQueueStorageClient()
{
throw new NotSupportedException();
}
private static string ExtractAccountName(string connectionString)
{
try
{
var valuePairs = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(component => component.Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(c => c[0].ToLowerInvariant(), c => c[1]);
if (valuePairs.ContainsKey("accountname"))
{
return valuePairs["accountname"];
}
if (valuePairs.ContainsKey("usedevelopmentstorage"))
{
return DevelopmentAccountName;
}
}
catch (IndexOutOfRangeException ex)
{
throw new FormatException("Settings must be of the form \"name=value\".", ex);
}
throw new FormatException("Could not parse the connection string.");
}
}
} | using System;
using System.IO;
using System.Linq;
namespace LightBlue.Standalone
{
public class StandaloneAzureStorage : IAzureStorage
{
public const string DevelopmentAccountName = "dev";
private readonly string _storageAccountDirectory;
public StandaloneAzureStorage(string connectionString)
{
var storageAccountName = ExtractAccountName(connectionString);
_storageAccountDirectory = Path.Combine(StandaloneEnvironment.LightBlueDataDirectory, storageAccountName);
Directory.CreateDirectory(_storageAccountDirectory);
}
public IAzureBlobStorageClient CreateAzureBlobStorageClient()
{
return new StandaloneAzureBlobStorageClient(_storageAccountDirectory);
}
public IAzureQueueStorageClient CreateAzureQueueStorageClient()
{
return new StandaloneAzureQueueStorageClient(_storageAccountDirectory);
}
private static string ExtractAccountName(string connectionString)
{
try
{
var valuePairs = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(component => component.Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(c => c[0].ToLowerInvariant(), c => c[1]);
if (valuePairs.ContainsKey("accountname"))
{
return valuePairs["accountname"];
}
if (valuePairs.ContainsKey("usedevelopmentstorage"))
{
return DevelopmentAccountName;
}
}
catch (IndexOutOfRangeException ex)
{
throw new FormatException("Settings must be of the form \"name=value\".", ex);
}
throw new FormatException("Could not parse the connection string.");
}
}
} |
Add failing test for get paused trigger groups | using System;
using Quartz.Simpl;
using Quartz.Spi;
namespace Quartz.DynamoDB.Tests
{
public class TriggerGroupGetTests
{
IJobStore _sut;
public TriggerGroupGetTests()
{
_sut = new JobStore();
var signaler = new Quartz.DynamoDB.Tests.Integration.RamJobStoreTests.SampleSignaler();
var loadHelper = new SimpleTypeLoadHelper();
_sut.Initialize(loadHelper, signaler);
}
}
}
| using System;
using Quartz.Simpl;
using Quartz.Spi;
using Xunit;
namespace Quartz.DynamoDB.Tests
{
public class TriggerGroupGetTests
{
IJobStore _sut;
public TriggerGroupGetTests()
{
_sut = new JobStore();
var signaler = new Quartz.DynamoDB.Tests.Integration.RamJobStoreTests.SampleSignaler();
var loadHelper = new SimpleTypeLoadHelper();
_sut.Initialize(loadHelper, signaler);
}
/// <summary>
/// Get paused trigger groups returns one record.
/// </summary>
[Fact]
[Trait("Category", "Integration")]
public void GetPausedTriggerGroupReturnsOneRecord()
{
//create a trigger group by calling for it to be paused.
string triggerGroup = Guid.NewGuid().ToString();
_sut.PauseTriggers(Quartz.Impl.Matchers.GroupMatcher<TriggerKey>.GroupEquals(triggerGroup));
var result = _sut.GetPausedTriggerGroups();
Assert.True(result.Contains(triggerGroup));
}
}
}
|
Hide the form in the taskbar | using System;
using System.Drawing;
using System.Windows.Forms;
namespace vuwall_motion {
public partial class TransparentForm : Form {
public TransparentForm() {
InitializeComponent();
DoubleBuffered = true;
}
private void TransparentForm_Load(object sender, EventArgs e)
{
int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle);
wl = wl | 0x80000 | 0x20;
TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl);
TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha);
Invalidate();
}
private void TransparentForm_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20);
}
// TODO: Method to get an event from MYO to get x & w positions, used to invalidate
}
}
| using System;
using System.Drawing;
using System.Windows.Forms;
namespace vuwall_motion {
public partial class TransparentForm : Form {
public TransparentForm() {
InitializeComponent();
DoubleBuffered = true;
ShowInTaskbar = false;
}
private void TransparentForm_Load(object sender, EventArgs e)
{
int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle);
wl = wl | 0x80000 | 0x20;
TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl);
TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha);
Invalidate();
}
private void TransparentForm_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20);
}
// TODO: Method to get an event from MYO to get x & w positions, used to invalidate
}
}
|
Add "+" to attributes to fetch since ApacheDS doesn't return all on * and AD doesn't return anything on + | namespace Novell.Directory.Ldap
{
/// <summary>
/// Extension Methods for <see cref="ILdapConnection"/> to
/// avoid bloating that interface.
/// </summary>
public static class LdapConnectionExtensionMethods
{
/// <summary>
/// Get some common Attributes from the Root DSE.
/// This is really just a specialized <see cref="LdapSearchRequest"/>
/// to handle getting some commonly requested information.
/// </summary>
public static RootDseInfo GetRootDseInfo(this ILdapConnection conn)
{
var searchResults = conn.Search("", LdapConnection.ScopeBase, "(objectClass=*)", new string[] { "*", "supportedExtension" }, false);
if (searchResults.HasMore())
{
var sr = searchResults.Next();
return new RootDseInfo(sr);
}
return null;
}
}
}
| namespace Novell.Directory.Ldap
{
/// <summary>
/// Extension Methods for <see cref="ILdapConnection"/> to
/// avoid bloating that interface.
/// </summary>
public static class LdapConnectionExtensionMethods
{
/// <summary>
/// Get some common Attributes from the Root DSE.
/// This is really just a specialized <see cref="LdapSearchRequest"/>
/// to handle getting some commonly requested information.
/// </summary>
public static RootDseInfo GetRootDseInfo(this ILdapConnection conn)
{
var searchResults = conn.Search("", LdapConnection.ScopeBase, "(objectClass=*)", new string[] { "*", "+", "supportedExtension" }, false);
if (searchResults.HasMore())
{
var sr = searchResults.Next();
return new RootDseInfo(sr);
}
return null;
}
}
}
|
Update the 'name' field description | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Eco
{
/// <summary>
/// Eco configuration library supports string varibales.
/// You can enable variables in your configuration file by adding 'public variable[] variables;'
/// field to your root configuration type.
/// Variable can be referenced anywhere in a configuration file by it's name using the following syntax: ${name}.
///
/// Variable's value can reference another variable. In this case variable value is expanded recursively.
/// Eco library throws an exception if a circular variable dendency is detected.
/// </summary>
[Doc("Represents a configuration variable of the string type. Can be referenced anywhere in a configuration file by the following syntax: ${name}.")]
public class variable
{
[Required, Doc("Name of the varible. Can contain 'word' characters only.")]
public string name;
[Required, Doc("Variable's value.")]
public string value;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Eco
{
/// <summary>
/// Eco configuration library supports string varibales.
/// You can enable variables in your configuration file by adding 'public variable[] variables;'
/// field to your root configuration type.
/// Variable can be referenced anywhere in a configuration file by it's name using the following syntax: ${name}.
///
/// Variable's value can reference another variable. In this case variable value is expanded recursively.
/// Eco library throws an exception if a circular variable dendency is detected.
/// </summary>
[Doc("Represents a configuration variable of the string type. Can be referenced anywhere in a configuration file by the following syntax: ${name}.")]
public class variable
{
[Required, Doc("Name of the varible. Can contain 'word' characters only (ie [A-Za-z0-9_]).")]
public string name;
[Required, Doc("Variable's value.")]
public string value;
}
}
|
Deal with case of removing a Subscription that has been previously removed (06624d) | using System;
using System.Collections.Generic;
using System.Linq;
namespace Adaptive.Aeron
{
internal class ActiveSubscriptions : IDisposable
{
private readonly Dictionary<int, List<Subscription>> _subscriptionsByStreamIdMap = new Dictionary<int, List<Subscription>>();
public void ForEach(int streamId, Action<Subscription> handler)
{
List<Subscription> subscriptions;
if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions))
{
subscriptions.ForEach(handler);
}
}
public void Add(Subscription subscription)
{
List<Subscription> subscriptions;
if (!_subscriptionsByStreamIdMap.TryGetValue(subscription.StreamId(), out subscriptions))
{
subscriptions = new List<Subscription>();
_subscriptionsByStreamIdMap[subscription.StreamId()] = subscriptions;
}
subscriptions.Add(subscription);
}
public void Remove(Subscription subscription)
{
int streamId = subscription.StreamId();
var subscriptions = _subscriptionsByStreamIdMap[streamId];
if (subscriptions.Remove(subscription) && subscriptions.Count == 0)
{
_subscriptionsByStreamIdMap.Remove(streamId);
}
}
public void Dispose()
{
var subscriptions = from subs in _subscriptionsByStreamIdMap.Values
from subscription in subs
select subscription;
foreach (var subscription in subscriptions)
{
subscription.Dispose();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Adaptive.Aeron
{
internal class ActiveSubscriptions : IDisposable
{
private readonly Dictionary<int, List<Subscription>> _subscriptionsByStreamIdMap = new Dictionary<int, List<Subscription>>();
public void ForEach(int streamId, Action<Subscription> handler)
{
List<Subscription> subscriptions;
if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions))
{
subscriptions.ForEach(handler);
}
}
public void Add(Subscription subscription)
{
List<Subscription> subscriptions;
if (!_subscriptionsByStreamIdMap.TryGetValue(subscription.StreamId(), out subscriptions))
{
subscriptions = new List<Subscription>();
_subscriptionsByStreamIdMap[subscription.StreamId()] = subscriptions;
}
subscriptions.Add(subscription);
}
public void Remove(Subscription subscription)
{
int streamId = subscription.StreamId();
List<Subscription> subscriptions;
if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions))
{
if (subscriptions.Remove(subscription) && subscriptions.Count == 0)
{
_subscriptionsByStreamIdMap.Remove(streamId);
}
}
}
public void Dispose()
{
var subscriptions = from subs in _subscriptionsByStreamIdMap.Values
from subscription in subs
select subscription;
foreach (var subscription in subscriptions)
{
subscription.Dispose();
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.