commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
31b8035a7365b7c7cfa52f47fa397b128151cf7e | Refactor DocumentDbUserRepository configuration | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Infrastructure/Data/DocumentDbUserRepository.cs | src/SFA.DAS.EmployerUsers.Infrastructure/Data/DocumentDbUserRepository.cs | using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using SFA.DAS.Configuration;
using SFA.DAS.EmployerUsers.Domain.Data;
using SFA.DAS.EmployerUsers.Infrastructure.Configuration;
using User = SFA.DAS.EmployerUsers.Domain.User;
namespace SFA.DAS.EmployerUsers.Infrastructure.Data
{
public class DocumentDbUserRepository : IUserRepository
{
private const string DatabaseName = "EmployerUsers";
private const string CollectionName = "User";
private readonly IConfigurationService _configurationService;
public DocumentDbUserRepository(IConfigurationService configurationService)
{
_configurationService = configurationService;
}
public async Task<User> GetById(string id)
{
try
{
var client = await GetClient();
var documentUri = UriFactory.CreateDocumentUri(DatabaseName, CollectionName, id);
var document = await client.ReadDocumentAsync(documentUri);
DocumentDbUser documentDbUser = (dynamic)document.Resource;
return documentDbUser.ToDomainUser();
}
catch (DocumentClientException de)
{
if (de.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
throw;
}
}
public async Task Create(User registerUser)
{
var client = await GetClient();
registerUser.Id = Guid.NewGuid().ToString();
var collectionId = UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName);
var documentDbUser = DocumentDbUser.FromDomainUser(registerUser);
await client.CreateDocumentAsync(collectionId, documentDbUser, null, true);
}
private async Task<DocumentClient> GetClient()
{
var configuration = await _configurationService.Get<EmployerUsersConfiguration>();
return new DocumentClient(new Uri(configuration.DataStorage.DocumentDbUri), configuration.DataStorage.DocumentDbAccessToken);
}
}
}
| using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using SFA.DAS.Configuration;
using SFA.DAS.EmployerUsers.Domain.Data;
using SFA.DAS.EmployerUsers.Infrastructure.Configuration;
using User = SFA.DAS.EmployerUsers.Domain.User;
namespace SFA.DAS.EmployerUsers.Infrastructure.Data
{
public class DocumentDbUserRepository : IUserRepository
{
private const string DatabaseName = "EmployerUsers";
private const string CollectionName = "User";
private readonly DocumentClient _client;
public DocumentDbUserRepository(IConfigurationService configurationService)
{
var cfgTask = configurationService.Get<EmployerUsersConfiguration>();
cfgTask.Wait();
var configuration = cfgTask.Result;
_client = new DocumentClient(new Uri(configuration.DataStorage.DocumentDbUri), configuration.DataStorage.DocumentDbAccessToken);
}
public async Task<User> GetById(string id)
{
try
{
var documentUri = UriFactory.CreateDocumentUri(DatabaseName, CollectionName, id);
var document = await _client.ReadDocumentAsync(documentUri);
DocumentDbUser documentDbUser = (dynamic)document.Resource;
return documentDbUser.ToDomainUser();
}
catch (DocumentClientException de)
{
if (de.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
throw;
}
}
public async Task Create(User registerUser)
{
registerUser.Id = Guid.NewGuid().ToString();
var collectionId = UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName);
var documentDbUser = DocumentDbUser.FromDomainUser(registerUser);
await _client.CreateDocumentAsync(collectionId, documentDbUser, null, true);
}
}
}
| mit | C# |
2bf0c28c1b9874c09e589a9dea4c8535051dda58 | Add Customer filter when listing CreditNote | stripe/stripe-dotnet | src/Stripe.net/Services/CreditNotes/CreditNoteListOptions.cs | src/Stripe.net/Services/CreditNotes/CreditNoteListOptions.cs | namespace Stripe
{
using Newtonsoft.Json;
public class CreditNoteListOptions : ListOptions
{
/// <summary>
/// ID of the customer.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string InvoiceId { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
public class CreditNoteListOptions : ListOptions
{
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string InvoiceId { get; set; }
}
}
| apache-2.0 | C# |
7de3161ba8371632f9be3da5483a6e4c571fdf85 | Fix IsOnce sprite option | ziggi/space-fly | game/Sprite.cs | game/Sprite.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace game
{
class Sprite
{
private Image Image;
private Point Position;
private Point DrawPosition;
private Size Size;
private int Speed;
private int FramesCount;
private bool IsOnce;
private double Index;
public Sprite(Point DrawPosition, Image Image, Point Position, Size Size, int Speed, int FramesCount, bool IsOnce) {
this.DrawPosition = DrawPosition;
this.Image = Image;
this.Position = Position;
this.Size = Size;
this.Speed = Speed;
this.FramesCount = FramesCount;
this.IsOnce = IsOnce;
}
public void Update() {
this.Index += this.Speed;
}
public void Draw(Graphics g) {
int frame;
if (this.Speed > 0) {
frame = Convert.ToInt32(Math.Floor(this.Index)) % this.FramesCount;
if (this.IsDone()) {
return;
}
} else {
frame = 0;
}
Point Pos = this.Position;
Pos.X += frame * this.Size.Width;
g.DrawImage(this.Image, new Rectangle(DrawPosition, this.Size), new Rectangle(Pos, this.Size), GraphicsUnit.Pixel);
}
public bool IsDone() {
return (this.IsOnce && Convert.ToInt32(Math.Floor(this.Index)) >= this.FramesCount);
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace game
{
class Sprite
{
private Image Image;
private Point Position;
private Point DrawPosition;
private Size Size;
private int Speed;
private int FramesCount;
private bool IsOnce;
private double Index;
public Sprite(Point DrawPosition, Image Image, Point Position, Size Size, int Speed, int FramesCount, bool IsOnce) {
this.DrawPosition = DrawPosition;
this.Image = Image;
this.Position = Position;
this.Size = Size;
this.Speed = Speed;
this.FramesCount = FramesCount;
this.IsOnce = IsOnce;
}
public void Update() {
this.Index += this.Speed;
}
public void Draw(Graphics g) {
int frame;
if (this.Speed > 0) {
frame = Convert.ToInt32(Math.Floor(this.Index));
if (this.IsDone()) {
return;
}
} else {
frame = 0;
}
Point Pos = this.Position;
Pos.X += frame * this.Size.Width;
g.DrawImage(this.Image, new Rectangle(DrawPosition, this.Size), new Rectangle(Pos, this.Size), GraphicsUnit.Pixel);
}
public bool IsDone() {
return (this.IsOnce && Convert.ToInt32(Math.Floor(this.Index)) >= this.FramesCount);
}
}
}
| mit | C# |
4b348efa59bff76683804aa7399ed4ec52272557 | Make ServiceCollectionExtensions consistent | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.Extensions.Localization/LocalizationServiceCollectionExtensions.cs | src/Microsoft.Extensions.Localization/LocalizationServiceCollectionExtensions.cs | // 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 Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Localization;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for setting up localization services in an <see cref="IServiceCollection" />.
/// </summary>
public static class LocalizationServiceCollectionExtensions
{
/// <summary>
/// Adds services required for application localization.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
public static void AddLocalization(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.AddOptions();
services.TryAddSingleton<IStringLocalizerFactory, ResourceManagerStringLocalizerFactory>();
services.TryAddTransient(typeof(IStringLocalizer<>), typeof(StringLocalizer<>));
}
/// <summary>
/// Adds services required for application localization.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <param name="setupAction">An <see cref="Action{LocalizationOptions}"/> to configure the <see cref="LocalizationOptions"/>.</param>
public static void AddLocalization(
this IServiceCollection services,
Action<LocalizationOptions> setupAction)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
services.AddLocalization();
services.Configure(setupAction);
}
}
} | // 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 Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Localization;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for adding localization servics to the DI container.
/// </summary>
public static class LocalizationServiceCollectionExtensions
{
/// <summary>
/// Adds services required for application localization.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddLocalization(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
return AddLocalization(services, setupAction: null);
}
/// <summary>
/// Adds services required for application localization.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <param name="setupAction">An action to configure the <see cref="LocalizationOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddLocalization(
this IServiceCollection services,
Action<LocalizationOptions> setupAction)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.TryAdd(new ServiceDescriptor(
typeof(IStringLocalizerFactory),
typeof(ResourceManagerStringLocalizerFactory),
ServiceLifetime.Singleton));
services.TryAdd(new ServiceDescriptor(
typeof(IStringLocalizer<>),
typeof(StringLocalizer<>),
ServiceLifetime.Transient));
if (setupAction != null)
{
services.Configure(setupAction);
}
return services;
}
}
} | apache-2.0 | C# |
9af007591a271f176cc74f374d2c239908f1ac7d | Store task of handlers (#43198) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Security/Authorization/Core/src/DefaultAuthorizationHandlerProvider.cs | src/Security/Authorization/Core/src/DefaultAuthorizationHandlerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Authorization;
/// <summary>
/// The default implementation of a handler provider,
/// which provides the <see cref="IAuthorizationHandler"/>s for an authorization request.
/// </summary>
public class DefaultAuthorizationHandlerProvider : IAuthorizationHandlerProvider
{
private readonly Task<IEnumerable<IAuthorizationHandler>> _handlersTask;
/// <summary>
/// Creates a new instance of <see cref="DefaultAuthorizationHandlerProvider"/>.
/// </summary>
/// <param name="handlers">The <see cref="IAuthorizationHandler"/>s.</param>
public DefaultAuthorizationHandlerProvider(IEnumerable<IAuthorizationHandler> handlers)
{
if (handlers == null)
{
throw new ArgumentNullException(nameof(handlers));
}
_handlersTask = Task.FromResult(handlers);
}
/// <inheritdoc />
public Task<IEnumerable<IAuthorizationHandler>> GetHandlersAsync(AuthorizationHandlerContext context)
=> _handlersTask;
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Authorization;
/// <summary>
/// The default implementation of a handler provider,
/// which provides the <see cref="IAuthorizationHandler"/>s for an authorization request.
/// </summary>
public class DefaultAuthorizationHandlerProvider : IAuthorizationHandlerProvider
{
private readonly IEnumerable<IAuthorizationHandler> _handlers;
/// <summary>
/// Creates a new instance of <see cref="DefaultAuthorizationHandlerProvider"/>.
/// </summary>
/// <param name="handlers">The <see cref="IAuthorizationHandler"/>s.</param>
public DefaultAuthorizationHandlerProvider(IEnumerable<IAuthorizationHandler> handlers)
{
if (handlers == null)
{
throw new ArgumentNullException(nameof(handlers));
}
_handlers = handlers;
}
/// <inheritdoc />
public Task<IEnumerable<IAuthorizationHandler>> GetHandlersAsync(AuthorizationHandlerContext context)
=> Task.FromResult(_handlers);
}
| apache-2.0 | C# |
e0fb46b715ce39ccf580e67a880146e9de274a03 | Add Buffer and Format properties | rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary | CSGL.Vulkan/BufferView.cs | CSGL.Vulkan/BufferView.cs | using System;
using System.Collections.Generic;
namespace CSGL.Vulkan {
public class BufferViewCreateInfo {
public Buffer buffer;
public VkFormat format;
public ulong offset;
public ulong range;
}
public class BufferView : INative<VkBufferView>, IDisposable {
bool disposed;
VkBufferView bufferView;
public Device Device { get; private set; }
public Buffer Buffer { get; private set; }
public VkFormat Format { get; private set; }
public ulong Offset { get; private set; }
public ulong Range { get; private set; }
public VkBufferView Native {
get {
return bufferView;
}
}
public BufferView(Device device, BufferViewCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
Device = device;
}
void CreateBufferView(BufferViewCreateInfo mInfo) {
VkBufferViewCreateInfo info = new VkBufferViewCreateInfo();
info.sType = VkStructureType.BufferViewCreateInfo;
info.buffer = mInfo.buffer.Native;
info.format = mInfo.format;
info.offset = mInfo.offset;
info.range = mInfo.range;
var result = Device.Commands.createBufferView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out bufferView);
if (result != VkResult.Success) throw new BufferViewException(result, string.Format("Error creating buffer view: {0}", result));
Buffer = mInfo.buffer;
Format = mInfo.format;
Offset = mInfo.offset;
Range = mInfo.range;
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (disposed) return;
Device.Commands.destroyBufferView(Device.Native, bufferView, Device.Instance.AllocationCallbacks);
disposed = true;
}
~BufferView() {
Dispose(false);
}
}
public class BufferViewException : VulkanException {
public BufferViewException(VkResult result, string message) : base(result, message) { }
}
}
| using System;
using System.Collections.Generic;
namespace CSGL.Vulkan {
public class BufferViewCreateInfo {
public Buffer buffer;
public VkFormat format;
public ulong offset;
public ulong range;
}
public class BufferView : INative<VkBufferView>, IDisposable {
bool disposed;
VkBufferView bufferView;
public Device Device { get; private set; }
public ulong Offset { get; private set; }
public ulong Range { get; private set; }
public VkBufferView Native {
get {
return bufferView;
}
}
public BufferView(Device device, BufferViewCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
Device = device;
}
void CreateBufferView(BufferViewCreateInfo mInfo) {
VkBufferViewCreateInfo info = new VkBufferViewCreateInfo();
info.sType = VkStructureType.BufferViewCreateInfo;
info.buffer = mInfo.buffer.Native;
info.format = mInfo.format;
info.offset = mInfo.offset;
info.range = mInfo.range;
var result = Device.Commands.createBufferView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out bufferView);
if (result != VkResult.Success) throw new BufferViewException(result, string.Format("Error creating buffer view: {0}", result));
Offset = mInfo.offset;
Range = mInfo.range;
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (disposed) return;
Device.Commands.destroyBufferView(Device.Native, bufferView, Device.Instance.AllocationCallbacks);
disposed = true;
}
~BufferView() {
Dispose(false);
}
}
public class BufferViewException : VulkanException {
public BufferViewException(VkResult result, string message) : base(result, message) { }
}
}
| mit | C# |
8815813be07707a76c43e3cae0b3b715c3a4169f | Update FirstReverse.cs | michaeljwebb/Algorithm-Practice | Coderbyte/FirstReverse.cs | Coderbyte/FirstReverse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coderbyte
{
class FirstReverse
{
static void Main(string[] args)
{
Console.WriteLine(First_Reverse(Console.ReadLine()));
}
public static string First_Reverse(string str)
{
char[] cArray = str.ToCharArray();
string result = "";
for (int i = cArray.Length - 1; i >= 0; i--)
{
result += cArray[i];
str = result;
}
return str;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coderbyte
{
class FirstReverse
{
static void Main(string[] args)
{
Console.WriteLine(First_Reverse(Console.ReadLine()));
}
public static string First_Reverse(string str)
{
char[] cArray = str.ToCharArray();
string result = "";
for (int i = cArray.Length - 1; i >= 0; i--)
{
result += cArray[i];
str = result;
}
return str;
}
}
}
| mit | C# |
8270228c61c82075da927b5b7cc2617bcfafc0b6 | add list control | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | ConsoleTestApp/Program.cs | ConsoleTestApp/Program.cs | using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Dashen;
using Dashen.Models;
namespace ConsoleTestApp
{
class Program
{
static void Main(string[] args)
{
var ui = new Dashboard(new Uri("http://localhost:8080"));
var model = new TextControlViewModel { Content = "Test" };
//config all the things...
ui.RegisterModel(new Definition
{
Create = () => model,
Heading = "Some Text",
Name = "TestContent"
});
ui.RegisterModel(new Definition
{
Create = () => new ListControlViewModel { Items = new[] { "One", "Two", "Many", "Lots" }.ToList() },
Heading = "Four things",
Name = "FourThings"
});
ui.Start();
Console.WriteLine("Webui running on port 8080.");
Console.WriteLine("Press any key to exit.");
Task.Run(() =>
{
var counter = 0;
while (true)
{
counter++;
model.Content = "Test " + counter;
Thread.Sleep(1000);
}
});
Console.ReadKey();
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
using Dashen;
using Dashen.Models;
namespace ConsoleTestApp
{
class Program
{
static void Main(string[] args)
{
var ui = new Dashboard(new Uri("http://localhost:8080"));
var model = new TextControlViewModel { Content = "Test" };
//config all the things...
ui.RegisterModel(new Definition
{
Create = () => model,
Heading = "Some Text",
Name = "TestContent"
});
ui.Start();
Console.WriteLine("Webui running on port 8080.");
Console.WriteLine("Press any key to exit.");
Task.Run(() =>
{
var counter = 0;
while (true)
{
counter++;
model.Content = "Test " + counter;
Thread.Sleep(1000);
}
});
Console.ReadKey();
}
}
}
| lgpl-2.1 | C# |
14e4e0fbd0e388beb26c71094da19bd979e04ef7 | Increase assembly version | kant2002/Dub | Dub/CommonAssemblyInfo.cs | Dub/CommonAssemblyInfo.cs | // -----------------------------------------------------------------------
// <copyright file="CommonAssemblyInfo.cs" company="Andrey Kurdiumov">
// Copyright (c) Andrey Kurdiumov. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyCopyright("Copyright Andrey Kurdiumov 2014-2015")]
[assembly: AssemblyCompany("Andrey Kurdiumov")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
| // -----------------------------------------------------------------------
// <copyright file="CommonAssemblyInfo.cs" company="Andrey Kurdiumov">
// Copyright (c) Andrey Kurdiumov. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyCopyright("Copyright Andrey Kurdiumov 2014-2015")]
[assembly: AssemblyCompany("Andrey Kurdiumov")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.2.9.0")]
[assembly: AssemblyFileVersion("0.2.9.0")]
| apache-2.0 | C# |
4ba1f6fac3eb64e082adf56716cecfe4abf3dc80 | Add key array comment | KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption,KyleBanks/XOREncryption | C#/Main.cs | C#/Main.cs | using System;
class XOREncryption
{
private static string encryptDecrypt(string input) {
char[] key = {'K', 'C', 'Q'}; //Any chars will work, in an array of any size
char[] output = new char[input.Length];
for(int i = 0; i < input.Length; i++) {
output[i] = (char) (input[i] ^ key[i % key.Length]);
}
return new string(output);
}
public static void Main (string[] args)
{
string encrypted = encryptDecrypt("kylewbanks.com");
Console.WriteLine ("Encrypted:" + encrypted);
string decrypted = encryptDecrypt(encrypted);
Console.WriteLine ("Decrypted:" + decrypted);
}
}
| using System;
class XOREncryption
{
private static string encryptDecrypt(string input) {
char[] key = {'K', 'C', 'Q'};
char[] output = new char[input.Length];
for(int i = 0; i < input.Length; i++) {
output[i] = (char) (input[i] ^ key[i % key.Length]);
}
return new string(output);
}
public static void Main (string[] args)
{
string encrypted = encryptDecrypt("kylewbanks.com");
Console.WriteLine ("Encrypted:" + encrypted);
string decrypted = encryptDecrypt(encrypted);
Console.WriteLine ("Decrypted:" + decrypted);
}
}
| mit | C# |
5201412bdf2632abeffebfae27bff60928be539d | Fix Spelling Mistake | Mpdreamz/shellprogressbar | src/ShellProgressBar.Example/Examples/DeeplyNestedProgressBarTreeExample.cs | src/ShellProgressBar.Example/Examples/DeeplyNestedProgressBarTreeExample.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace ShellProgressBar.Example.Examples
{
public class DeeplyNestedProgressBarTreeExample : IProgressBarExample
{
public Task Start(CancellationToken token)
{
var random = new Random();
var numberOfSteps = 7;
var overProgressOptions = new ProgressBarOptions
{
BackgroundColor = ConsoleColor.DarkGray,
};
using (var pbar = new ProgressBar(numberOfSteps, "overall progress", overProgressOptions))
{
var stepBarOptions = new ProgressBarOptions
{
ForeGroundColor = ConsoleColor.Cyan,
ForeGroundColorDone = ConsoleColor.DarkGreen,
ProgressCharacter = '─',
BackgroundColor = ConsoleColor.DarkGray,
CollapseWhenFinished = false,
} ;
Parallel.For(0, numberOfSteps, (i) =>
{
var workBarOptions = new ProgressBarOptions
{
ForeGroundColor = ConsoleColor.Yellow,
ProgressCharacter = '─',
BackgroundColor = ConsoleColor.DarkGray,
};
var childSteps = random.Next(1, 5);
using (var childProgress = pbar.Spawn(childSteps, $"step {i} progress", stepBarOptions))
Parallel.For(0, childSteps, (ci) =>
{
var childTicks = random.Next(50, 250);
using (var innerChildProgress = childProgress.Spawn(childTicks, $"step {i}::{ci} progress", workBarOptions))
{
for (var r = 0; r < childTicks; r++)
{
innerChildProgress.Tick();
Program.BusyWait(50);
}
}
childProgress.Tick();
});
pbar.Tick();
});
}
return Task.FromResult(1);
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace ShellProgressBar.Example.Examples
{
public class DeeplyNestedProgressBarTreeExample : IProgressBarExample
{
public Task Start(CancellationToken token)
{
var random = new Random();
var numberOfSteps = 7;
var overProgressOptions = new ProgressBarOptions
{
BackgroundColor = ConsoleColor.DarkGray,
};
using (var pbar = new ProgressBar(numberOfSteps, "overal progress", overProgressOptions))
{
var stepBarOptions = new ProgressBarOptions
{
ForeGroundColor = ConsoleColor.Cyan,
ForeGroundColorDone = ConsoleColor.DarkGreen,
ProgressCharacter = '─',
BackgroundColor = ConsoleColor.DarkGray,
CollapseWhenFinished = false,
} ;
Parallel.For(0, numberOfSteps, (i) =>
{
var workBarOptions = new ProgressBarOptions
{
ForeGroundColor = ConsoleColor.Yellow,
ProgressCharacter = '─',
BackgroundColor = ConsoleColor.DarkGray,
};
var childSteps = random.Next(1, 5);
using (var childProgress = pbar.Spawn(childSteps, $"step {i} progress", stepBarOptions))
Parallel.For(0, childSteps, (ci) =>
{
var childTicks = random.Next(50, 250);
using (var innerChildProgress = childProgress.Spawn(childTicks, $"step {i}::{ci} progress", workBarOptions))
{
for (var r = 0; r < childTicks; r++)
{
innerChildProgress.Tick();
Program.BusyWait(50);
}
}
childProgress.Tick();
});
pbar.Tick();
});
}
return Task.FromResult(1);
}
}
} | mit | C# |
fc45ea7eaedf29462fa94d3412dba82c3b28038f | Implement direct-to-node deserialization (faster despite nasty array issues) | EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an | A-vs-An/A-vs-An-DotNet/Internals/Node.cs | A-vs-An/A-vs-An-DotNet/Internals/Node.cs | using System;
namespace AvsAnLib.Internals {
/// <summary>
/// A node the article lookup trie. Do not mutate after construction.
/// </summary>
public struct Node : IComparable<Node> {
public char c;
public Ratio ratio;
public Node[] SortedKids;
public int CompareTo(Node other) { return c.CompareTo(other.c); }
public static Node CreateFromMutable(MutableNode node, char key=' ') {
Node[] sortedKids = null;
if (node.Kids != null) {
sortedKids = new Node[node.Kids.Count];
int i = 0;
foreach (var kv in node.Kids)
sortedKids[i++] = CreateFromMutable(kv.Value, kv.Key);
Array.Sort(sortedKids);
}
return new Node { c = key, ratio = node.ratio, SortedKids = sortedKids };
}
public void LoadPrefixRatio(string prefix, int depth, Ratio prefixRatio) {
if (prefix.Length == depth) {
ratio = prefixRatio;
} else {
int idx;
char kidC = prefix[depth];
if (SortedKids == null) {
SortedKids = new[] { new Node { c = kidC, } };
idx = 0;
} else {
var nearestIdx = FindNearestNode(kidC);
idx = nearestIdx;
if (SortedKids[nearestIdx].c != kidC) {
if (SortedKids[nearestIdx].c < kidC) {
idx = nearestIdx + 1;
}
InsertBefore(idx, kidC);
}
}
SortedKids[idx].LoadPrefixRatio(prefix, depth + 1, prefixRatio);
}
}
int FindNearestNode(char c) {
int start = 0, end = SortedKids.Length;
while (end - start > 1) {
int midpoint = end + start >> 1;
if (SortedKids[midpoint].c <= c) {
start = midpoint;
} else {
end = midpoint;
}
}
return start;
}
void InsertBefore(int idx, char c) {
var newArr = new Node[SortedKids.Length + 1];
int i = 0;
for (; i < idx; i++) {
newArr[i] = SortedKids[i];
}
newArr[idx].c = c;
for (; i < SortedKids.Length; i++) {
newArr[i + 1] = SortedKids[i];
}
SortedKids = newArr;
}
}
} | using System;
namespace AvsAnLib.Internals {
/// <summary>
/// A node the article lookup trie. Do not mutate after construction.
/// </summary>
public struct Node : IComparable<Node> {
public char c;
public Ratio ratio;
public Node[] SortedKids;
public int CompareTo(Node other) { return c.CompareTo(other.c); }
public static Node CreateFromMutable(MutableNode node, char key=' ') {
Node[] sortedKids = null;
if (node.Kids != null) {
sortedKids = new Node[node.Kids.Count];
int i = 0;
foreach (var kv in node.Kids)
sortedKids[i++] = CreateFromMutable(kv.Value, kv.Key);
Array.Sort(sortedKids);
}
return new Node { c = key, ratio = node.ratio, SortedKids = sortedKids };
}
}
} | apache-2.0 | C# |
99436186c72160a1ce47527bed8995d3d0bd32b7 | make class abstract | xamarin/monotouch-samples,xamarin/monotouch-samples,xamarin/monotouch-samples | ios9/FilterDemoApp/FilterDemoFramework/DSPKernel.cs | ios9/FilterDemoApp/FilterDemoFramework/DSPKernel.cs | using System;
using AudioToolbox;
using AudioUnit;
namespace FilterDemoFramework {
public abstract class DSPKernel {
void HandleOneEvent (AURenderEvent theEvent)
{
switch (theEvent.Head.EventType) {
case AURenderEventType.Parameter:
case AURenderEventType.ParameterRamp:
AUParameterEvent paramEvent = theEvent.Parameter;
StartRamp (paramEvent.ParameterAddress, paramEvent.Value, (int)paramEvent.RampDurationSampleFrames);
break;
case AURenderEventType.Midi:
throw new NotImplementedException ();
}
}
// There are two APIs for getting all of the events.
// - The "raw" pointers from the linked list
// - The EnumeratorCurrentEvents wrapper
//#define USE_RAW_EVENT_ENUMERATION
#if USE_RAW_EVENT_ENUMERATION
unsafe void PerformAllSimultaneousEvents (nint now, AURenderEvent** theEvent)
{
do {
HandleOneEvent (**theEvent);
*theEvent = (*theEvent)->Head.UnsafeNext;
} while (*theEvent != null && ((*theEvent)->Head.EventSampleTime == now));
}
public unsafe void ProcessWithEvents (AudioTimeStamp timestamp, int frameCount, AURenderEventEnumerator events)
{
var now = (nint)timestamp.SampleTime;
int framesRemaining = frameCount;
AURenderEvent* theEvent = events.UnsafeFirst;
while (framesRemaining > 0) {
if (theEvent == null) {
int bufferOffset = frameCount - framesRemaining;
Process (framesRemaining, bufferOffset);
return;
}
int framesThisSegment = (int)(theEvent->Head.EventSampleTime - now);
if (framesThisSegment > 0) {
int bufferOffset = frameCount - framesRemaining;
Process (framesThisSegment, bufferOffset);
framesRemaining -= framesThisSegment;
now += framesThisSegment;
}
PerformAllSimultaneousEvents (now, &theEvent);
}
}
#else
public unsafe void ProcessWithEvents (AudioTimeStamp timestamp, int frameCount, AURenderEventEnumerator events)
{
var now = (nint)timestamp.SampleTime;
int framesRemaining = frameCount;
while (framesRemaining > 0) {
if (events.IsAtEnd) {
int bufferOffset = frameCount - framesRemaining;
Process (framesRemaining, bufferOffset);
return;
}
var framesThisSegment = (int)(events.Current.Head.EventSampleTime - now);
if (framesThisSegment > 0) {
int bufferOffset = frameCount - framesRemaining;
Process (framesThisSegment, bufferOffset);
framesRemaining -= framesThisSegment;
now += framesThisSegment;
}
foreach (AURenderEvent e in events.EnumeratorCurrentEvents (now))
HandleOneEvent (e);
events.MoveNext ();
}
}
#endif
public abstract void Process (int frameCount, int bufferOffset);
public abstract void StartRamp (ulong address, float value, int duration);
}
}
| using System;
using AudioToolbox;
using AudioUnit;
namespace FilterDemoFramework {
public class DSPKernel {
void HandleOneEvent (AURenderEvent theEvent)
{
switch (theEvent.Head.EventType) {
case AURenderEventType.Parameter:
case AURenderEventType.ParameterRamp:
AUParameterEvent paramEvent = theEvent.Parameter;
StartRamp (paramEvent.ParameterAddress, paramEvent.Value, (int)paramEvent.RampDurationSampleFrames);
break;
case AURenderEventType.Midi:
throw new NotImplementedException ();
}
}
// There are two APIs for getting all of the events.
// - The "raw" pointers from the linked list
// - The EnumeratorCurrentEvents wrapper
//#define USE_RAW_EVENT_ENUMERATION
#if USE_RAW_EVENT_ENUMERATION
unsafe void PerformAllSimultaneousEvents (nint now, AURenderEvent** theEvent)
{
do {
HandleOneEvent (**theEvent);
*theEvent = (*theEvent)->Head.UnsafeNext;
} while (*theEvent != null && ((*theEvent)->Head.EventSampleTime == now));
}
public unsafe void ProcessWithEvents (AudioTimeStamp timestamp, int frameCount, AURenderEventEnumerator events)
{
var now = (nint)timestamp.SampleTime;
int framesRemaining = frameCount;
AURenderEvent* theEvent = events.UnsafeFirst;
while (framesRemaining > 0) {
if (theEvent == null) {
int bufferOffset = frameCount - framesRemaining;
Process (framesRemaining, bufferOffset);
return;
}
int framesThisSegment = (int)(theEvent->Head.EventSampleTime - now);
if (framesThisSegment > 0) {
int bufferOffset = frameCount - framesRemaining;
Process (framesThisSegment, bufferOffset);
framesRemaining -= framesThisSegment;
now += framesThisSegment;
}
PerformAllSimultaneousEvents (now, &theEvent);
}
}
#else
public unsafe void ProcessWithEvents (AudioTimeStamp timestamp, int frameCount, AURenderEventEnumerator events)
{
var now = (nint)timestamp.SampleTime;
int framesRemaining = frameCount;
while (framesRemaining > 0) {
if (events.IsAtEnd) {
int bufferOffset = frameCount - framesRemaining;
Process (framesRemaining, bufferOffset);
return;
}
var framesThisSegment = (int)(events.Current.Head.EventSampleTime - now);
if (framesThisSegment > 0) {
int bufferOffset = frameCount - framesRemaining;
Process (framesThisSegment, bufferOffset);
framesRemaining -= framesThisSegment;
now += framesThisSegment;
}
foreach (AURenderEvent e in events.EnumeratorCurrentEvents (now))
HandleOneEvent (e);
events.MoveNext ();
}
}
#endif
public virtual void Process (int frameCount, int bufferOffset)
{
}
public virtual void StartRamp (ulong address, float value, int duration)
{
}
}
}
| mit | C# |
33d57054d93575114acf3fa817157a45c8f59e80 | fix incorrect comment | JSONAPIdotNET/JSONAPI.NET,SphtKr/JSONAPI.NET | JSONAPI/Documents/IResourceLinkage.cs | JSONAPI/Documents/IResourceLinkage.cs | namespace JSONAPI.Documents
{
/// <summary>
/// Describes a relationship's linkage
/// </summary>
public interface IResourceLinkage
{
/// <summary>
/// Whether the linkage is to-many (true) or to-one (false).
/// </summary>
bool IsToMany { get; }
/// <summary>
/// The identifiers this linkage refers to. If IsToMany is false, this
/// property must return an array of length either 0 or 1. If true,
/// the array may be of any length. This property must not return null.
/// </summary>
IResourceIdentifier[] Identifiers { get; }
}
} | namespace JSONAPI.Documents
{
/// <summary>
/// Describes a relationship's linkage
/// </summary>
public interface IResourceLinkage
{
/// <summary>
/// Whether the linkage is to-many (true) or to-one (false).
/// </summary>
bool IsToMany { get; }
/// <summary>
/// The identifiers this linkage refers to. If IsToMany is true, this
/// property must return an array of length either 0 or 1. If false,
/// the array may be of any length. This property must not return null.
/// </summary>
IResourceIdentifier[] Identifiers { get; }
}
} | mit | C# |
9347c3f535e9820ed461ea5c11b62fd9d9a8d7a4 | Add trigger user change test | smoogipoo/osu,peppy/osu,2yangk23/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,johnneijzen/osu | osu.Game.Tests/Visual/Online/TestSceneCommentsContainer.cs | osu.Game.Tests/Visual/Online/TestSceneCommentsContainer.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Game.Online.API.Requests;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Game.Overlays.Comments;
using osu.Game.Overlays;
using osu.Framework.Allocation;
using osu.Game.Online.API;
namespace osu.Game.Tests.Visual.Online
{
[TestFixture]
public class TestSceneCommentsContainer : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(CommentsContainer),
typeof(CommentsHeader),
typeof(DrawableComment),
typeof(HeaderButton),
typeof(SortTabControl),
typeof(ShowChildrenButton),
typeof(DeletedCommentsCounter),
typeof(VotePill),
typeof(CommentsPage),
};
protected override bool UseOnlineAPI => true;
[Cached]
private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);
private CommentsContainer comments;
private readonly BasicScrollContainer scroll;
public TestSceneCommentsContainer()
{
Add(scroll = new BasicScrollContainer
{
RelativeSizeAxes = Axes.Both,
Child = comments = new CommentsContainer()
});
}
[BackgroundDependencyLoader]
private void load(IAPIProvider api)
{
AddStep("Big Black comments", () => comments.ShowComments(CommentableType.Beatmapset, 41823));
AddStep("Airman comments", () => comments.ShowComments(CommentableType.Beatmapset, 24313));
AddStep("Lazer build comments", () => comments.ShowComments(CommentableType.Build, 4772));
AddStep("News comments", () => comments.ShowComments(CommentableType.NewsPost, 715));
AddStep("Trigger user change", api.LocalUser.TriggerChange);
AddStep("Idle state", () =>
{
scroll.Clear();
scroll.Add(comments = new CommentsContainer());
});
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Game.Online.API.Requests;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Game.Overlays.Comments;
using osu.Game.Overlays;
using osu.Framework.Allocation;
namespace osu.Game.Tests.Visual.Online
{
[TestFixture]
public class TestSceneCommentsContainer : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(CommentsContainer),
typeof(CommentsHeader),
typeof(DrawableComment),
typeof(HeaderButton),
typeof(SortTabControl),
typeof(ShowChildrenButton),
typeof(DeletedCommentsCounter),
typeof(VotePill),
typeof(CommentsPage),
};
protected override bool UseOnlineAPI => true;
[Cached]
private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);
public TestSceneCommentsContainer()
{
BasicScrollContainer scroll;
CommentsContainer comments;
Add(scroll = new BasicScrollContainer
{
RelativeSizeAxes = Axes.Both,
Child = comments = new CommentsContainer()
});
AddStep("Big Black comments", () => comments.ShowComments(CommentableType.Beatmapset, 41823));
AddStep("Airman comments", () => comments.ShowComments(CommentableType.Beatmapset, 24313));
AddStep("Lazer build comments", () => comments.ShowComments(CommentableType.Build, 4772));
AddStep("News comments", () => comments.ShowComments(CommentableType.NewsPost, 715));
AddStep("Idle state", () =>
{
scroll.Clear();
scroll.Add(comments = new CommentsContainer());
});
}
}
}
| mit | C# |
0907eadb55f59107489e3d59209cd57d6bb87778 | Make string format optional if no trace listener is attached | chkr1011/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet,JTrotta/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet | MQTTnet.Core/Diagnostics/MqttTrace.cs | MQTTnet.Core/Diagnostics/MqttTrace.cs | using System;
namespace MQTTnet.Core.Diagnostics
{
public static class MqttTrace
{
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
public static void Verbose(string source, string message)
{
Publish(source, MqttTraceLevel.Verbose, null, message);
}
public static void Information(string source, string message)
{
Publish(source, MqttTraceLevel.Information, null, message);
}
public static void Warning(string source, string message)
{
Publish(source, MqttTraceLevel.Warning, null, message);
}
public static void Warning(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Warning, exception, message);
}
public static void Error(string source, string message)
{
Publish(source, MqttTraceLevel.Error, null, message);
}
public static void Error(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Error, exception, message);
}
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
{
var handler = TraceMessagePublished;
if (handler == null)
{
return;
}
message = string.Format(message, 1);
handler.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
}
}
}
| using System;
namespace MQTTnet.Core.Diagnostics
{
public static class MqttTrace
{
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
public static void Verbose(string source, string message)
{
Publish(source, MqttTraceLevel.Verbose, null, message);
}
public static void Information(string source, string message)
{
Publish(source, MqttTraceLevel.Information, null, message);
}
public static void Warning(string source, string message)
{
Publish(source, MqttTraceLevel.Warning, null, message);
}
public static void Warning(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Warning, exception, message);
}
public static void Error(string source, string message)
{
Publish(source, MqttTraceLevel.Error, null, message);
}
public static void Error(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Error, exception, message);
}
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
{
TraceMessagePublished?.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
}
}
}
| mit | C# |
f31cf1ba8bcf55c9bdf170ae8ed2ae4111980d1a | Write current user's role into claims identity. | enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api | Infopulse.EDemocracy.Web/Auth/Providers/SimpleAuthorizationServerProvider.cs | Infopulse.EDemocracy.Web/Auth/Providers/SimpleAuthorizationServerProvider.cs | using System.Data.Entity;
using System.Linq;
using Infopulse.EDemocracy.Data.Repositories;
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Infopulse.EDemocracy.Web.Auth.Providers
{
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (AuthRepository _repo = new AuthRepository())
{
var user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName));
AddRoleClaim(identity, context.UserName);
context.Validated(identity);
}
private Claim GetUserRoleClaim(string userEmail)
{
using (var db = new AuthContext())
{
var user = db.Users.Include(u => u.Claims).SingleOrDefault(u => u.Email == userEmail);
var roleClaim = user.Claims.SingleOrDefault(c => c.ClaimType == ClaimTypes.Role);
if (roleClaim != null)
{
return new Claim(ClaimTypes.Role, roleClaim.ClaimValue);
}
}
return null;
}
private void AddRoleClaim(ClaimsIdentity identity, string userEmail)
{
var roleClaim = GetUserRoleClaim(userEmail);
if (roleClaim != null)
{
identity.AddClaim(roleClaim);
}
}
}
} | using Infopulse.EDemocracy.Data.Repositories;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Infopulse.EDemocracy.Web.Auth.Providers
{
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (AuthRepository _repo = new AuthRepository())
{
var user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName));
context.Validated(identity);
}
}
} | cc0-1.0 | C# |
a375b4b70b88fd913a6c07e5dad092ef1fb7d4b5 | Update BinanceTransferHistory.cs (#636) | JKorf/Binance.Net | Binance.Net/Objects/Spot/MarginData/BinanceTransferHistory.cs | Binance.Net/Objects/Spot/MarginData/BinanceTransferHistory.cs | using System;
using Binance.Net.Converters;
using Binance.Net.Enums;
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;
namespace Binance.Net.Objects.Spot.MarginData
{
/// <summary>
/// Transfer history entry
/// </summary>
public class BinanceTransferHistory
{
/// <summary>
/// Amount of the transfer
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// Asset of the transfer
/// </summary>
public decimal Asset { get; set; }
/// <summary>
/// Status of the transfer
/// </summary>
public string Status { get; set; } = "";
/// <summary>
/// Timestamp of the transaction
/// </summary>
[JsonConverter(typeof(TimestampConverter))]
public DateTime Timestamp { get; set; }
/// <summary>
/// Transaction id
/// </summary>
[JsonProperty("txId")]
public decimal TransactionId { get; set; }
/// <summary>
/// Direction of the transfer
/// </summary>
[JsonProperty("type"), JsonConverter(typeof(TransferDirectionConverter))]
public TransferDirection Direction { get; set; }
}
}
| using Binance.Net.Converters;
using Binance.Net.Enums;
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;
namespace Binance.Net.Objects.Spot.MarginData
{
/// <summary>
/// Transfer history entry
/// </summary>
public class BinanceTransferHistory
{
/// <summary>
/// Amount of the transfer
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// Asset of the transfer
/// </summary>
public decimal Asset { get; set; }
/// <summary>
/// Status of the transfer
/// </summary>
public string Status { get; set; } = "";
/// <summary>
/// Timestamp of the transaction
/// </summary>
[JsonConverter(typeof(TimestampConverter))]
public decimal Timestamp { get; set; }
/// <summary>
/// Transaction id
/// </summary>
[JsonProperty("txId")]
public decimal TransactionId { get; set; }
/// <summary>
/// Direction of the transfer
/// </summary>
[JsonProperty("type"), JsonConverter(typeof(TransferDirectionConverter))]
public TransferDirection Direction { get; set; }
}
}
| mit | C# |
4cd39620629a1f9acdb8af4c0078775ad37837b3 | Make `Structure` class abstract | convertersystems/opc-ua-client | UaClient/ServiceModel/Ua/Structure.cs | UaClient/ServiceModel/Ua/Structure.cs | // Copyright (c) Converter Systems LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Workstation.ServiceModel.Ua
{
/// <summary>
/// A base implementation of a Structure.
/// </summary>
[DataTypeId(DataTypeIds.Structure)]
public abstract class Structure : IEncodable
{
public virtual void Encode(IEncoder encoder)
{
}
public virtual void Decode(IDecoder decoder)
{
}
}
}
| // Copyright (c) Converter Systems LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Workstation.ServiceModel.Ua
{
/// <summary>
/// A base implementation of a Structure.
/// </summary>
[DataTypeId(DataTypeIds.Structure)]
public class Structure : IEncodable
{
public virtual void Encode(IEncoder encoder)
{
}
public virtual void Decode(IDecoder decoder)
{
}
}
}
| mit | C# |
2bf6323e3be39bfbb0b5e2c155144a452e45a2f8 | Update UsingCellName.cs | aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Data/Handling/AccessingCells/UsingCellName.cs | Examples/CSharp/Data/Handling/AccessingCells/UsingCellName.cs | using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Data.Handling.AccessingCells
{
public class UsingCellName
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Using the Sheet 1 in Workbook
Worksheet worksheet = workbook.Worksheets[0];
//Accessing a cell using its name
Cell cell = worksheet.Cells["A1"];
string value = cell.Value.ToString();
Console.WriteLine(value);
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Data.Handling.AccessingCells
{
public class UsingCellName
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Using the Sheet 1 in Workbook
Worksheet worksheet = workbook.Worksheets[0];
//Accessing a cell using its name
Cell cell = worksheet.Cells["A1"];
string value = cell.Value.ToString();
Console.WriteLine(value);
}
}
} | mit | C# |
52327b830978353fe5a63996c5556e42d43b5481 | Use Specific Sources for nuget | ApplETS/ETSMobile-WindowsPlatforms,ApplETS/ETSMobile-WindowsPlatforms | build.cake | build.cake | //////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
// Solution
var rootFolder = "./Ets.Mobile";
var solutionPath = rootFolder + "/Ets.Mobile.WindowsPhone.sln";
var allProjectsBinPath = rootFolder + "/**/bin";
// Tests
var testFolder = rootFolder + "/Ets.Mobile.Tests/";
var testProjects = new List<string>()
{
"Ets.Mobile.Client.Tests/Ets.Mobile.Client.Tests.csproj"
};
var testBinPath = testFolder + "Ets.Mobile.Client.Tests/bin";
// Configurations
var target = Argument("target", "Default");
var releaseConfiguration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
// Define directories for tests.
for(var ind = 0; ind < testProjects.Count; ind++)
{
testProjects[ind] = testFolder + testProjects[ind];
}
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() => {
CleanDirectories(allProjectsBinPath);
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() => {
NuGetRestore(solutionPath, new NuGetRestoreSettings()
{
Source = new List<string>()
{
"https://api.nuget.org/v3/index.json",
"http://nuget.syncfusion.com/MzAwMTE1LDEz",
"http://nuget.syncfusion.com/MzAwMTE1LDEw"
}
});
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() => {
// Since we use AppVeyor (with Windows Env), we'll use MSBuild
MSBuild(solutionPath, settings =>
settings
.SetConfiguration(releaseConfiguration)
.SetPlatformTarget(PlatformTarget.ARM)
);
// Build test projects in x86
foreach(var project in testProjects)
{
MSBuild(project, settings =>
settings
.SetConfiguration(releaseConfiguration)
.SetPlatformTarget(PlatformTarget.x86)
.SetMSBuildPlatform(MSBuildPlatform.x86)
);
}
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() => {
XUnit2(testBinPath + "/x86/" + releaseConfiguration + "/*.Tests.dll", new XUnit2Settings {
ToolPath = "./tools/xunit.runner.console/tools/xunit.console.x86.exe"
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
| //////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
// Solution
var rootFolder = "./Ets.Mobile";
var solutionPath = rootFolder + "/Ets.Mobile.WindowsPhone.sln";
var allProjectsBinPath = rootFolder + "/**/bin";
// Tests
var testFolder = rootFolder + "/Ets.Mobile.Tests/";
var testProjects = new List<string>()
{
"Ets.Mobile.Client.Tests/Ets.Mobile.Client.Tests.csproj"
};
var testBinPath = testFolder + "Ets.Mobile.Client.Tests/bin";
// Configurations
var target = Argument("target", "Default");
var releaseConfiguration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
// Define directories for tests.
for(var ind = 0; ind < testProjects.Count; ind++)
{
testProjects[ind] = testFolder + testProjects[ind];
}
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() => {
CleanDirectories(allProjectsBinPath);
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() => {
NuGetRestore(solutionPath);
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() => {
// Since we use AppVeyor (with Windows Env), we'll use MSBuild
MSBuild(solutionPath, settings =>
settings
.SetConfiguration(releaseConfiguration)
.SetPlatformTarget(PlatformTarget.ARM)
);
// Build test projects in x86
foreach(var project in testProjects)
{
MSBuild(project, settings =>
settings
.SetConfiguration(releaseConfiguration)
.SetPlatformTarget(PlatformTarget.x86)
.SetMSBuildPlatform(MSBuildPlatform.x86)
);
}
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() => {
XUnit2(testBinPath + "/x86/" + releaseConfiguration + "/*.Tests.dll", new XUnit2Settings {
ToolPath = "./tools/xunit.runner.console/tools/xunit.console.x86.exe"
});
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
| apache-2.0 | C# |
55807307abb3fbf6923e9a8b2c73332a126901b2 | Change message and description | occar421/OpenTKAnalyzer | src/OpenTKAnalyzer/OpenTKAnalyzer/OpenTK/RotationValueOpenTKMathAnalyzer.cs | src/OpenTKAnalyzer/OpenTKAnalyzer/OpenTK/RotationValueOpenTKMathAnalyzer.cs | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace OpenTKAnalyzer.OpenTK
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
class RotationValueOpenTKMathAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "RotatinoValueOpenTKMath";
private const string Title = "Rotation value(OpenTK Math)";
private const string MessageFormat = "{0} accepts {1} values.";
private const string Description = "Warm on literal in argument seems invalid style(radian or degree).";
private const string Category = "OpenTKAnalyzer:OpenTK";
private const string RadianString = "radian";
private const string DegreeString = "degree";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
id: DiagnosticId,
title: Title,
messageFormat: MessageFormat,
category: Category,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression);
}
private static void Analyze(SyntaxNodeAnalysisContext context)
{
var invotation = context.Node as InvocationExpressionSyntax;
// TODO: check method name and literal on argument
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace OpenTKAnalyzer.OpenTK
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
class RotationValueOpenTKMathAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "RotatinoValueOpenTKMath";
private const string Title = "Rotation value(OpenTK Math)";
private const string MessageFormat = "{0} accepts radian values.";
private const string Description = "Warm on literal in argument seems degree.";
private const string Category = "OpenTKAnalyzer:OpenTK";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
id: DiagnosticId,
title: Title,
messageFormat: MessageFormat,
category: Category,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression);
}
private static void Analyze(SyntaxNodeAnalysisContext context)
{
var invotation = context.Node as InvocationExpressionSyntax;
// TODO: check method name and literal on argument
}
}
}
| mit | C# |
b7866c22a009299234d22823a4f048a209a48d11 | Use compund assignment | panopticoncentral/roslyn,heejaechang/roslyn,eriawan/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,physhi/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,tmat/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,aelij/roslyn,agocke/roslyn,dotnet/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,gafter/roslyn,sharwell/roslyn,reaction1989/roslyn,reaction1989/roslyn,gafter/roslyn,KirillOsenkov/roslyn,aelij/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,KevinRansom/roslyn,dotnet/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,mavasani/roslyn,davkean/roslyn,KevinRansom/roslyn,brettfo/roslyn,physhi/roslyn,AlekseyTs/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,panopticoncentral/roslyn,mavasani/roslyn,AlekseyTs/roslyn,genlu/roslyn,brettfo/roslyn,abock/roslyn,AmadeusW/roslyn,genlu/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,agocke/roslyn,gafter/roslyn,eriawan/roslyn,bartdesmet/roslyn,davkean/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,physhi/roslyn,abock/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,jmarolf/roslyn,abock/roslyn,agocke/roslyn,reaction1989/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,diryboy/roslyn,genlu/roslyn,sharwell/roslyn,jmarolf/roslyn,stephentoub/roslyn,aelij/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,weltkante/roslyn,sharwell/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,eriawan/roslyn,heejaechang/roslyn,stephentoub/roslyn,tannergooding/roslyn,weltkante/roslyn | src/VisualStudio/Core/Def/Implementation/Extensions/VsTextSpanExtensions.cs | src/VisualStudio/Core/Def/Implementation/Extensions/VsTextSpanExtensions.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions
{
internal static class VsTextSpanExtensions
{
public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(this VsTextSpan spanInSecondaryBuffer, Microsoft.CodeAnalysis.Workspace workspace, DocumentId documentId, out VsTextSpan spanInPrimaryBuffer)
{
spanInPrimaryBuffer = default;
if (!(workspace is VisualStudioWorkspaceImpl visualStudioWorkspace))
{
return false;
}
var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId);
if (containedDocument == null)
{
return false;
}
var bufferCoordinator = containedDocument.BufferCoordinator;
var primary = new VsTextSpan[1];
var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(spanInSecondaryBuffer, primary);
spanInPrimaryBuffer = primary[0];
return ErrorHandler.Succeeded(hresult);
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions
{
internal static class VsTextSpanExtensions
{
public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(this VsTextSpan spanInSecondaryBuffer, Microsoft.CodeAnalysis.Workspace workspace, DocumentId documentId, out VsTextSpan spanInPrimaryBuffer)
{
spanInPrimaryBuffer = default;
var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
if (visualStudioWorkspace == null)
{
return false;
}
var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId);
if (containedDocument == null)
{
return false;
}
var bufferCoordinator = containedDocument.BufferCoordinator;
var primary = new VsTextSpan[1];
var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(spanInSecondaryBuffer, primary);
spanInPrimaryBuffer = primary[0];
return ErrorHandler.Succeeded(hresult);
}
}
}
| mit | C# |
7265d89137b3c4c73af08e857ab5a9c739b7411f | Clarify installation of fonts on Linux | gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop | src/BloomExe/ToPalaso/FontInstaller.cs | src/BloomExe/ToPalaso/FontInstaller.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.CognitoSync;
using Palaso.IO;
namespace Bloom.ToPalaso
{
/// <summary>
/// Helper class for installing fonts.
/// To use this: the sourceFolder passed to InstallFont must be one that GetDirectoryDistributedWithApplication can find.
/// It must contain the fonts you want to be sure are installed.
/// It MUST also contain the installer program, "Install Bloom Literacy Fonts.exe", a renamed version of FontReg.exe (see below).
/// The user will typically see a UAC dialog asking whether it is OK to run this program (if the fonts are not already
/// installed).
/// </summary>
public class FontInstaller
{
public static void InstallFont(string sourceFolder)
{
// This is not needed on Linux - fonts should be installed by adding a package
// dependency, in this case fonts-sil-andika, or by installing that particular
// package.
if (!Palaso.PlatformUtilities.Platform.IsWindows)
return;
var sourcePath = FileLocator.GetDirectoryDistributedWithApplication(sourceFolder);
if (AllFontsExist(sourcePath))
return; // already installed (Enhance: maybe one day we want to check version?)
var info = new ProcessStartInfo()
{
// Renamed to make the UAC dialog less mysterious.
// Originally it is FontReg.exe (http://code.kliu.org/misc/fontreg/).
// Eventually we will probably have to get our version signed.
FileName = "Install Bloom Literacy Fonts.exe",
Arguments = "/copy",
WorkingDirectory = sourcePath,
UseShellExecute = true, // required for runas to achieve privilege elevation
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas" // that is, run as admin (required to install fonts)
};
try
{
Process.Start(info);
}
// I hate catching 'Exception' but the one that is likely to happen, the user refused the privilege escalation
// or is not authorized to do it, comes out as Win32Exception, which is not much more helpful.
// We probably want to ignore anything else that can go wrong with trying to install the fonts.
catch (Exception)
{
}
}
private static bool AllFontsExist(string sourcePath)
{
var fontFolder = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
foreach (var fontFile in Directory.GetFiles(sourcePath, "*.ttf"))
{
var destPath = Path.Combine(fontFolder, Path.GetFileName(fontFile));
if (!File.Exists(destPath))
return false;
}
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.CognitoSync;
using Palaso.IO;
namespace Bloom.ToPalaso
{
/// <summary>
/// Helper class for installing fonts.
/// To use this: the sourceFolder passed to InstallFont must be one that GetDirectoryDistributedWithApplication can find.
/// It must contain the fonts you want to be sure are installed.
/// It MUST also contain the installer program, "Install Bloom Literacy Fonts.exe", a renamed version of FontReg.exe (see below).
/// The user will typically see a UAC dialog asking whether it is OK to run this program (if the fonts are not already
/// installed).
/// </summary>
public class FontInstaller
{
public static void InstallFont(string sourceFolder)
{
if (Palaso.PlatformUtilities.Platform.IsWindows)
{
var sourcePath = FileLocator.GetDirectoryDistributedWithApplication(sourceFolder);
if (AllFontsExist(sourcePath))
return; // already installed (Enhance: maybe one day we want to check version?)
var info = new ProcessStartInfo()
{
// Renamed to make the UAC dialog less mysterious.
// Originally it is FontReg.exe (http://code.kliu.org/misc/fontreg/).
// Eventually we will probably have to get our version signed.
FileName = "Install Bloom Literacy Fonts.exe",
Arguments = "/copy",
WorkingDirectory = sourcePath,
UseShellExecute = true, // required for runas to achieve privilege elevation
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas" // that is, run as admin (required to install fonts)
};
try
{
Process.Start(info);
}
// I hate catching 'Exception' but the one that is likely to happen, the user refused the privilege escalation
// or is not authorized to do it, comes out as Win32Exception, which is not much more helpful.
// We probably want to ignore anything else that can go wrong with trying to install the fonts.
catch (Exception)
{
}
}
// Todo Linux: any way we can install fonts on Linux??
// The code for checking that they are already installed MIGHT work...
// very unlikely running a Windows EXE will actually do the installation, though.
// However, possibly on Linux we don't have to worry about privilege escalation?
}
private static bool AllFontsExist(string sourcePath)
{
var fontFolder = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
foreach (var fontFile in Directory.GetFiles(sourcePath, "*.ttf"))
{
var destPath = Path.Combine(fontFolder, Path.GetFileName(fontFile));
if (!File.Exists(destPath))
return false;
}
return true;
}
}
}
| mit | C# |
abd6a0f4a5addf2692453df409e984ae25238047 | Add rationale for exit status codes to comments. | kgybels/git-tfs,TheoAndersen/git-tfs,bleissem/git-tfs,WolfVR/git-tfs,modulexcite/git-tfs,bleissem/git-tfs,hazzik/git-tfs,hazzik/git-tfs,timotei/git-tfs,pmiossec/git-tfs,irontoby/git-tfs,TheoAndersen/git-tfs,bleissem/git-tfs,vzabavnov/git-tfs,irontoby/git-tfs,TheoAndersen/git-tfs,NathanLBCooper/git-tfs,allansson/git-tfs,TheoAndersen/git-tfs,allansson/git-tfs,irontoby/git-tfs,NathanLBCooper/git-tfs,adbre/git-tfs,WolfVR/git-tfs,kgybels/git-tfs,codemerlin/git-tfs,jeremy-sylvis-tmg/git-tfs,modulexcite/git-tfs,adbre/git-tfs,git-tfs/git-tfs,steveandpeggyb/Public,hazzik/git-tfs,timotei/git-tfs,jeremy-sylvis-tmg/git-tfs,allansson/git-tfs,allansson/git-tfs,kgybels/git-tfs,modulexcite/git-tfs,adbre/git-tfs,PKRoma/git-tfs,spraints/git-tfs,guyboltonking/git-tfs,timotei/git-tfs,spraints/git-tfs,jeremy-sylvis-tmg/git-tfs,WolfVR/git-tfs,steveandpeggyb/Public,codemerlin/git-tfs,hazzik/git-tfs,steveandpeggyb/Public,guyboltonking/git-tfs,guyboltonking/git-tfs,andyrooger/git-tfs,spraints/git-tfs,NathanLBCooper/git-tfs,codemerlin/git-tfs | GitTfs/GitTfsExitCodes.cs | GitTfs/GitTfsExitCodes.cs | using System;
namespace Sep.Git.Tfs
{
/// <summary>
/// Collection of exit codes used by git-tfs.
/// </summary>
/// <remarks>
/// For consistency across all running environments, both various
/// Windows - shells (powershell.exe, cmd.exe) and UNIX - like environments
/// such as bash (MinGW), sh or zsh avoid using negative exit status codes
/// or codes 255 or higher.
///
/// Some running environments might either modulo exit codes with 256 or clamp
/// them to interval [0, 255].
///
/// For more information:
/// http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
/// http://tldp.org/LDP/abs/html/exitcodes.html
/// </remarks>
public static class GitTfsExitCodes
{
public const int OK = 0;
public const int Help = 1;
public const int InvalidArguments = 2;
public const int ForceRequired = 3;
public const int ExceptionThrown = Byte.MaxValue - 1;
}
}
| using System;
namespace Sep.Git.Tfs
{
public static class GitTfsExitCodes
{
public const int OK = 0;
public const int Help = 1;
public const int InvalidArguments = 2;
public const int ForceRequired = 3;
public const int ExceptionThrown = Byte.MaxValue - 1;
}
}
| apache-2.0 | C# |
0c4c69c66d1a2dafb9d0bc6c5030a01a32370f6d | update in sample | p-org/PSharp | Samples/OperationsExample/Test.cs | Samples/OperationsExample/Test.cs | using System;
using Microsoft.PSharp;
namespace OperationsExample
{
public class Test
{
static void Main(string[] args)
{
var runtime = PSharpRuntime.Create();
Test.Execute(runtime);
Console.ReadLine();
}
[Microsoft.PSharp.Test]
public static void Execute(PSharpRuntime runtime)
{
runtime.CreateMachine(typeof(GodMachine));
}
}
}
| using System;
using Microsoft.PSharp;
namespace OperationsExample
{
class Test
{
static void Main(string[] args)
{
Test.Execute();
Console.ReadLine();
}
[Microsoft.PSharp.Test]
public static void Execute()
{
PSharpRuntime.CreateMachine(typeof(GodMachine));
}
}
}
| mit | C# |
8d43275a54ea01aa65bb87e2d4d9260b8f98d2fe | Improve exception handling when function does not exist | croquet-australia/api.croquet-australia.com.au | source/CroquetAustralia.DownloadTournamentEntries/ReadModels/FunctionReadModel.cs | source/CroquetAustralia.DownloadTournamentEntries/ReadModels/FunctionReadModel.cs | using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
public class FunctionReadModel
{
public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
{
TournamentItem = FindFirstFunction(tournament, lineItem);
EntrySubmitted = entrySubmitted;
LineItem = lineItem;
}
private static TournamentItem FindFirstFunction(Tournament tournament, SubmitEntry.LineItem lineItem)
{
try
{
return tournament.Functions.First(f => f.Id == lineItem.Id);
}
catch (Exception e)
{
throw new Exception($"Cannot find function '{lineItem.Id}' in tournament '{tournament.Title}'.", e);
}
}
public EntrySubmittedReadModel EntrySubmitted { get; }
public SubmitEntry.LineItem LineItem { get; }
public TournamentItem TournamentItem { get; }
}
} | using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
public class FunctionReadModel
{
public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
{
TournamentItem = tournament.Functions.First(f => f.Id == lineItem.Id);
EntrySubmitted = entrySubmitted;
LineItem = lineItem;
}
public EntrySubmittedReadModel EntrySubmitted { get; }
public SubmitEntry.LineItem LineItem { get; }
public TournamentItem TournamentItem { get; }
}
} | mit | C# |
32fccc394e4def82b87d1a9b97fcddc506eb2692 | Make SiteStatistics thread safe per content | lunet-io/lunet,lunet-io/lunet | src/Lunet/Statistics/SiteStatistics.cs | src/Lunet/Statistics/SiteStatistics.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections.Generic;
using Lunet.Core;
using Lunet.Plugins;
namespace Lunet.Statistics
{
public class SiteStatistics
{
public SiteStatistics()
{
Content = new Dictionary<ContentObject, ContentStat>();
Plugins = new Dictionary<ISitePluginCore, PluginStat>();
}
public Dictionary<ContentObject, ContentStat> Content { get; }
public Dictionary<ISitePluginCore, PluginStat> Plugins { get; }
public TimeSpan TotalTime { get; set; }
public ContentStat GetContentStat(ContentObject page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
ContentStat stat;
lock (Content)
{
if (!Content.TryGetValue(page, out stat))
{
stat = new ContentStat(page);
Content.Add(page, stat);
}
}
return stat;
}
public PluginStat GetPluginStat(ISitePluginCore plugin)
{
if (plugin == null) throw new ArgumentNullException(nameof(plugin));
PluginStat stat;
if (!Plugins.TryGetValue(plugin, out stat))
{
stat = new PluginStat(plugin);
Plugins.Add(plugin, stat);
}
return stat;
}
public void Dump(Action<string> log)
{
if (log == null) throw new ArgumentNullException(nameof(log));
log($"Total time: {TotalTime.TotalSeconds:0.###}s");
// TODO: Add report
}
public void Reset()
{
Plugins.Clear();
Content.Clear();
TotalTime = new TimeSpan(0);
}
}
} | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections.Generic;
using Lunet.Core;
using Lunet.Plugins;
namespace Lunet.Statistics
{
public class SiteStatistics
{
public SiteStatistics()
{
Content = new Dictionary<ContentObject, ContentStat>();
Plugins = new Dictionary<ISitePluginCore, PluginStat>();
}
public Dictionary<ContentObject, ContentStat> Content { get; }
public Dictionary<ISitePluginCore, PluginStat> Plugins { get; }
public TimeSpan TotalTime { get; set; }
public ContentStat GetContentStat(ContentObject page)
{
if (page == null) throw new ArgumentNullException(nameof(page));
ContentStat stat;
if (!Content.TryGetValue(page, out stat))
{
stat = new ContentStat(page);
Content.Add(page, stat);
}
return stat;
}
public PluginStat GetPluginStat(ISitePluginCore plugin)
{
if (plugin == null) throw new ArgumentNullException(nameof(plugin));
PluginStat stat;
if (!Plugins.TryGetValue(plugin, out stat))
{
stat = new PluginStat(plugin);
Plugins.Add(plugin, stat);
}
return stat;
}
public void Dump(Action<string> log)
{
if (log == null) throw new ArgumentNullException(nameof(log));
log($"Total time: {TotalTime.TotalSeconds:0.###}s");
// TODO: Add report
}
public void Reset()
{
Plugins.Clear();
Content.Clear();
TotalTime = new TimeSpan(0);
}
}
} | bsd-2-clause | C# |
ebed8a59477050b7b21d07465a444130d2b882bc | fix logging | igeligel/csharp-steamgaug-es-api | SteamGaugesApi.Example/Program.cs | SteamGaugesApi.Example/Program.cs | using System;
using SteamGaugesApi.Core;
namespace SteamGaugesApi.Example
{
internal static class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Press a key to fetch the API...");
Console.Read();
var client = new Client();
var result = client.Get();
Console.WriteLine(
"API was fetched. Next time debug here to get more information."
);
}
}
}
| using System;
using SteamGaugesApi.Core;
namespace SteamGaugesApi.Example
{
internal static class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.Read();
Client client = new Client();
var result = client.Get();
Console.WriteLine("awdwadwa");
}
}
}
| mit | C# |
f9a02c759a6d9b13da9982e9e4c0871550636934 | update for pr | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit/Inspectors/Setup/ProjectPreferencesInspector.cs | Assets/MixedRealityToolkit/Inspectors/Setup/ProjectPreferencesInspector.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor
{
[CustomEditor(typeof(ProjectPreferences))]
internal class ProjectPreferencesInspector : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox("Use Project Settings > MRTK to edit project preferences or interact in code via ProjectPreferences.cs", MessageType.Warning);
DrawDefaultInspector();
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor
{
[CustomEditor(typeof(ProjectPreferences))]
public class ProjectPreferencesInspector : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox("Use Project Settings > MRTK to edit project preferences or interact in code via ProjectPreferences.cs", MessageType.Warning);
DrawDefaultInspector();
}
}
}
| mit | C# |
a7695454722947075ae0dab9f7d386ce9ca96938 | Add helper Asserts for new ReactiveCommand behaviors | PKI-InVivo/reactive-domain | src/ReactiveDomain/ReactiveDomain.Tests/Helpers/Asserts.cs | src/ReactiveDomain/ReactiveDomain.Tests/Helpers/Asserts.cs | using System;
using System.Threading;
using ReactiveDomain.Bus;
using ReactiveDomain.Tests.Helpers;
using ReactiveUI;
// ReSharper disable once CheckNamespace - this is where it is supposed to be
namespace Xunit
{
public partial class Assert
{
public static void IsOrBecomesFalse(Func<bool> func, int? timeout = null, string msg = null)
{
IsOrBecomesTrue(() => !func(), timeout, msg);
}
public static void IsOrBecomesTrue(Func<bool> func, int? timeout = null, string msg = null)
{
if (!timeout.HasValue) timeout = 750;
var sw = System.Diagnostics.Stopwatch.StartNew();
// ReSharper disable once LoopVariableIsNeverChangedInsideLoop - Yes it does
while (!func())
{
Thread.Sleep(10);
DispatcherUtil.DoEvents();
if (sw.ElapsedMilliseconds > timeout) break;
}
True(func(), msg ?? "");
}
public static void CommandThrows<T>(Action fireAction) where T : Exception
{
var exp = Throws<CommandException>(fireAction);
IsType<T>(exp.InnerException);
}
public static void ArraySegmentEqual<T>(
T[] expectedSequence, T[] buffer, int offset = 0)
{
for (int i = 0; i < expectedSequence.Length; i++)
{
int b = i + offset;
True(buffer[b].Equals(expectedSequence[i]),
$"Byte #{b} differs: {buffer[b]} != {expectedSequence[i]}");
}
}
public static void CanExecute<TIn, TOut>(ReactiveCommand<TIn, TOut> cmd)
{
var canExecute = false;
using (cmd.CanExecute.Subscribe(x => canExecute = x))
True(canExecute);
}
public static void CannotExecute<TIn, TOut>(ReactiveCommand<TIn, TOut> cmd)
{
var canExecute = true;
using (cmd.CanExecute.Subscribe(x => canExecute = x))
False(canExecute);
}
}
}
| using System;
using System.Threading;
using ReactiveDomain.Bus;
using ReactiveDomain.Tests.Helpers;
// ReSharper disable once CheckNamespace - this is where it is supposed to be
namespace Xunit
{
public partial class Assert
{
public static void IsOrBecomesFalse(Func<bool> func, int? timeout = null, string msg = null)
{
IsOrBecomesTrue(() => !func(), timeout, msg);
}
public static void IsOrBecomesTrue(Func<bool> func, int? timeout = null, string msg = null)
{
if (!timeout.HasValue) timeout = 750;
var sw = System.Diagnostics.Stopwatch.StartNew();
// ReSharper disable once LoopVariableIsNeverChangedInsideLoop - Yes it does
while (!func())
{
Thread.Sleep(10);
DispatcherUtil.DoEvents();
if (sw.ElapsedMilliseconds > timeout) break;
}
True(func(), msg ?? "");
}
public static void CommandThrows<T>(Action fireAction) where T : Exception
{
var exp = Throws<CommandException>(fireAction);
IsType<T>(exp.InnerException);
}
public static void ArraySegmentEqual<T>(
T[] expectedSequence, T[] buffer, int offset = 0)
{
for (int i = 0; i < expectedSequence.Length; i++)
{
int b = i + offset;
True(buffer[b].Equals(expectedSequence[i]),
$"Byte #{b} differs: {buffer[b]} != {expectedSequence[i]}");
}
}
}
}
| mit | C# |
7dd00faa10a4559b31351cc66f03205fc42c49fc | Update Ensure calls to use full path | dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS | src/Umbraco.Infrastructure/Runtime/CoreInitialComponent.cs | src/Umbraco.Infrastructure/Runtime/CoreInitialComponent.cs | using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
namespace Umbraco.Core.Runtime
{
public class CoreInitialComponent : IComponent
{
private readonly IIOHelper _ioHelper;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly GlobalSettings _globalSettings;
public CoreInitialComponent(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, IOptions<GlobalSettings> globalSettings)
{
_ioHelper = ioHelper;
_hostingEnvironment = hostingEnvironment;
_globalSettings = globalSettings.Value;
}
public void Initialize()
{
// ensure we have some essential directories
// every other component can then initialize safely
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoMediaPath));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.PartialViews));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MacroPartials));
}
public void Terminate()
{ }
}
}
| using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.IO;
namespace Umbraco.Core.Runtime
{
public class CoreInitialComponent : IComponent
{
private readonly IIOHelper _ioHelper;
private readonly GlobalSettings _globalSettings;
public CoreInitialComponent(IIOHelper ioHelper, IOptions<GlobalSettings> globalSettings)
{
_ioHelper = ioHelper;
_globalSettings = globalSettings.Value;
}
public void Initialize()
{
// ensure we have some essential directories
// every other component can then initialize safely
_ioHelper.EnsurePathExists(Constants.SystemDirectories.Data);
_ioHelper.EnsurePathExists(_globalSettings.UmbracoMediaPath);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.MvcViews);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.PartialViews);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.MacroPartials);
}
public void Terminate()
{ }
}
}
| mit | C# |
086a7e7e9343c153dcca69bce26fe3c92620a00a | Update NotesRepository.cs | CarmelSoftware/MVCDataRepositoryXML | Models/NotesRepository.cs | Models/NotesRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
public class NotesRepository : INotesRepository
{
private List<Note> notes = new List<Note>();
private int iNumberOfEntries = 1;
private XDocument doc;
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
| mit | C# |
1d0deb7e3e641be958964c484ccea00f7d717fd8 | Update ConfigurationRootSetup.cs | tiksn/TIKSN-Exchange | TIKSN.Exchange/ConfigurationRootSetup.cs | TIKSN.Exchange/ConfigurationRootSetup.cs | using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using TIKSN.Configuration;
namespace TIKSN.Exchange
{
public class ConfigurationRootSetup : ConfigurationRootSetupBase
{
protected override void SetupConfiguration(IConfigurationBuilder builder)
{
base.SetupConfiguration(builder);
builder.AddInMemoryCollection(new Dictionary<string, string>
{
{ ConfigurationPath.Combine("ConnectionStrings", ConnectionStringNames.MainConnectionString), "Filename=database.db"}
});
}
}
} | using TIKSN.Configuration;
namespace TIKSN.Exchange
{
public class ConfigurationRootSetup : ConfigurationRootSetupBase
{
}
} | mit | C# |
299d528654f823689e14ffc6fb56c9f2db55ae5f | Simplify implementation | UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,ZLima12/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,2yangk23/osu,johnneijzen/osu | osu.Game/Graphics/UserInterface/HoverClickSounds.cs | osu.Game/Graphics/UserInterface/HoverClickSounds.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Input.Events;
using osuTK.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover and click sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverClickSounds : HoverSounds
{
private SampleChannel sampleClick;
private readonly MouseButton[] buttons;
/// <summary>
/// Creates an instance that adds sounds on hover and on click for any of the buttons specified.
/// </summary>
/// <param name="sampleSet">Set of click samples to play.</param>
/// <param name="buttons">
/// Array of button codes which should trigger the click sound.
/// If this optional parameter is omitted or set to <code>null</code>, the click sound will only be added on left click.
/// </param>
public HoverClickSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal, MouseButton[] buttons = null)
: base(sampleSet)
{
this.buttons = buttons ?? new[] { MouseButton.Left };
}
protected override bool OnMouseUp(MouseUpEvent e)
{
if (buttons.Contains(e.Button) && Contains(e.ScreenSpaceMousePosition))
sampleClick?.Play();
return base.OnMouseUp(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Samples.Get($@"UI/generic-select{SampleSet.GetDescription()}");
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Input.Events;
using osuTK.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover and click sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverClickSounds : HoverSounds
{
private SampleChannel sampleClick;
private readonly MouseButton[] buttons;
/// <summary>
/// Creates an instance that adds sounds on hover and on click for any of the buttons specified.
/// </summary>
/// <param name="sampleSet">Set of click samples to play.</param>
/// <param name="buttons">
/// Array of button codes which should trigger the click sound.
/// If this optional parameter is omitted or set to <code>null</code>, the click sound will only be added on left click.
/// </param>
public HoverClickSounds(HoverSampleSet sampleSet = HoverSampleSet.Normal, MouseButton[] buttons = null)
: base(sampleSet)
{
this.buttons = buttons ?? new[] { MouseButton.Left };
}
protected override bool OnMouseUp(MouseUpEvent e)
{
bool shouldPlayEffect = buttons.Contains(e.Button);
// examine the button pressed first for short-circuiting
// in most usages it is more likely that another button was pressed than that the cursor left the drawable bounds
if (shouldPlayEffect && Contains(e.ScreenSpaceMousePosition))
sampleClick?.Play();
return base.OnMouseUp(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Samples.Get($@"UI/generic-select{SampleSet.GetDescription()}");
}
}
}
| mit | C# |
a145453dec9525f52f76641c0e5248a297837c6c | Remove the last 32 bytes of GC allocation from PluginManager.GetPlugin() (#379) | PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator | targets/unity-v2/source/Shared/Public/PluginContractKey.cs | targets/unity-v2/source/Shared/Public/PluginContractKey.cs | using System.Collections.Generic;
namespace PlayFab
{
public struct PluginContractKey
{
public PluginContract _pluginContract;
public string _pluginName;
}
public class PluginContractKeyComparator : EqualityComparer<PluginContractKey>
{
public override bool Equals(PluginContractKey x, PluginContractKey y)
{
return x._pluginContract == y._pluginContract && x._pluginName.Equals(y._pluginName);
}
public override int GetHashCode(PluginContractKey obj)
{
return (int)obj._pluginContract + obj._pluginName.GetHashCode();
}
}
}
| using System;
using System.Collections.Generic;
using PlayFab.Internal;
using PlayFab.Json;
namespace PlayFab
{
public class PluginContractKey
{
public PluginContract _pluginContract;
public string _pluginName;
}
public class PluginContractKeyComparator : EqualityComparer<PluginContractKey>
{
public override bool Equals(PluginContractKey x, PluginContractKey y)
{
return x._pluginContract == y._pluginContract && x._pluginName.Equals(y._pluginName);
}
public override int GetHashCode(PluginContractKey obj)
{
return (int)obj._pluginContract + obj._pluginName.GetHashCode();
}
}
}
| apache-2.0 | C# |
761434b6036a8fec431e59cb00235fee740686aa | Update C#.cs | TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets | Backend/AddUserToUacGroup/C#.cs | Backend/AddUserToUacGroup/C#.cs | import RestSharp;
public string Server = "https://api.chayns.net/v2.0";
private const string Secret = "Your Tapp Secret";
[HttpPost]
[Route("UserPermitted")]
public IHttpActionResult UserPermitted(int locationId, int tappId, int userId, int groupId)
{
try
{
//Test if the user exists in the Group
dynamic user = AddUserToUacGroup(locationId, tappId, userId, groupId);
//null means add failed
if (user == null)
{
return InternalServerError();
}
else
{
//Build user-model
object userModel = new
{
userId = user.userId,
firstName = user.firstName,
lastName = user.lastName,
name = user.firstName,
gender = user.gender
};
return Ok(userModel);
}
}
catch (Exception exception)
{
return InternalServerError(exception);
}
}
public dynamic AddUserToUacGroup(int locationId, int tappId, int userId, int groupId)
{
//Set up RestSharp
RestClient restClient = new RestClient(Server);
//Build the request
RestRequest req = new RestRequest("/" + locationId + "/Uac/" + groupId + "/User/" + userId);
req.Method = Method.POST;
req.AddHeader("Content-Type", "application/json");
req.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToString(tappId) + ':' + Secret)));
//Run the request
IRestResponse resp = restClient.Execute(req);
//Test response health
if (resp.StatusCode == HttpStatusCode.Created)
{
//Parse data
dynamic data = JObject.Parse(resp.Content);
//Just return the user-Model
return data.data[0];
}
return null;
}
| mit | C# |
|
81cc3603a59ebcdb4cd5b166dae18447ee31623d | Add DualQuaternion.FromRotation method | virtuallynaked/virtually-naked,virtuallynaked/virtually-naked | Viewer/src/math/DualQuaternion.cs | Viewer/src/math/DualQuaternion.cs | using ProtoBuf;
using SharpDX;
[ProtoContract(UseProtoMembersOnly = true)]
public struct DualQuaternion {
[ProtoMember(1)]
private Quaternion real;
[ProtoMember(2)]
private Quaternion dual;
public Quaternion Real => real;
public Quaternion Dual => dual;
public DualQuaternion(Quaternion real, Quaternion dual) {
this.real = real;
this.dual = dual;
}
public static readonly DualQuaternion Identity = new DualQuaternion(Quaternion.Identity, Quaternion.Zero);
private static readonly Vector3 Epsilon = 1e-5f * Vector3.One;
public static DualQuaternion FromMatrix(Matrix matrix) {
Vector3 translation = new Vector3(matrix.M41, matrix.M42, matrix.M43);
var rotationMatrix = new Matrix3x3(
matrix.M11, matrix.M12, matrix.M13,
matrix.M21, matrix.M22, matrix.M23,
matrix.M31, matrix.M32, matrix.M33);
rotationMatrix.Orthonormalize();
Quaternion.RotationMatrix(ref rotationMatrix, out Quaternion rotation);
return FromRotationTranslation(rotation, translation);
}
public static DualQuaternion FromRotation(Quaternion rotation) {
return new DualQuaternion(rotation, Quaternion.Zero);
}
public static DualQuaternion FromRotation(Quaternion rotation, Vector3 center) {
//TODO: optimize
return FromTranslation(-center)
.Chain(FromRotation(rotation))
.Chain(FromTranslation(+center));
}
public static DualQuaternion FromRotationTranslation(Quaternion rotation, Vector3 translation) {
Quaternion real = rotation;
Quaternion dual = 0.5f * (new Quaternion(translation.X, translation.Y, translation.Z, 0) * rotation);
return new DualQuaternion(real, dual);
}
public static DualQuaternion FromTranslation(Vector3 translation) {
Quaternion dual = 0.5f * new Quaternion(translation.X, translation.Y, translation.Z, 0);
return new DualQuaternion(Quaternion.Identity, dual);
}
public Quaternion Rotation {
get {
return this.Real;
}
}
public Vector3 Translation {
get {
Quaternion t = 2 * Dual * Quaternion.Invert(Real);
return new Vector3(t.X, t.Y, t.Z);
}
}
public Vector3 Transform(Vector3 v) {
return Vector3.Transform(v, Rotation) + Translation;
}
public Vector3 InverseTransform(Vector3 v) {
return Vector3.Transform(v - Translation, Quaternion.Invert(Rotation));
}
private static DualQuaternion Multiply(DualQuaternion dq1, DualQuaternion dq2) {
return new DualQuaternion(
dq1.Real * dq2.Real,
dq1.Real * dq2.Dual + dq1.Dual * dq2.Real);
}
public DualQuaternion Chain(DualQuaternion dq2) {
return Multiply(dq2, this);
}
public Matrix ToMatrix() {
return Matrix.RotationQuaternion(Rotation) * Matrix.Translation(Translation);
}
public DualQuaternion Invert() {
var inverseRotation = Quaternion.Invert(Rotation);
var inverseTranslation = Vector3.Transform(-Translation, inverseRotation);
return DualQuaternion.FromRotationTranslation(inverseRotation, inverseTranslation);
}
}
| using ProtoBuf;
using SharpDX;
[ProtoContract(UseProtoMembersOnly = true)]
public struct DualQuaternion {
[ProtoMember(1)]
private Quaternion real;
[ProtoMember(2)]
private Quaternion dual;
public Quaternion Real => real;
public Quaternion Dual => dual;
public DualQuaternion(Quaternion real, Quaternion dual) {
this.real = real;
this.dual = dual;
}
public static readonly DualQuaternion Identity = new DualQuaternion(Quaternion.Identity, Quaternion.Zero);
private static readonly Vector3 Epsilon = 1e-5f * Vector3.One;
public static DualQuaternion FromMatrix(Matrix matrix) {
Vector3 translation = new Vector3(matrix.M41, matrix.M42, matrix.M43);
var rotationMatrix = new Matrix3x3(
matrix.M11, matrix.M12, matrix.M13,
matrix.M21, matrix.M22, matrix.M23,
matrix.M31, matrix.M32, matrix.M33);
rotationMatrix.Orthonormalize();
Quaternion.RotationMatrix(ref rotationMatrix, out Quaternion rotation);
return FromRotationTranslation(rotation, translation);
}
public static DualQuaternion FromRotationTranslation(Quaternion rotation, Vector3 translation) {
Quaternion real = rotation;
Quaternion dual = 0.5f * (new Quaternion(translation.X, translation.Y, translation.Z, 0) * rotation);
return new DualQuaternion(real, dual);
}
public static DualQuaternion FromTranslation(Vector3 translation) {
Quaternion dual = 0.5f * new Quaternion(translation.X, translation.Y, translation.Z, 0);
return new DualQuaternion(Quaternion.Identity, dual);
}
public Quaternion Rotation {
get {
return this.Real;
}
}
public Vector3 Translation {
get {
Quaternion t = 2 * Dual * Quaternion.Invert(Real);
return new Vector3(t.X, t.Y, t.Z);
}
}
public Vector3 Transform(Vector3 v) {
return Vector3.Transform(v, Rotation) + Translation;
}
public Vector3 InverseTransform(Vector3 v) {
return Vector3.Transform(v - Translation, Quaternion.Invert(Rotation));
}
private static DualQuaternion Multiply(DualQuaternion dq1, DualQuaternion dq2) {
return new DualQuaternion(
dq1.Real * dq2.Real,
dq1.Real * dq2.Dual + dq1.Dual * dq2.Real);
}
public DualQuaternion Chain(DualQuaternion dq2) {
return Multiply(dq2, this);
}
public Matrix ToMatrix() {
return Matrix.RotationQuaternion(Rotation) * Matrix.Translation(Translation);
}
public DualQuaternion Invert() {
var inverseRotation = Quaternion.Invert(Rotation);
var inverseTranslation = Vector3.Transform(-Translation, inverseRotation);
return DualQuaternion.FromRotationTranslation(inverseRotation, inverseTranslation);
}
}
| mit | C# |
33bcef4c615f703616d82e3e223834b7c404a640 | Load script by lines | vejuhust/msft-scooter | ScooterController/ScooterController/InstructionInterrupter.cs | ScooterController/ScooterController/InstructionInterrupter.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScooterController
{
class InstructionInterrupter
{
private readonly List<string> instructionRawLines;
public InstructionInterrupter(string filename = "instruction.txt")
{
using (var file = new StreamReader(filename))
{
string line;
var lines = new List<string>();
while ((line = file.ReadLine()) != null)
{
lines.Add(line);
}
this.instructionRawLines = lines;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScooterController
{
class InstructionInterrupter
{
public InstructionInterrupter(string filename = "instruction.txt")
{
}
}
}
| mit | C# |
f7c2ce3c03ed85ef0f20d3c0f10f33f7cbb996d2 | Stop IrcCalc from calculating channel messages | IvionSauce/MeidoBot | IrcCalc/IrcCalc.cs | IrcCalc/IrcCalc.cs | using System.Collections.Generic;
using Calculation;
// Using directives for plugin use.
using MeidoCommon;
using System.ComponentModel.Composition;
[Export(typeof(IMeidoHook))]
public class Calc : IMeidoHook
{
public string Name
{
get { return "IrcCalc"; }
}
public string Version
{
get { return "1.16"; }
}
public Dictionary<string,string> Help
{
get
{
return new Dictionary<string, string>()
{
{"calc", @"calc <expression> - Calculates expression, accepted operators: ""+"", ""-"", ""*""," +
@" ""/"", ""^""."}
};
}
}
public void Stop()
{}
[ImportingConstructor]
public Calc(IIrcComm irc, IMeidoComm meido)
{
meido.RegisterTrigger("calc", HandleTrigger);
irc.AddQueryMessageHandler(HandleMessage);
}
public static void HandleTrigger(IIrcMessage e)
{
if (e.MessageArray.Length > 1)
{
var exprStr = string.Join(" ", e.MessageArray, 1, e.MessageArray.Length - 1);
var expr = TokenizedExpression.Parse(exprStr);
if (expr.Success)
{
double result = ShuntingYard.Calculate(expr);
e.Reply( result.ToString() );
}
else
OutputError(e, expr);
}
}
public static void HandleMessage(IIrcMessage e)
{
var expr = TokenizedExpression.Parse(e.Message);
// Only automatically calculate if the expression is legitimate and if it's reasonable to assume it's meant
// to be a calculation (not just a single number). A minimal calculation will involve at least 3 tokens:
// `number operator number`.
const int minTokenCount = 3;
if (expr.Success && expr.Expression.Count >= minTokenCount)
{
double result = ShuntingYard.Calculate(expr);
e.Reply( result.ToString() );
}
}
static void OutputError(IIrcMessage e, TokenizedExpression expr)
{
string error = expr.ErrorMessage;
if (expr.ErrorPosition >= 0)
error += " | Postion: " + expr.ErrorPosition;
e.Reply(error);
}
} | using System.Collections.Generic;
using Calculation;
// Using directives for plugin use.
using MeidoCommon;
using System.ComponentModel.Composition;
[Export(typeof(IMeidoHook))]
public class Calc : IMeidoHook
{
public string Name
{
get { return "IrcCalc"; }
}
public string Version
{
get { return "1.16"; }
}
public Dictionary<string,string> Help
{
get
{
return new Dictionary<string, string>()
{
{"calc", @"calc <expression> - Calculates expression, accepted operators: ""+"", ""-"", ""*""," +
@" ""/"", ""^""."}
};
}
}
public void Stop()
{}
[ImportingConstructor]
public Calc(IIrcComm irc, IMeidoComm meido)
{
meido.RegisterTrigger("calc", HandleTrigger);
irc.AddChannelMessageHandler(HandleMessage);
irc.AddQueryMessageHandler(HandleMessage);
}
public static void HandleTrigger(IIrcMessage e)
{
if (e.MessageArray.Length > 1)
{
var exprStr = string.Join(" ", e.MessageArray, 1, e.MessageArray.Length - 1);
var expr = TokenizedExpression.Parse(exprStr);
if (expr.Success)
{
double result = ShuntingYard.Calculate(expr);
e.Reply( result.ToString() );
}
else
OutputError(e, expr);
}
}
public static void HandleMessage(IIrcMessage e)
{
var expr = TokenizedExpression.Parse(e.Message);
// Only automatically calculate if the expression is legitimate and if it's reasonable to assume it's meant
// to be a calculation (not just a single number). A minimal calculation will involve at least 3 tokens:
// `number operator number`.
const int minTokenCount = 3;
if (expr.Success && expr.Expression.Count >= minTokenCount)
{
double result = ShuntingYard.Calculate(expr);
e.Reply( result.ToString() );
}
}
static void OutputError(IIrcMessage e, TokenizedExpression expr)
{
string error = expr.ErrorMessage;
if (expr.ErrorPosition >= 0)
error += " | Postion: " + expr.ErrorPosition;
e.Reply(error);
}
} | bsd-2-clause | C# |
e39046536a7756c75689baa2acf289a28a034b58 | Remove outdated comment | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/Dialogs/DialogViewModelBase.cs | WalletWasabi.Fluent/ViewModels/Dialogs/DialogViewModelBase.cs | using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
/// <summary>
/// CommonBase class.
/// </summary>
public abstract class DialogViewModelBase : ViewModelBase
{
private bool _isDialogOpen;
/// <summary>
/// Gets or sets if the dialog is opened/closed.
/// </summary>
public bool IsDialogOpen
{
get => _isDialogOpen;
set => this.RaiseAndSetIfChanged(ref _isDialogOpen, value);
}
}
}
| using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
/// <summary>
/// CommonBase class.
/// </summary>
public abstract class DialogViewModelBase : ViewModelBase
{
private bool _isDialogOpen;
// Intended to be empty.
/// <summary>
/// Gets or sets if the dialog is opened/closed.
/// </summary>
public bool IsDialogOpen
{
get => _isDialogOpen;
set => this.RaiseAndSetIfChanged(ref _isDialogOpen, value);
}
}
}
| mit | C# |
28342adceb2995f9074a289c0b82b580f5fb1fe9 | Fix ProjectN build breaks (dotnet/corert#7115) | cshung/coreclr,mmitche/coreclr,mmitche/coreclr,poizan42/coreclr,krk/coreclr,krk/coreclr,poizan42/coreclr,poizan42/coreclr,cshung/coreclr,krk/coreclr,krk/coreclr,wtgodbe/coreclr,cshung/coreclr,mmitche/coreclr,cshung/coreclr,wtgodbe/coreclr,mmitche/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,cshung/coreclr,wtgodbe/coreclr,poizan42/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,mmitche/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,mmitche/coreclr | src/System.Private.CoreLib/shared/System/Environment.WinRT.cs | src/System.Private.CoreLib/shared/System/Environment.WinRT.cs | // 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.IO;
using Internal.Runtime.Augments;
namespace System
{
public static partial class Environment
{
public static string UserName => "Windows User";
public static string UserDomainName => "Windows Domain";
private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
{
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
return callbacks != null && callbacks.IsAppxModel() ?
callbacks.GetFolderPath(folder, option) :
null;
}
}
}
| // 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.IO;
namespace System
{
public static partial class Environment
{
public static string UserName => "Windows User";
public static string UserDomainName => "Windows Domain";
private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
{
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
return callbacks != null && callbacks.IsAppxModel() ?
callbacks.GetFolderPath(folder, option) :
null;
}
}
}
| mit | C# |
13c8701403d6de8cab6dd551c1b5a96765de3fea | resolve available content types | HarshPoint/HarshPoint,the-ress/HarshPoint,NaseUkolyCZ/HarshPoint | HarshPoint/Provisioning/Resolvers/ResolveContentTypeById.cs | HarshPoint/Provisioning/Resolvers/ResolveContentTypeById.cs | using HarshPoint.Provisioning.Implementation;
using Microsoft.SharePoint.Client;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace HarshPoint.Provisioning.Resolvers
{
public sealed class ResolveContentTypeById :
Resolvable<ContentType, HarshContentTypeId, HarshProvisionerContext, ResolveContentTypeById>
{
public ResolveContentTypeById(IEnumerable<HarshContentTypeId> identifiers)
: base(identifiers)
{
}
protected override Task<IEnumerable<ContentType>> ResolveChainElement(ResolveContext<HarshProvisionerContext> context)
{
if (context == null)
{
throw Error.ArgumentNull(nameof(context));
}
return this.ResolveQuery(
ClientObjectResolveQuery.ContentTypeById,
context,
context.ProvisionerContext.Web.ContentTypes,
context.ProvisionerContext.Web.AvailableContentTypes
);
}
}
} | using HarshPoint.Provisioning.Implementation;
using Microsoft.SharePoint.Client;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace HarshPoint.Provisioning.Resolvers
{
public sealed class ResolveContentTypeById :
Resolvable<ContentType, HarshContentTypeId, HarshProvisionerContext, ResolveContentTypeById>
{
public ResolveContentTypeById(IEnumerable<HarshContentTypeId> identifiers)
: base(identifiers)
{
}
protected override Task<IEnumerable<ContentType>> ResolveChainElement(ResolveContext<HarshProvisionerContext> context)
{
if (context == null)
{
throw Error.ArgumentNull(nameof(context));
}
return this.ResolveQuery(
ClientObjectResolveQuery.ContentTypeById,
context,
context.ProvisionerContext.Web.ContentTypes
);
}
}
} | bsd-2-clause | C# |
c3a4eb2248d3b78256f9ccd70fe25cb32f40b780 | Change ChildOrderType to Enum type | kiyoaki/bitflyer-api-dotnet-client | src/BitFlyer.Apis/ResponseData/ChildOrder.cs | src/BitFlyer.Apis/ResponseData/ChildOrder.cs | using Newtonsoft.Json;
namespace BitFlyer.Apis
{
public class ChildOrder
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("child_order_id")]
public string ChildOrderId { get; set; }
[JsonProperty("product_code")]
public ProductCode ProductCode { get; set; }
[JsonProperty("side")]
public Side Side { get; set; }
[JsonProperty("child_order_type")]
public ChildOrderType ChildOrderType { get; set; }
[JsonProperty("price")]
public double Price { get; set; }
[JsonProperty("average_price")]
public double AveragePrice { get; set; }
[JsonProperty("size")]
public double Size { get; set; }
[JsonProperty("child_order_state")]
public ChildOrderState ChildOrderState { get; set; }
[JsonProperty("expire_date")]
public string ExpireDate { get; set; }
[JsonProperty("child_order_date")]
public string ChildOrderDate { get; set; }
[JsonProperty("child_order_acceptance_id")]
public string ChildOrderAcceptanceId { get; set; }
[JsonProperty("outstanding_size")]
public double OutstandingSize { get; set; }
[JsonProperty("cancel_size")]
public double CancelSize { get; set; }
[JsonProperty("executed_size")]
public double ExecutedSize { get; set; }
[JsonProperty("total_commission")]
public double TotalCommission { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
| using Newtonsoft.Json;
namespace BitFlyer.Apis
{
public class ChildOrder
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("child_order_id")]
public string ChildOrderId { get; set; }
[JsonProperty("product_code")]
public ProductCode ProductCode { get; set; }
[JsonProperty("side")]
public Side Side { get; set; }
[JsonProperty("child_order_type")]
public string ChildOrderType { get; set; }
[JsonProperty("price")]
public double Price { get; set; }
[JsonProperty("average_price")]
public double AveragePrice { get; set; }
[JsonProperty("size")]
public double Size { get; set; }
[JsonProperty("child_order_state")]
public ChildOrderState ChildOrderState { get; set; }
[JsonProperty("expire_date")]
public string ExpireDate { get; set; }
[JsonProperty("child_order_date")]
public string ChildOrderDate { get; set; }
[JsonProperty("child_order_acceptance_id")]
public string ChildOrderAcceptanceId { get; set; }
[JsonProperty("outstanding_size")]
public double OutstandingSize { get; set; }
[JsonProperty("cancel_size")]
public double CancelSize { get; set; }
[JsonProperty("executed_size")]
public double ExecutedSize { get; set; }
[JsonProperty("total_commission")]
public double TotalCommission { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
| mit | C# |
7413b72c63d0191a496b1feeec55f1d2fa119b2f | simplify entity configuration registration | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | src/FilterLists.Data/FilterListsDbContext.cs | src/FilterLists.Data/FilterListsDbContext.cs | using FilterLists.Data.Entities;
using FilterLists.Data.Entities.Junctions;
using Microsoft.EntityFrameworkCore;
namespace FilterLists.Data
{
public class FilterListsDbContext : DbContext
{
public FilterListsDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<FilterList> FilterLists { get; set; }
public DbSet<Language> Languages { get; set; }
public DbSet<License> Licenses { get; set; }
public DbSet<Maintainer> Maintainers { get; set; }
public DbSet<Rule> Rules { get; set; }
public DbSet<Snapshot> Snapshots { get; set; }
public DbSet<Software> Software { get; set; }
public DbSet<Syntax> Syntaxes { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Dependent> Dependents { get; set; }
public DbSet<FilterListLanguage> FilterListLanguages { get; set; }
public DbSet<FilterListMaintainer> FilterListMaintainers { get; set; }
public DbSet<FilterListTag> FilterListTags { get; set; }
public DbSet<Fork> Forks { get; set; }
public DbSet<Merge> Merges { get; set; }
public DbSet<SnapshotRule> SnapshotRules { get; set; }
public DbSet<SoftwareSyntax> SoftwareSyntaxes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(FilterListsDbContext).Assembly);
}
}
} | using FilterLists.Data.Entities;
using FilterLists.Data.Entities.Junctions;
using FilterLists.Data.EntityTypeConfigurations;
using FilterLists.Data.EntityTypeConfigurations.Junctions;
using Microsoft.EntityFrameworkCore;
namespace FilterLists.Data
{
public class FilterListsDbContext : DbContext
{
public FilterListsDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<FilterList> FilterLists { get; set; }
public DbSet<Language> Languages { get; set; }
public DbSet<License> Licenses { get; set; }
public DbSet<Maintainer> Maintainers { get; set; }
public DbSet<Rule> Rules { get; set; }
public DbSet<Snapshot> Snapshots { get; set; }
public DbSet<Software> Software { get; set; }
public DbSet<Syntax> Syntaxes { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Dependent> Dependents { get; set; }
public DbSet<FilterListLanguage> FilterListLanguages { get; set; }
public DbSet<FilterListMaintainer> FilterListMaintainers { get; set; }
public DbSet<FilterListTag> FilterListTags { get; set; }
public DbSet<Fork> Forks { get; set; }
public DbSet<Merge> Merges { get; set; }
public DbSet<SnapshotRule> SnapshotRules { get; set; }
public DbSet<SoftwareSyntax> SoftwareSyntaxes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
ApplyConfigurations(modelBuilder);
}
private static void ApplyConfigurations(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new FilterListTypeConfiguration());
modelBuilder.ApplyConfiguration(new LanguageTypeConfiguration());
modelBuilder.ApplyConfiguration(new LicenseTypeConfiguration());
modelBuilder.ApplyConfiguration(new MaintainerTypeConfiguration());
modelBuilder.ApplyConfiguration(new RuleTypeConfiguration());
modelBuilder.ApplyConfiguration(new SnapshotTypeConfiguration());
modelBuilder.ApplyConfiguration(new SoftwareTypeConfiguration());
modelBuilder.ApplyConfiguration(new SyntaxTypeConfiguration());
modelBuilder.ApplyConfiguration(new TagTypeConfiguration());
modelBuilder.ApplyConfiguration(new DependentTypeConfiguration());
modelBuilder.ApplyConfiguration(new FilterListLanguageTypeConfiguration());
modelBuilder.ApplyConfiguration(new FilterListMaintainerTypeConfiguration());
modelBuilder.ApplyConfiguration(new FilterListTagTypeConfiguration());
modelBuilder.ApplyConfiguration(new ForkTypeConfiguration());
modelBuilder.ApplyConfiguration(new MergeTypeConfiguration());
modelBuilder.ApplyConfiguration(new SnapshotRuleTypeConfiguration());
modelBuilder.ApplyConfiguration(new SoftwareSyntaxTypeConfiguration());
}
}
} | mit | C# |
8739acb6b9c17e1b2f804b68e36ded442677c505 | Tweak richtext control size | siege918/quest,textadventures/quest,textadventures/quest,F2Andy/quest,textadventures/quest,siege918/quest,F2Andy/quest,textadventures/quest,siege918/quest,siege918/quest,F2Andy/quest | WebEditor/WebEditor/Views/Edit/Controls/RichTextControl.cshtml | WebEditor/WebEditor/Views/Edit/Controls/RichTextControl.cshtml | @model WebEditor.Models.Controls.RichTextControl
<table>
<tr>
<td style="vertical-align: top">
@Html.TextArea(Model.Control.Attribute, Model.Value, 10, 80, new { @class = "richtext", style = "width: 640px; height: 350px; font-size: 12pt" })
</td>
@if (Model.TextProcessorCommands != null)
{
<td style="vertical-align: top">
@foreach (var commandData in Model.TextProcessorCommands)
{
<button type="button" class="text-processor-helper" data-key="@Model.Control.Attribute" data-insertbefore="@commandData.InsertBefore" data-insertafter="@commandData.InsertAfter">@commandData.Command</button>
<span style="vertical-align: middle">@commandData.Info</span>
<br/>
}
<a href="http://quest5.net/wiki/Text_processor" target="_blank">Text Processor help</a>
</td>
}
</tr>
</table> | @model WebEditor.Models.Controls.RichTextControl
<table>
<tr>
<td style="vertical-align: top">
@Html.TextArea(Model.Control.Attribute, Model.Value, 10, 80, new { @class = "richtext", style = "width: 40em; height: 25em; font-size: 12pt" })
</td>
@if (Model.TextProcessorCommands != null)
{
<td style="vertical-align: top">
@foreach (var commandData in Model.TextProcessorCommands)
{
<button type="button" class="text-processor-helper" data-key="@Model.Control.Attribute" data-insertbefore="@commandData.InsertBefore" data-insertafter="@commandData.InsertAfter">@commandData.Command</button>
<span style="vertical-align: middle">@commandData.Info</span>
<br/>
}
<a href="http://quest5.net/wiki/Text_processor" target="_blank">Text Processor help</a>
</td>
}
</tr>
</table> | mit | C# |
6899a0e3165d28e2bb682344acba89fa57ed7adb | Add BalancingOption documentation | David-Desmaisons/EasyActor | EasyActor/BalancingOption.cs | EasyActor/BalancingOption.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EasyActor
{
/// <summary>
/// Describe the strategy used by the <see cref="ILoadBalancerFactory"/> to create actors
/// </summary>
public enum BalancingOption
{
/// <summary>
/// <see cref="ILoadBalancerFactory"/> prefers actor creation to maximize parrelelism
/// </summary>
PreferParralelism,
/// <summary>
/// <see cref="ILoadBalancerFactory"/> minizes object creations
/// </summary>
MinizeObjectCreation
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EasyActor
{
public enum BalancingOption
{
PreferParralelism,
MinizeObjectCreation
}
} | mit | C# |
97458ec0d0c175e7511fdc1a0118154403474283 | Remove Duplicate Path Parameters | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | src/Server/Bit.WebApi/Implementations/SwaggerDefaultValuesOperationFilter.cs | src/Server/Bit.WebApi/Implementations/SwaggerDefaultValuesOperationFilter.cs | using Swashbuckle.Swagger;
using System.Linq;
using System.Web.Http.Description;
namespace Bit.WebApi.Implementations
{
/// <summary>
/// Represents the Swagger/Swashbuckle operation filter used to provide default values.
/// </summary>
/// <remarks>This <see cref="IOperationFilter"/> is only required due to bugs in the <see cref="SwaggerGenerator"/>.
/// Once they are fixed and published, this class can be removed.</remarks>
public class SwaggerDefaultValuesOperationFilter : IOperationFilter
{
/// <summary>
/// Applies the filter to the specified operation using the given context.
/// </summary>
/// <param name="operation">The operation to apply the filter to.</param>
/// <param name="schemaRegistry">The API schema registry.</param>
/// <param name="apiDescription">The API description being filtered.</param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
{
return;
}
foreach (Parameter parameter in operation.parameters)
{
var parameterName = parameter.name;
if (parameterName.Contains('.'))
parameterName = parameter.name.Split('.')[0];
ApiParameterDescription description = apiDescription.ParameterDescriptions.First(p => p.Name == parameterName);
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1101
if (parameter.description == null)
{
parameter.description = description.Documentation;
}
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1089
// REF: https://github.com/domaindrivendev/Swashbuckle/pull/1090
if (parameter.@default == null)
{
parameter.@default = description.ParameterDescriptor?.DefaultValue;
}
}
}
}
}
| using Swashbuckle.Swagger;
using System.Linq;
using System.Web.Http.Description;
namespace Bit.WebApi.Implementations
{
/// <summary>
/// Represents the Swagger/Swashbuckle operation filter used to provide default values.
/// </summary>
/// <remarks>This <see cref="IOperationFilter"/> is only required due to bugs in the <see cref="SwaggerGenerator"/>.
/// Once they are fixed and published, this class can be removed.</remarks>
public class SwaggerDefaultValuesOperationFilter : IOperationFilter
{
/// <summary>
/// Applies the filter to the specified operation using the given context.
/// </summary>
/// <param name="operation">The operation to apply the filter to.</param>
/// <param name="schemaRegistry">The API schema registry.</param>
/// <param name="apiDescription">The API description being filtered.</param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
{
return;
}
foreach (Parameter parameter in operation.parameters)
{
ApiParameterDescription description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.name);
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1101
if (parameter.description == null)
{
parameter.description = description.Documentation;
}
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1089
// REF: https://github.com/domaindrivendev/Swashbuckle/pull/1090
if (parameter.@default == null)
{
parameter.@default = description.ParameterDescriptor?.DefaultValue;
}
}
}
}
}
| mit | C# |
6a67e52d6c78b8879bbce2bff2ad198de99f8216 | Fix appveyor compiler issues | jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes | ConsoleApps/FunWithSpikes/FunWithCastles/Settings/Adapters/ReadOnlyAdapter.cs | ConsoleApps/FunWithSpikes/FunWithCastles/Settings/Adapters/ReadOnlyAdapter.cs | using System;
namespace FunWithCastles.Settings.Adapters
{
internal class ReadOnlyAdapter : ISettingsAdapter
{
private ISettingsAdapter _adaptee;
public ReadOnlyAdapter(ISettingsAdapter adaptee)
{
if (null == adaptee)
{
throw new ArgumentNullException(nameof(adaptee));
}
_adaptee = adaptee;
}
public object this[string name]
{
get { return _adaptee[name]; }
set
{
new InvalidOperationException($"Reading values is not supported by the {nameof(ReadOnlyAdapter)}");
}
}
public bool CanRead(string name)
{
return _adaptee.CanRead(name);
}
public bool CanWrite(string name)
{
return false;
}
}
} | using System;
namespace FunWithCastles.Settings.Adapters
{
internal class ReadOnlyAdapter : ISettingsAdapter
{
private ISettingsAdapter _adaptee;
public ReadOnlyAdapter(ISettingsAdapter adaptee)
{
_adaptee = adaptee ?? throw new ArgumentNullException(nameof(adaptee));
}
public object this[string name]
{
get => _adaptee[name];
set => new InvalidOperationException($"Reading values is not supported by the {nameof(ReadOnlyAdapter)}");
}
public bool CanRead(string name)
{
return _adaptee.CanRead(name);
}
public bool CanWrite(string name)
{
return false;
}
}
} | mit | C# |
53c27a6a14a6ab01098ba9eb8d0148b751441f37 | Remove obserlete method | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/IoC_Example_Installers/AutofacRegistrar.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/IoC_Example_Installers/AutofacRegistrar.cs | using System;
using System.Data;
using Autofac;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.IoC_Example_Installers
{
public class AutofacRegistrar
{
public void Register(ContainerBuilder builder)
{
builder.Register(c=> new AutofacDbFactory(c)).As<IDbFactory>().SingleInstance();
builder.RegisterType<Dapper.Repository.UnitOfWork.Data.UnitOfWork>().As<IUnitOfWork>();
}
sealed class AutofacDbFactory : IDbFactory
{
private readonly IComponentContext _container;
public AutofacDbFactory(IComponentContext container)
{
_container = container;
}
public T Create<T>() where T : class, ISession
{
return _container.Resolve<T>();
}
public TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel = IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession
{
return _container.Resolve<TUnitOfWork>(new NamedParameter("factory", _container.Resolve <IDbFactory>()),
new NamedParameter("session", Create<TSession>()), new NamedParameter("isolationLevel", isolationLevel)
, new NamedParameter("sessionOnlyForThisUnitOfWork", true));
}
public T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork
{
return _container.Resolve<T>(new NamedParameter("factory", factory),
new NamedParameter("session", session), new NamedParameter("isolationLevel", isolationLevel));
}
public void Release(IDisposable instance)
{
instance.Dispose();
}
}
}
}
| using System;
using System.Data;
using Autofac;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.IoC_Example_Installers
{
public class AutofacRegistrar
{
public void Register(ContainerBuilder builder)
{
builder.Register(c=> new AutofacDbFactory(c)).As<IDbFactory>().SingleInstance();
builder.RegisterType<Dapper.Repository.UnitOfWork.Data.UnitOfWork>().As<IUnitOfWork>();
}
sealed class AutofacDbFactory : IDbFactory
{
private readonly IComponentContext _container;
public AutofacDbFactory(IComponentContext container)
{
_container = container;
}
public T Create<T>() where T : class, ISession
{
return _container.Resolve<T>();
}
public T CreateSession<T>() where T : class, ISession
{
return _container.Resolve<T>();
}
public TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel = IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession
{
return _container.Resolve<TUnitOfWork>(new NamedParameter("factory", _container.Resolve <IDbFactory>()),
new NamedParameter("session", Create<TSession>()), new NamedParameter("isolationLevel", isolationLevel)
, new NamedParameter("sessionOnlyForThisUnitOfWork", true));
}
public T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork
{
return _container.Resolve<T>(new NamedParameter("factory", factory),
new NamedParameter("session", session), new NamedParameter("isolationLevel", isolationLevel));
}
public void Release(IDisposable instance)
{
instance.Dispose();
}
}
}
}
| mit | C# |
a421ce5881269c0ec3c40d55ad47724de9789ad3 | Fix test, mine block with transaction | ajlopez/BlockchainSharp | Src/BlockchainSharp.Tests/Processors/MinerProcessorTests.cs | Src/BlockchainSharp.Tests/Processors/MinerProcessorTests.cs | namespace BlockchainSharp.Tests.Processors
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BlockchainSharp.Stores;
using BlockchainSharp.Processors;
using BlockchainSharp.Tests.TestUtils;
using BlockchainSharp.Core;
[TestClass]
public class MinerProcessorTests
{
[TestMethod]
public void MineBlock()
{
TransactionPool transactionPool = new TransactionPool();
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(0, block.Transactions.Count);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
[TestMethod]
public void MineBlockWithTransaction()
{
TransactionPool transactionPool = new TransactionPool();
Transaction transaction = FactoryHelper.CreateTransaction(1000);
transactionPool.AddTransaction(transaction);
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(1, block.Transactions.Count);
Assert.AreSame(transaction, block.Transactions[0]);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
}
}
| namespace BlockchainSharp.Tests.Processors
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BlockchainSharp.Stores;
using BlockchainSharp.Processors;
using BlockchainSharp.Tests.TestUtils;
using BlockchainSharp.Core;
[TestClass]
public class MinerProcessorTests
{
[TestMethod]
public void MineBlock()
{
TransactionPool transactionPool = new TransactionPool();
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(0, block.Transactions.Count);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
[TestMethod]
public void MineBlockWithTransaction()
{
TransactionPool transactionPool = new TransactionPool();
Transaction transaction = FactoryHelper.CreateTransaction(1000);
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(1, block.Transactions.Count);
Assert.AreSame(transaction, block.Transactions[0]);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
}
}
| mit | C# |
a0aa3c2baf01ad57c4a54bfae18768af707d8fc3 | Fix ambiguous reference to ILogger from Unity 5.3 upwards. | robotlegs-sharp/robotlegs-sharp-framework | src/robotlegs/bender/platforms/unity/extensions/contentView/ContextViewTransformExtension.cs | src/robotlegs/bender/platforms/unity/extensions/contentView/ContextViewTransformExtension.cs | //------------------------------------------------------------------------------
// Copyright (c) 2014-2015 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
using robotlegs.bender.extensions.contextview.api;
using robotlegs.bender.extensions.matching;
using robotlegs.bender.framework.api;
namespace robotlegs.bender.platforms.unity.extensions.contextview
{
public class ContextViewTransformExtension : IExtension
{
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private IInjector _injector;
private ILogger _logger;
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
public void Extend (IContext context)
{
_injector = context.injector;
_logger = context.GetLogger(this);
context.AddConfigHandler(new InstanceOfMatcher (typeof(IContextView)), AddContextView);
}
/*============================================================================*/
/* Private Functions */
/*============================================================================*/
private void AddContextView(object contextViewObject)
{
IContextView contextView = contextViewObject as IContextView;
if (!(contextView.view is UnityEngine.Transform))
{
_logger.Warn ("Cannot map {0} as Transform for the ContextViewTransformExtension to work. Try to configure with 'new TransformContextView(transform)'", contextView.view);
return;
}
if (_injector.HasDirectMapping (typeof(UnityEngine.Transform)))
{
_logger.Warn ("A Transform has already been mapped, ignoring {0}", contextView.view);
return;
}
_logger.Debug("Mapping {0} as Transform", contextView.view);
_injector.Map(typeof(UnityEngine.Transform)).ToValue(contextView.view);
}
}
}
| //------------------------------------------------------------------------------
// Copyright (c) 2014-2015 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
using robotlegs.bender.extensions.contextview.api;
using robotlegs.bender.extensions.matching;
using robotlegs.bender.framework.api;
using UnityEngine;
namespace robotlegs.bender.platforms.unity.extensions.contextview
{
public class ContextViewTransformExtension : IExtension
{
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private IInjector _injector;
private ILogger _logger;
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
public void Extend (IContext context)
{
_injector = context.injector;
_logger = context.GetLogger(this);
context.AddConfigHandler(new InstanceOfMatcher (typeof(IContextView)), AddContextView);
}
/*============================================================================*/
/* Private Functions */
/*============================================================================*/
private void AddContextView(object contextViewObject)
{
IContextView contextView = contextViewObject as IContextView;
if (!(contextView.view is Transform))
{
_logger.Warn ("Cannot map {0} as Transform for the ContextViewTransformExtension to work. Try to configure with 'new TransformContextView(transform)'", contextView.view);
return;
}
if (_injector.HasDirectMapping (typeof(Transform)))
{
_logger.Warn ("A Transform has already been mapped, ignoring {0}", contextView.view);
return;
}
_logger.Debug("Mapping {0} as Transform", contextView.view);
_injector.Map(typeof(Transform)).ToValue(contextView.view);
}
}
}
| mit | C# |
adb4810e09b952e3fb53dd0669310fbc6adb032e | Fix comments | helix-toolkit/helix-toolkit,JeremyAnsel/helix-toolkit,holance/helix-toolkit,chrkon/helix-toolkit,Iluvatar82/helix-toolkit | Source/HelixToolkit.Wpf.SharpDX/Model/Elements3D/PostEffects/PostEffectMeshBorderHighlight.cs | Source/HelixToolkit.Wpf.SharpDX/Model/Elements3D/PostEffects/PostEffectMeshBorderHighlight.cs | using HelixToolkit.Wpf.SharpDX.Core;
namespace HelixToolkit.Wpf.SharpDX
{
/// <summary>
/// Highlight the border of meshes
/// </summary>
/// <seealso cref="HelixToolkit.Wpf.SharpDX.Element3D" />
public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur
{
public PostEffectMeshBorderHighlight()
{
EffectName = DefaultRenderTechniqueNames.PostEffectMeshBorderHighlight;
}
/// <summary>
/// Override this function to set render technique during Attach Host.
/// <para>If <see cref="Element3DCore.OnSetRenderTechnique" /> is set, then <see cref="Element3DCore.OnSetRenderTechnique" /> instead of <see cref="OnCreateRenderTechnique" /> function will be called.</para>
/// </summary>
/// <param name="host"></param>
/// <returns>
/// Return RenderTechnique
/// </returns>
protected override IRenderTechnique OnCreateRenderTechnique(IRenderHost host)
{
return host.EffectsManager[DefaultRenderTechniqueNames.PostEffectMeshBorderHighlight];
}
}
}
| namespace HelixToolkit.Wpf.SharpDX
{
/// <summary>
/// Highlight the border of meshes
/// </summary>
/// <seealso cref="HelixToolkit.Wpf.SharpDX.Element3D" />
public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur
{
public PostEffectMeshBorderHighlight()
{
EffectName = DefaultRenderTechniqueNames.PostEffectMeshBorderHighlight;
}
/// <summary>
/// Override this function to set render technique during Attach Host.
/// <para>If <see cref="Element3DCore.OnSetRenderTechnique" /> is set, then <see cref="Element3DCore.OnSetRenderTechnique" /> instead of <see cref="OnCreateRenderTechnique" /> function will be called.</para>
/// </summary>
/// <param name="host"></param>
/// <returns>
/// Return RenderTechnique
/// </returns>
protected override IRenderTechnique OnCreateRenderTechnique(IRenderHost host)
{
return host.EffectsManager[DefaultRenderTechniqueNames.PostEffectMeshBorderHighlight];
}
}
}
| mit | C# |
cdf9ee5f2df5117a92b4234a76823ff8247c0d43 | add ServiceUrl to private keys | colbylwilliams/XWeather,colbylwilliams/XWeather | XWeather/Shared/Constants/PrivateKeys.cs | XWeather/Shared/Constants/PrivateKeys.cs | namespace XWeather.Constants
{
public static class PrivateKeys
{
public const string WuApiKey = @""; // https://github.com/colbylwilliams/XWeather#weather-underground
public const string GoogleMapsApiKey = @""; // https://github.com/colbylwilliams/XWeather#google-maps-api-key-android
public static class MobileCenter // https://github.com/colbylwilliams/XWeather#mobile-center#visual-studio-mobile-center-optional
{
#if __IOS__
public const string AppSecret = @"";
public const string ServiceUrl = @"";
#elif __ANDROID__
public const string AppSecret = @"";
public const string ServiceUrl = @"";
#endif
}
}
} | namespace XWeather.Constants
{
public static class PrivateKeys
{
public const string WuApiKey = @""; // https://github.com/colbylwilliams/XWeather#weather-underground
public const string GoogleMapsApiKey = @""; // https://github.com/colbylwilliams/XWeather#google-maps-api-key-android
public static class MobileCenter // https://github.com/colbylwilliams/XWeather#mobile-center#visual-studio-mobile-center-optional
{
#if __IOS__
public const string AppSecret = @"";
#elif __ANDROID__
public const string AppSecret = @"";
#endif
}
}
} | mit | C# |
be14d1778061813f0b9ba783d03be3e92989b50a | Fix missing using | iainx/xwt,hwthomas/xwt,akrisiun/xwt,steffenWi/xwt,residuum/xwt,directhex/xwt,antmicro/xwt,mono/xwt,mminns/xwt,TheBrainTech/xwt,sevoku/xwt,mminns/xwt,lytico/xwt,hamekoz/xwt,cra0zy/xwt | Xwt.WPF/Xwt.WPFBackend/DropDownButton.cs | Xwt.WPF/Xwt.WPFBackend/DropDownButton.cs | //
// DropDownButton.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using SWC = System.Windows.Controls;
namespace Xwt.WPFBackend
{
public class DropDownButton
: SWC.Primitives.ToggleButton
{
public event EventHandler<MenuOpeningEventArgs> MenuOpening;
protected override void OnToggle()
{
base.OnToggle();
if (!IsChecked.HasValue || !IsChecked.Value)
return;
var args = new MenuOpeningEventArgs ();
var opening = this.MenuOpening;
if (opening != null)
opening (this, args);
var menu = args.ContextMenu;
if (menu == null) {
IsChecked = false;
return;
}
FocusManager.SetIsFocusScope (menu, false);
string text = Content as string;
if (!String.IsNullOrWhiteSpace (text)) {
SWC.MenuItem selected = menu.Items.OfType<SWC.MenuItem>().FirstOrDefault (i => i.Header as string == text);
if (selected != null)
selected.IsChecked = true;
}
menu.Closed += OnMenuClosed;
menu.PlacementTarget = this;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
private void OnMenuClosed (object sender, RoutedEventArgs e)
{
var menu = sender as SWC.ContextMenu;
if (menu != null)
menu.Closed -= OnMenuClosed;
IsChecked = false;
}
public class MenuOpeningEventArgs
: EventArgs
{
public SWC.ContextMenu ContextMenu
{
get;
set;
}
}
}
} | //
// DropDownButton.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls.Primitives;
using SWC = System.Windows.Controls;
namespace Xwt.WPFBackend
{
public class DropDownButton
: SWC.Primitives.ToggleButton
{
public event EventHandler<MenuOpeningEventArgs> MenuOpening;
protected override void OnToggle()
{
base.OnToggle();
if (!IsChecked.HasValue || !IsChecked.Value)
return;
var args = new MenuOpeningEventArgs ();
var opening = this.MenuOpening;
if (opening != null)
opening (this, args);
var menu = args.ContextMenu;
if (menu == null) {
IsChecked = false;
return;
}
FocusManager.SetIsFocusScope (menu, false);
string text = Content as string;
if (!String.IsNullOrWhiteSpace (text)) {
SWC.MenuItem selected = menu.Items.OfType<SWC.MenuItem>().FirstOrDefault (i => i.Header as string == text);
if (selected != null)
selected.IsChecked = true;
}
menu.Closed += OnMenuClosed;
menu.PlacementTarget = this;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
private void OnMenuClosed (object sender, RoutedEventArgs e)
{
var menu = sender as SWC.ContextMenu;
if (menu != null)
menu.Closed -= OnMenuClosed;
IsChecked = false;
}
public class MenuOpeningEventArgs
: EventArgs
{
public SWC.ContextMenu ContextMenu
{
get;
set;
}
}
}
} | mit | C# |
2c0e8927d35331a7913abf249dec855bbe5bfb86 | Remove key. | Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex | backend/tests/Squidex.Infrastructure.Tests/Assets/AmazonS3AssetStoreFixture.cs | backend/tests/Squidex.Infrastructure.Tests/Assets/AmazonS3AssetStoreFixture.cs | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Infrastructure.Assets
{
public sealed class AmazonS3AssetStoreFixture
{
public AmazonS3AssetStore AssetStore { get; }
public AmazonS3AssetStoreFixture()
{
// From: https://console.aws.amazon.com/iam/home?region=eu-central-1#/users/s3?section=security_credentials
AssetStore = new AmazonS3AssetStore(new AmazonS3Options
{
AccessKey = "key",
Bucket = "squidex-test",
BucketFolder = "squidex-assets",
ForcePathStyle = false,
RegionName = "eu-central-1",
SecretKey = "secret",
ServiceUrl = null
});
AssetStore.InitializeAsync().Wait();
}
}
}
| // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Infrastructure.Assets
{
public sealed class AmazonS3AssetStoreFixture
{
public AmazonS3AssetStore AssetStore { get; }
public AmazonS3AssetStoreFixture()
{
// From: https://console.aws.amazon.com/iam/home?region=eu-central-1#/users/s3?section=security_credentials
AssetStore = new AmazonS3AssetStore(new AmazonS3Options
{
AccessKey = "AKIAYR4IRKRWJVE7BEUV",
Bucket = "squidex-test",
BucketFolder = "squidex-assets",
ForcePathStyle = false,
RegionName = "eu-central-1",
SecretKey = "m7fJ0QzqcQ+2RGaYM7eGRs2QC0efOD+0oHn5UUho",
ServiceUrl = null
});
AssetStore.InitializeAsync().Wait();
}
}
}
| mit | C# |
368fd4326721fdf39ee1d1e42ca1ce475bc911ea | Add a safety check for when Authors is null, which shouldn't happen in the first place. Work items: 1727, 1728 | mdavid/nuget,mdavid/nuget | src/DialogServices/PackageManagerUI/Converters/StringCollectionsToStringConverter.cs | src/DialogServices/PackageManagerUI/Converters/StringCollectionsToStringConverter.cs | using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else if (value == null)
{
return String.Empty;
}
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| apache-2.0 | C# |
00bb6a3eb7c2f83850b012367899a57ea08338ab | Fix - Cambiata chiave degli eventi da id richiesta a codice | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Persistence.MongoDB/GestioneInterventi/GetListaEventiByCodiceRichiesta.cs | src/backend/SO115App.Persistence.MongoDB/GestioneInterventi/GetListaEventiByCodiceRichiesta.cs | using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
public class GetListaEventiByCodiceRichiesta : IGetListaEventi
{
private readonly DbContext _dbContext;
public GetListaEventiByCodiceRichiesta(DbContext dbContext)
{
_dbContext = dbContext;
}
public List<Evento> Get(ListaEventiQuery query)
{
return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Codice, query.IdRichiesta)).Single().Eventi;
}
}
}
| using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
public class GetListaEventiByCodiceRichiesta : IGetListaEventi
{
private readonly DbContext _dbContext;
public GetListaEventiByCodiceRichiesta(DbContext dbContext)
{
_dbContext = dbContext;
}
public List<Evento> Get(ListaEventiQuery query)
{
return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Id, query.IdRichiesta)).Single().Eventi;
}
}
}
| agpl-3.0 | C# |
e5814b6b3df47def9f38183d0322d0bc59fc8d29 | improve EGID structure | sebas77/Svelto.ECS,sebas77/Svelto-ECS | Svelto.ECS/EGID.cs | Svelto.ECS/EGID.cs | using System;
using System.Collections.Generic;
namespace Svelto.ECS
{
public struct EGID:IEquatable<long>,IEqualityComparer<long>
{
long _GID;
public long GID
{
get { return _GID; }
}
public int entityID
{
get { return (int) (_GID & 0xFFFFFFFF); }
}
public int groupID
{
get { return (int) (_GID >> 32); }
}
public EGID(int entityID, int groupID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, groupID);
}
public EGID(int entityID, ExclusiveGroup groupID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, (int) groupID);
}
static long MAKE_GLOBAL_ID(int entityId, int groupId)
{
return (long)groupId << 32 | ((long)(uint)entityId & 0xFFFFFFFF);
}
public bool Equals(long other)
{
return _GID == other;
}
public bool Equals(long x, long y)
{
return x == y;
}
public int GetHashCode(long obj)
{
return _GID.GetHashCode();
}
}
} | namespace Svelto.ECS
{
public struct EGID
{
long _GID;
public long GID
{
get { return _GID; }
}
public int entityID
{
get { return (int) (_GID & 0xFFFFFFFF); }
}
public int groupID
{
get { return (int) (_GID >> 32); }
}
public EGID(int entityID, int groupID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, groupID);
}
public EGID(int entityID, ExclusiveGroup groupID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, (int) groupID);
}
static long MAKE_GLOBAL_ID(int entityId, int groupId)
{
return (long)groupId << 32 | ((long)(uint)entityId & 0xFFFFFFFF);
}
}
} | mit | C# |
ea050ca58bde82369f5568657a43db982e92595b | Make fields in MapPainter readonly | MHeasell/Mappy,MHeasell/Mappy | Mappy/UI/Painters/MapPainter.cs | Mappy/UI/Painters/MapPainter.cs | namespace Mappy.UI.Painters
{
using System.Collections.Generic;
using System.Drawing;
using Mappy.Collections;
public class MapPainter : IPainter
{
private readonly IGrid<Bitmap> map;
private readonly int tileSize;
public MapPainter(IGrid<Bitmap> map, int tileSize)
{
this.map = map;
this.tileSize = tileSize;
}
public void Paint(Graphics g, Rectangle clipRectangle)
{
IEnumerable<Point> enumer = GridUtil.EnumerateCoveringIndices(
clipRectangle,
new Size(this.tileSize, this.tileSize),
new Size(this.map.Width, this.map.Height));
foreach (Point p in enumer)
{
g.DrawImageUnscaled(
this.map[p.X, p.Y],
p.X * this.tileSize,
p.Y * this.tileSize);
}
}
}
}
| namespace Mappy.UI.Painters
{
using System.Collections.Generic;
using System.Drawing;
using Mappy.Collections;
public class MapPainter : IPainter
{
private IGrid<Bitmap> map;
private int tileSize;
public MapPainter(IGrid<Bitmap> map, int tileSize)
{
this.map = map;
this.tileSize = tileSize;
}
public void Paint(Graphics g, Rectangle clipRectangle)
{
IEnumerable<Point> enumer = GridUtil.EnumerateCoveringIndices(
clipRectangle,
new Size(this.tileSize, this.tileSize),
new Size(this.map.Width, this.map.Height));
foreach (Point p in enumer)
{
g.DrawImageUnscaled(
this.map[p.X, p.Y],
p.X * this.tileSize,
p.Y * this.tileSize);
}
}
}
}
| mit | C# |
a1dbce90652bb017b82b272d6cb2d20adbfbee20 | Rename AddEncoders -> AddWebEncoders | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.Framework.WebEncoders/EncoderServiceCollectionExtensions.cs | src/Microsoft.Framework.WebEncoders/EncoderServiceCollectionExtensions.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Internal;
using Microsoft.Framework.WebEncoders;
namespace Microsoft.Framework.DependencyInjection
{
public static class EncoderServiceCollectionExtensions
{
public static IServiceCollection AddWebEncoders([NotNull] this IServiceCollection services)
{
return AddWebEncoders(services, configuration: null);
}
public static IServiceCollection AddWebEncoders([NotNull] this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions(configuration);
services.TryAdd(EncoderServices.GetDefaultServices(configuration));
return services;
}
}
}
| // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Internal;
using Microsoft.Framework.WebEncoders;
namespace Microsoft.Framework.DependencyInjection
{
public static class EncoderServiceCollectionExtensions
{
public static IServiceCollection AddEncoders([NotNull] this IServiceCollection services)
{
return AddEncoders(services, configuration: null);
}
public static IServiceCollection AddEncoders([NotNull] this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions(configuration);
services.TryAdd(EncoderServices.GetDefaultServices(configuration));
return services;
}
}
}
| apache-2.0 | C# |
08be6c11134b6874c706aa52d4b7f7c1421b0c7b | Fix MVVM code style. | GGG-KILLER/GUtils.NET | Tsu.MVVM/ViewModelBase.cs | Tsu.MVVM/ViewModelBase.cs | // Copyright © 2016 GGG KILLER <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the “Software”), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
// the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Tsu.MVVM
{
/// <summary>
/// Implements a few utility functions for a ViewModel base
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>
/// Does the logic for calling <see cref="PropertyChanged"/> if the value has changed (and
/// also sets the value of the field)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="newValue"></param>
/// <param name="propertyName"></param>
[MethodImpl(MethodImplOptions.NoInlining)]
protected virtual void SetField<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
return;
field = newValue;
OnPropertyChanged(propertyName);
}
/// <summary>
/// Invokes <see cref="PropertyChanged"/>
/// </summary>
/// <param name="propertyName"></param>
/// <exception cref="ArgumentNullException">
/// Invoked if a <paramref name="propertyName"/> is not provided (and the value isn't
/// auto-filled by the compiler)
/// </exception>
[MethodImpl(MethodImplOptions.NoInlining)]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(
this,
new PropertyChangedEventArgs(propertyName ?? throw new ArgumentNullException(nameof(propertyName))));
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Tsu.MVVM
{
/// <summary>
/// Implements a few utility functions for a ViewModel base
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>
/// Does the logic for calling <see cref="PropertyChanged"/> if the value has changed (and
/// also sets the value of the field)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="newValue"></param>
/// <param name="propertyName"></param>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void SetField<T> ( ref T field, T newValue, [CallerMemberName] String propertyName = null )
{
if ( EqualityComparer<T>.Default.Equals ( field, newValue ) )
return;
field = newValue;
this.OnPropertyChanged ( propertyName );
}
/// <summary>
/// Invokes <see cref="PropertyChanged"/>
/// </summary>
/// <param name="propertyName"></param>
/// <exception cref="ArgumentNullException">
/// Invoked if a <paramref name="propertyName"/> is not provided (and the value isn't
/// auto-filled by the compiler)
/// </exception>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void OnPropertyChanged ( [CallerMemberName] String propertyName = null ) =>
this.PropertyChanged?.Invoke (
this,
new PropertyChangedEventArgs ( propertyName ?? throw new ArgumentNullException ( nameof ( propertyName ) ) ) );
}
} | mit | C# |
e821a7a1f0d3c24b192a68828e7099d91626514c | Move compilation for docs (#2833) | fassadlr/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode | src/Stratis.SmartContracts.IntegrationTests/TestChain/TestChainExample.cs | src/Stratis.SmartContracts.IntegrationTests/TestChain/TestChainExample.cs | using Stratis.Bitcoin.Features.SmartContracts.Models;
using Stratis.SmartContracts.Executor.Reflection.Compilation;
using Stratis.SmartContracts.Executor.Reflection.Local;
using Stratis.SmartContracts.Test;
using Xunit;
namespace Stratis.SmartContracts.IntegrationTests.TestChain
{
public class TestChainExample
{
[Fact]
public void TestChain_Auction()
{
// Compile the contract we want to deploy
ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/Auction.cs");
Assert.True(compilationResult.Success);
using (Test.TestChain chain = new Test.TestChain().Initialize())
{
// Get an address we can use for deploying
Base58Address deployerAddress = chain.PreloadedAddresses[0];
// Create and send transaction to mempool with parameters
SendCreateContractResult createResult = chain.SendCreateContractTransaction(deployerAddress, compilationResult.Compilation, 0, new object[] {20uL});
// Mine a block which will contain our sent transaction
chain.MineBlocks(1);
// Check the receipt to see that contract deployment was successful
ReceiptResponse receipt = chain.GetReceipt(createResult.TransactionId);
Assert.Equal(deployerAddress, receipt.From);
// Check that the code is indeed saved on-chain
byte[] savedCode = chain.GetCode(createResult.NewContractAddress);
Assert.NotNull(savedCode);
// Use another identity to bid
Base58Address bidderAddress = chain.PreloadedAddresses[1];
// Send a call to the bid method
SendCallContractResult callResult = chain.SendCallContractTransaction(bidderAddress, "Bid", createResult.NewContractAddress, 1);
chain.MineBlocks(1);
// Call a method locally to check the state is as expected
ILocalExecutionResult localCallResult = chain.CallContractMethodLocally(bidderAddress, "HighestBidder", createResult.NewContractAddress, 0);
Address storedHighestBidder = (Address) localCallResult.Return;
Assert.NotEqual(default(Address), storedHighestBidder); // TODO: A nice way of comparing hex and base58 representations
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Stratis.Bitcoin.Features.SmartContracts.Models;
using Stratis.SmartContracts.Executor.Reflection;
using Stratis.SmartContracts.Executor.Reflection.Compilation;
using Stratis.SmartContracts.Executor.Reflection.Local;
using Stratis.SmartContracts.Test;
using Xunit;
namespace Stratis.SmartContracts.IntegrationTests.TestChain
{
public class TestChainExample
{
[Fact]
public void TestChain_Auction()
{
using (Test.TestChain chain = new Test.TestChain().Initialize())
{
// Get an address we can use for deploying
Base58Address deployerAddress = chain.PreloadedAddresses[0];
// Compile the contract we want to deploy
ContractCompilationResult result = ContractCompiler.CompileFile("SmartContracts/Auction.cs");
Assert.True(result.Success);
// Create and send transaction to mempool with parameters
SendCreateContractResult createResult = chain.SendCreateContractTransaction(deployerAddress, result.Compilation, 0, new object[] {20uL});
// Mine a block which will contain our sent transaction
chain.MineBlocks(1);
// Check the receipt to see that contract deployment was successful
ReceiptResponse receipt = chain.GetReceipt(createResult.TransactionId);
Assert.Equal(deployerAddress, receipt.From);
// Check that the code is indeed saved on-chain
byte[] savedCode = chain.GetCode(createResult.NewContractAddress);
Assert.NotNull(savedCode);
// Use another identity to bid
Base58Address bidderAddress = chain.PreloadedAddresses[1];
// Send a call to the bid method
SendCallContractResult callResult = chain.SendCallContractTransaction(bidderAddress, "Bid", createResult.NewContractAddress, 1);
chain.MineBlocks(1);
// Call a method locally to check the state is as expected
ILocalExecutionResult localCallResult = chain.CallContractMethodLocally(bidderAddress, "HighestBidder", createResult.NewContractAddress, 0);
Address storedHighestBidder = (Address) localCallResult.Return;
Assert.NotEqual(default(Address), storedHighestBidder); // TODO: A nice way of comparing hex and base58 representations
}
}
}
}
| mit | C# |
5c8534015ecbadbb075a0ca0443d05a01230de54 | Bump nuget version | mikhailshilkov/With.Fody | With.Fody/AssemblyInfo.cs | With.Fody/AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("With.Fody")]
[assembly: AssemblyProduct("With.Fody")]
[assembly: AssemblyVersion("0.5.1")]
[assembly: AssemblyFileVersion("0.5.1")]
| using System.Reflection;
[assembly: AssemblyTitle("With.Fody")]
[assembly: AssemblyProduct("With.Fody")]
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
| mit | C# |
ac0ec0f6db732cf0caa0ed7bcaf9a9c0cd3d12df | Revert "[DEVOPS-245] verify test failure" | sailthru/sailthru-net-client | Sailthru/Sailthru.Tests/Test.cs | Sailthru/Sailthru.Tests/Test.cs | using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
}
}
}
| using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
Assert.Fail();
}
}
}
| mit | C# |
ce9f69071e3a2e61e6e52f50224d39a2bb8cfeff | change `GetFontSizeByLevel` return value to actual font size | peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework | osu.Framework/Graphics/Containers/Markdown/MarkdownHeading.cs | osu.Framework/Graphics/Containers/Markdown/MarkdownHeading.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax;
using osu.Framework.Allocation;
using osuTK;
namespace osu.Framework.Graphics.Containers.Markdown
{
/// <summary>
/// Visualises a heading.
/// </summary>
/// <code>
/// # H1
/// ## H2
/// ### H3
/// </code>
public class MarkdownHeading : CompositeDrawable, IMarkdownTextFlowComponent
{
private readonly HeadingBlock headingBlock;
[Resolved]
private IMarkdownTextFlowComponent parentFlowComponent { get; set; }
public MarkdownHeading(HeadingBlock headingBlock)
{
this.headingBlock = headingBlock;
AutoSizeAxes = Axes.Y;
RelativeSizeAxes = Axes.X;
}
[BackgroundDependencyLoader]
private void load()
{
MarkdownTextFlowContainer textFlow;
InternalChild = textFlow = CreateTextFlow();
textFlow.Scale = new Vector2(GetFontSizeByLevel(headingBlock.Level));
textFlow.AddInlineText(headingBlock.Inline);
}
public virtual MarkdownTextFlowContainer CreateTextFlow() => parentFlowComponent.CreateTextFlow();
protected virtual float GetFontSizeByLevel(int level)
{
switch (level)
{
case 1:
return 54;
case 2:
return 40;
case 3:
return 30;
case 4:
return 26;
default:
return 20;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax;
using osu.Framework.Allocation;
using osuTK;
namespace osu.Framework.Graphics.Containers.Markdown
{
/// <summary>
/// Visualises a heading.
/// </summary>
/// <code>
/// # H1
/// ## H2
/// ### H3
/// </code>
public class MarkdownHeading : CompositeDrawable, IMarkdownTextFlowComponent
{
private readonly HeadingBlock headingBlock;
[Resolved]
private IMarkdownTextFlowComponent parentFlowComponent { get; set; }
public MarkdownHeading(HeadingBlock headingBlock)
{
this.headingBlock = headingBlock;
AutoSizeAxes = Axes.Y;
RelativeSizeAxes = Axes.X;
}
[BackgroundDependencyLoader]
private void load()
{
MarkdownTextFlowContainer textFlow;
InternalChild = textFlow = CreateTextFlow();
textFlow.Scale = new Vector2(GetFontSizeByLevel(headingBlock.Level));
textFlow.AddInlineText(headingBlock.Inline);
}
public virtual MarkdownTextFlowContainer CreateTextFlow() => parentFlowComponent.CreateTextFlow();
protected virtual float GetFontSizeByLevel(int level)
{
switch (level)
{
case 1:
return 2.7f;
case 2:
return 2;
case 3:
return 1.5f;
case 4:
return 1.3f;
default:
return 1;
}
}
}
}
| mit | C# |
b2a2df31d645d65f3e4b8df3cadb435e5d6681ec | Enable NH-315 fixture since it works now | fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core | src/NHibernate.Test/NHSpecificTest/NH315/Fixture.cs | src/NHibernate.Test/NHSpecificTest/NH315/Fixture.cs | using System;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH315
{
/// <summary>
/// Summary description for Fixture.
/// </summary>
[TestFixture]
public class Fixture : BugTestCase
{
public override string BugNumber
{
get { return "NH315"; }
}
[Test]
public void SaveClient()
{
Client client = new Client();
Person person = new Person();
client.Contacts = new ClientPersons();
using( ISession s = OpenSession() )
{
s.Save( person );
client.Contacts.PersonId = person.Id;
client.Contacts.Person = person;
s.Save( client );
s.Flush();
}
using( ISession s = OpenSession() )
{
s.Delete( client );
s.Delete( person );
s.Flush();
}
}
}
}
| using System;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH315
{
/// <summary>
/// Summary description for Fixture.
/// </summary>
[TestFixture]
[Ignore("Not working, see http://jira.nhibernate.org/browse/NH-315")]
public class Fixture : TestCase
{
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override System.Collections.IList Mappings
{
get
{
return new string[] { "NHSpecificTest.NH315.Mappings.hbm.xml" };
}
}
[Test]
public void SaveClient()
{
Client client = new Client();
Person person = new Person();
client.Contacts = new ClientPersons();
using( ISession s = OpenSession() )
{
s.Save( person );
client.Contacts.PersonId = person.Id;
client.Contacts.Person = person;
s.Save( client );
s.Flush();
}
using( ISession s = OpenSession() )
{
s.Delete( client );
s.Delete( person );
s.Flush();
}
}
}
}
| lgpl-2.1 | C# |
d1cca24e99827591745f6b7fabb6cf2b2b23a825 | update to eventnoteslnk | Paymentsense/Dapper.SimpleSave | PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Event/EventNotesLnkDto.cs | PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Event/EventNotesLnkDto.cs | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Dto.Event
{
[DataContract]
public class EventNotesLnkDto
{
[DataMember]
public Guid EventNotesGuid { get; set; }
[DataMember]
public Guid NotesGuid { get; set; }
[DataMember]
public Guid EventGuid { get; set; }
[DataMember]
public DateTimeOffset UpdateDate { get; set; }
[DataMember]
public Guid UpdateSessionGuid { get; set; }
[DataMember]
public EventTransactionDto Event { get; set; }
[DataMember]
public NotesTransactionDto Notes { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Dto.Event
{
[DataContract]
public class EventNotesLnkDto
{
[DataMember]
public Guid EventNotesGuid { get; set; }
[DataMember]
public Guid NotesGuid { get; set; }
[DataMember]
public Guid EventGuid { get; set; }
[DataMember]
public DateTimeOffset UpdateDate { get; set; }
[DataMember]
public Guid UpdateSessionGuid { get; set; }
[DataMember]
public EventTransactionDto Event { get; set; }
[DataMember]
public IList<NotesTransactionDto> Notes { get; set; }
}
}
| mit | C# |
634864e77ea7f51b06ab587d509dbc5db9a3949f | Update Sqlserver | sunkaixuan/SqlSugar | Src/Asp.Net/SqlSugar/Realization/SqlServer/SqlBuilder/SqlServerInsertBuilder.cs | Src/Asp.Net/SqlSugar/Realization/SqlServer/SqlBuilder/SqlServerInsertBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class SqlServerInsertBuilder:InsertBuilder
{
public override string ToSqlString()
{
if (IsNoInsertNull)
{
DbColumnInfoList = DbColumnInfoList.Where(it => it.Value != null).ToList();
}
var groupList = DbColumnInfoList.GroupBy(it => it.TableId).ToList();
var isSingle = groupList.Count() == 1;
string columnsString = string.Join(",", groupList.First().Select(it => Builder.GetTranslationColumnName(it.DbColumnName)));
if (isSingle)
{
string columnParametersString = string.Join(",", this.DbColumnInfoList.Select(it => Builder.SqlParameterKeyWord + it.DbColumnName));
return string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString);
}
else
{
StringBuilder batchInsetrSql = new StringBuilder();
int pageSize = 200;
if (this.EntityInfo.Columns.Count > 30)
{
pageSize = 50;
}
else if (this.EntityInfo.Columns.Count > 20)
{
pageSize = 100;
}
int pageIndex = 1;
int totalRecord = groupList.Count;
int pageCount = (totalRecord + pageSize - 1) / pageSize;
while (pageCount >= pageIndex)
{
batchInsetrSql.AppendFormat(SqlTemplateBatch, GetTableNameString, columnsString);
int i = 0;
foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
{
var isFirst = i == 0;
if (!isFirst)
{
batchInsetrSql.Append(SqlTemplateBatchUnion);
}
batchInsetrSql.Append("\r\n SELECT " + string.Join(",", columns.Select(it => string.Format(SqlTemplateBatchSelect, FormatValue(it.Value), Builder.GetTranslationColumnName(it.DbColumnName)))));
++i;
}
pageIndex++;
batchInsetrSql.Append("\r\n;\r\n");
}
var result = batchInsetrSql.ToString();
if (this.Context.CurrentConnectionConfig.DbType == DbType.SqlServer)
{
result += "select SCOPE_IDENTITY();";
}
return result;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class SqlServerInsertBuilder:InsertBuilder
{
}
}
| apache-2.0 | C# |
1201fe23dffb6c2ac255f088d765e7d49aab5cf8 | Fix WpfWindowStarter crash leading to failed test | timotei/il-repack,gluck/il-repack | ILRepack.IntegrationTests/Scenarios/AnotherClassLibrary/WpfWindowStarter.cs | ILRepack.IntegrationTests/Scenarios/AnotherClassLibrary/WpfWindowStarter.cs | using System.Windows;
using System.Windows.Threading;
namespace AnotherClassLibrary
{
public class WpfWindowStarter
{
public static void ShowWindowWithControl()
{
Window window = new Window();
window.Content = new ADummyUserControl();
window.Show();
window.Close();
Dispatcher.CurrentDispatcher.InvokeShutdown();
}
}
}
| using System.Windows;
namespace AnotherClassLibrary
{
public class WpfWindowStarter
{
public static void ShowWindowWithControl()
{
Window window = new Window();
window.Content = new ADummyUserControl();
window.Show();
}
}
}
| apache-2.0 | C# |
67a6ee185ca79864a096ef6e87338be0694b166b | fix client side validation, too | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Web/Views/Shared/_ValidationScriptsPartial.cshtml | src/Tugberk.Web/Views/Shared/_ValidationScriptsPartial.cshtml | <script src="~/node_modules/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"></script> | <script src="~/node_modules/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/node_modules/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script> | agpl-3.0 | C# |
bfc9a3a8d214ae83497b6b422e6e4abde51251e0 | Remove debug line | Voxelgon/Voxelgon,Voxelgon/Voxelgon | Assets/Plugins/Voxelgon/Spacecraft/RCSport.cs | Assets/Plugins/Voxelgon/Spacecraft/RCSport.cs | using UnityEngine;
using System.Collections;
public class RCSport : MonoBehaviour {
public GameObject particleSys;
public Animation animator;
public bool portEnabled;
public ShipManager.PortFunction function;
public ShipManager ship;
public void Start() {
particleSys = gameObject.GetComponentInChildren<ParticleSystem>().gameObject;
animator = particleSys.GetComponent<Animation>();
}
public void enable() {
animator.Play("ThrusterEnable");
animator.CrossFadeQueued("ThrusterEffects");
}
public void disable() {
animator.Stop("ThrusterEffects");
animator.Play("ThrusterDisable");
}
public void FixedUpdate() {
if ((ship.controlMatrix[function] == true) && (portEnabled == false)) {
portEnabled = true;
enable();
} else if((ship.controlMatrix[function] == false) && (portEnabled == true)) {
portEnabled = false;
disable();
}
}
}
| using UnityEngine;
using System.Collections;
public class RCSport : MonoBehaviour {
public GameObject particleSys;
public Animation animator;
public bool portEnabled;
public ShipManager.PortFunction function;
public ShipManager ship;
public void Start() {
particleSys = gameObject.GetComponentInChildren<ParticleSystem>().gameObject;
animator = particleSys.GetComponent<Animation>();
}
public void enable() {
animator.Play("ThrusterEnable");
animator.CrossFadeQueued("ThrusterEffects");
}
public void disable() {
animator.Stop("ThrusterEffects");
animator.Play("ThrusterDisable");
}
public void FixedUpdate() {
if ((ship.controlMatrix[function] == true) && (portEnabled == false)) {
portEnabled = true;
enable();
Debug.Log("ENABLE");
} else if((ship.controlMatrix[function] == false) && (portEnabled == true)) {
portEnabled = false;
disable();
}
}
}
| apache-2.0 | C# |
6ebeea7285d2aa094a4386837276f1aa3aadd3f9 | Update footer | GeorgDangl/WebDocu,GeorgDangl/WebDocu,GeorgDangl/WebDocu | src/Dangl.WebDocumentation/Views/Shared/_FooterPartial.cshtml | src/Dangl.WebDocumentation/Views/Shared/_FooterPartial.cshtml | @using Microsoft.Extensions.Options
@inject IOptions<AppSettings> AppSettings
<footer class="ms-footer">
<div class="container">
<p class="d-block d-sm-none">
<div class="row d-block d-sm-none">
<div class="col-md-6 d-block d-sm-none">
<span class="ms-logo">GD</span> © 2015 - @DateTime.Now.Year <a href="https://www.dangl-it.com">Dangl<b>IT</b> GmbH</a>
</div>
<div class="col-md-6 d-block d-sm-none">
<a asp-controller="Home" asp-action="Privacy">
Legal Notice & Privacy
</a>
</div>
</div>
</p>
<p class="d-none d-sm-block">
<span class="ms-logo">GD</span>
© 2015 - @DateTime.Now.Year <a href="https://www.dangl-it.com">Dangl<b>IT</b> GmbH</a> - <a asp-controller="Home" asp-action="Privacy">
Legal Notice & Privacy
</a>
</p>
</div>
</footer>
| @using Microsoft.Extensions.Options
@inject IOptions<AppSettings> AppSettings
<footer class="ms-footer">
<div class="container">
<p class="d-block d-sm-none">
<div class="row d-block d-sm-none">
<div class="col-md-6 d-block d-sm-none">
<span class="ms-logo">GD</span> @AppSettings.Value.SiteTitlePrefix<strong>@AppSettings.Value.SiteTitlePostfix</strong> © 2015 - @DateTime.Now.Year: <a href="https://www.dangl-it.com">Dangl<b>IT</b> GmbH</a>
</div>
<div class="col-md-6 d-block d-sm-none">
<a asp-controller="Home" asp-action="Privacy">
Legal Notice & Privacy
</a>
</div>
</div>
</p>
<p class="d-none d-sm-block">
<span class="ms-logo">GD</span> @AppSettings.Value.SiteTitlePrefix<strong>@AppSettings.Value.SiteTitlePostfix</strong>
© 2015 - @DateTime.Now.Year: <a href="https://www.dangl-it.com">Dangl<b>IT</b> GmbH</a> - <a asp-controller="Home" asp-action="Privacy">
Legal Notice & Privacy
</a>
</p>
</div>
</footer>
| mit | C# |
1aa41cb1d82be24b1fb0931273994ceb51360376 | add additional parameters for InputCommandParameter | LagoVista/DeviceAdmin | src/LagoVista.IoT.DeviceAdmin/Models/InputCommandParameter.cs | src/LagoVista.IoT.DeviceAdmin/Models/InputCommandParameter.cs | using LagoVista.Core.Attributes;
using LagoVista.Core.Models;
using LagoVista.IoT.DeviceAdmin.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.Models
{
[EntityDescription(DeviceAdminDomain.DeviceAdmin, DeviceLibraryResources.Names.InputCommandParameter_Title, DeviceLibraryResources.Names.InputCommandParameter_Help, DeviceLibraryResources.Names.InputCommandParamter_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))]
public class InputCommandParameter
{
public enum InputCommandParameterTypes
{
[EnumLabel("string", DeviceLibraryResources.Names.Parameter_Types_String, typeof(DeviceLibraryResources))]
String,
[EnumLabel("integer", DeviceLibraryResources.Names.Parameter_Types_Integer, typeof(DeviceLibraryResources))]
Integer,
[EnumLabel("decimal", DeviceLibraryResources.Names.Parameter_Types_Decimal, typeof(DeviceLibraryResources))]
Decimal,
[EnumLabel("true-false", DeviceLibraryResources.Names.Parameter_Types_TrueFalse, typeof(DeviceLibraryResources))]
TrueFalse,
[EnumLabel("geolocation", DeviceLibraryResources.Names.Parameter_Types_GeoLocation, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.WorkflowInput_Type_GeoLocation_Help)]
GeoLocation,
}
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_IsRequired, ResourceType: typeof(DeviceLibraryResources))]
public bool IsRequired { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Name, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)]
public String Name { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Key, HelpResource: Resources.DeviceLibraryResources.Names.Common_Key_Help, FieldType: FieldTypes.Key, RegExValidationMessageResource: Resources.DeviceLibraryResources.Names.Common_Key_Validation, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)]
public String Key { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.InputCommandParameter_Type, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, WaterMark: DeviceLibraryResources.Names.Parameter_Type_Watermark)]
public EntityHeader ParameterType { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Description, FieldType: FieldTypes.MultiLineText, ResourceType: typeof(DeviceLibraryResources))]
public String Description { get; set; }
}
}
| using LagoVista.Core.Attributes;
using LagoVista.Core.Models;
using LagoVista.IoT.DeviceAdmin.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.Models
{
[EntityDescription(DeviceAdminDomain.DeviceAdmin, DeviceLibraryResources.Names.InputCommandParameter_Title, DeviceLibraryResources.Names.InputCommandParameter_Help, DeviceLibraryResources.Names.InputCommandParamter_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))]
public class InputCommandParameter
{
public enum InputCommandParameterTypes
{
[EnumLabel("string", DeviceLibraryResources.Names.Parameter_Types_String, typeof(DeviceLibraryResources))]
String,
[EnumLabel("integer", DeviceLibraryResources.Names.Parameter_Types_Integer, typeof(DeviceLibraryResources))]
Integer,
[EnumLabel("decimal", DeviceLibraryResources.Names.Parameter_Types_Decimal, typeof(DeviceLibraryResources))]
Decimal,
[EnumLabel("true-false", DeviceLibraryResources.Names.Parameter_Types_TrueFalse, typeof(DeviceLibraryResources))]
TrueFalse,
[EnumLabel("geolocation", DeviceLibraryResources.Names.Parameter_Types_GeoLocation, typeof(DeviceLibraryResources), DeviceLibraryResources.Names.WorkflowInput_Type_GeoLocation_Help)]
GeoLocation,
}
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_IsRequired, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, IsUserEditable: false)]
public bool IsRequired { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Name, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, IsUserEditable: false)]
public String Name { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Key, HelpResource: Resources.DeviceLibraryResources.Names.Common_Key_Help, FieldType: FieldTypes.Key, RegExValidationMessageResource: Resources.DeviceLibraryResources.Names.Common_Key_Validation, ResourceType: typeof(DeviceLibraryResources), IsRequired: true)]
public String Key { get; set; }
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.InputCommandParameter_Type, ResourceType: typeof(DeviceLibraryResources), IsRequired: true, IsUserEditable: false, WaterMark:DeviceLibraryResources.Names.Parameter_Type_Watermark)]
public EntityHeader ParameterType { get; set; }
}
}
| mit | C# |
2b3c38d623ac8f4eb163bb6516eb64db34c54127 | Fix missed view model reference | aregaz/starcounterdemo,aregaz/starcounterdemo | src/RealEstateAgencyFranchise/Controllers/OfficeController.cs | src/RealEstateAgencyFranchise/Controllers/OfficeController.cs | using RealEstateAgencyFranchise.Database;
using RealEstateAgencyFranchise.ViewModels;
using Starcounter;
using System.Linq;
namespace RealEstateAgencyFranchise.Controllers
{
internal class OfficeController
{
public Json Get(ulong officeObjectNo)
{
return Db.Scope(() =>
{
var offices = Db.SQL<Office>(
"select o from Office o where o.ObjectNo = ?",
officeObjectNo);
if (offices == null || !offices.Any())
{
return new Response()
{
StatusCode = 404,
StatusDescription = "Office not found"
};
}
var office = offices.First;
var json = new OfficeDetailsJson
{
Data = office
};
if (Session.Current == null)
{
Session.Current = new Session(SessionOptions.PatchVersioning);
}
json.Session = Session.Current;
return json;
});
}
}
}
| using RealEstateAgencyFranchise.Database;
using Starcounter;
using System.Linq;
namespace RealEstateAgencyFranchise.Controllers
{
internal class OfficeController
{
public Json Get(ulong officeObjectNo)
{
return Db.Scope(() =>
{
var offices = Db.SQL<Office>(
"select o from Office o where o.ObjectNo = ?",
officeObjectNo);
if (offices == null || !offices.Any())
{
return new Response()
{
StatusCode = 404,
StatusDescription = "Office not found"
};
}
var office = offices.First;
var json = new OfficeListJson
{
Data = office
};
if (Session.Current == null)
{
Session.Current = new Session(SessionOptions.PatchVersioning);
}
json.Session = Session.Current;
return json;
});
}
}
}
| mit | C# |
aaf6dbef3ee777c565ade30722d83ccefc1ae67e | Update post request helper | geeklearningio/Testavior | src/GeekLearning.Test.Integration/Helpers/PostRequestHelper.cs | src/GeekLearning.Test.Integration/Helpers/PostRequestHelper.cs | namespace System.Net.Http
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
// http://www.stefanhendriks.com/2016/05/11/integration-testing-your-asp-net-core-app-dealing-with-anti-request-forgery-csrf-formdata-and-cookies/
public static class PostRequestHelper
{
public static HttpContent CreatePostMessageContent(this object content, string path, Dictionary<string, string> additionalFormPostBodyData = null)
{
var properties = content.GetType().GetProperties();
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var prop in properties.Where(p => !p.PropertyType.IsConstructedGenericType))
{
propValues.Add($"{prop.Name}", prop.GetValue(content)?.ToString());
}
if (additionalFormPostBodyData != null)
{
additionalFormPostBodyData.ToList().ForEach(data => propValues.Add(data.Key, data.Value));
}
return CreatePostMessageContent(path, propValues);
}
public static HttpContent CreatePostMessageContent(string path, Dictionary<string, string> formPostBodyData)
{
return new FormUrlEncodedContent(ToFormPostData(formPostBodyData));
}
private static List<KeyValuePair<string, string>> ToFormPostData(Dictionary<string, string> formPostBodyData)
{
List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
formPostBodyData.Keys.ToList().ForEach(key =>
{
result.Add(new KeyValuePair<string, string>(key, formPostBodyData[key]));
});
return result;
}
}
}
| namespace System.Net.Http
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
// http://www.stefanhendriks.com/2016/05/11/integration-testing-your-asp-net-core-app-dealing-with-anti-request-forgery-csrf-formdata-and-cookies/
public static class PostRequestHelper
{
public static HttpRequestMessage CreatePostMessage(this object content, string path, Dictionary<string, string> additionalFormPostBodyData = null)
{
var properties = content.GetType().GetProperties();
Dictionary<string, string> propValues = new Dictionary<string, string>();
foreach (var prop in properties.Where(p => !p.PropertyType.IsConstructedGenericType))
{
propValues.Add($"{prop.Name}", prop.GetValue(content)?.ToString());
}
if (additionalFormPostBodyData != null)
{
additionalFormPostBodyData.ToList().ForEach(data => propValues.Add(data.Key, data.Value));
}
return CreatePostMessage(path, propValues);
}
public static HttpRequestMessage CreatePostMessage(string path, Dictionary<string, string> formPostBodyData)
{
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, path)
{
Content = new FormUrlEncodedContent(ToFormPostData(formPostBodyData))
};
return httpRequestMessage;
}
private static List<KeyValuePair<string, string>> ToFormPostData(Dictionary<string, string> formPostBodyData)
{
List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
formPostBodyData.Keys.ToList().ForEach(key =>
{
result.Add(new KeyValuePair<string, string>(key, formPostBodyData[key]));
});
return result;
}
}
}
| mit | C# |
5a73c2bf2b192291565a2b7cd8699b80096652ff | Update HtmlEntityInlineRenderer.cs | lunet-io/markdig | src/Markdig/Renderers/Html/Inlines/HtmlEntityInlineRenderer.cs | src/Markdig/Renderers/Html/Inlines/HtmlEntityInlineRenderer.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Syntax.Inlines;
namespace Markdig.Renderers.Html.Inlines
{
/// <summary>
/// A HTML renderer for a <see cref="HtmlEntityInline"/>.
/// </summary>
/// <seealso cref="Markdig.Renderers.Html.HtmlObjectRenderer{Markdig.Syntax.Inlines.HtmlEntityInline}" />
public class HtmlEntityInlineRenderer : HtmlObjectRenderer<HtmlEntityInline>
{
protected override void Write(HtmlRenderer renderer, HtmlEntityInline obj)
{
if (renderer.EnableHtmlForInline)
{
renderer.WriteEscape(obj.Transcoded);
}
else
{
renderer.Write(obj.Transcoded);
}
}
}
}
| // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Syntax.Inlines;
namespace Markdig.Renderers.Html.Inlines
{
/// <summary>
/// A HTML renderer for a <see cref="HtmlEntityInline"/>.
/// </summary>
/// <seealso cref="Markdig.Renderers.Html.HtmlObjectRenderer{Markdig.Syntax.Inlines.HtmlEntityInline}" />
public class HtmlEntityInlineRenderer : HtmlObjectRenderer<HtmlEntityInline>
{
protected override void Write(HtmlRenderer renderer, HtmlEntityInline obj)
{
if (renderer.EnableHtmlForInline)
renderer.WriteEscape(obj.Transcoded);
else
renderer.Write(obj.Transcoded);
}
}
}
| bsd-2-clause | C# |
ba74cd0ebe44c75d74ed5505e4a7431944d7add9 | fix for issue #41 | RichiCoder1/omnisharp-roslyn,sriramgd/omnisharp-roslyn,hitesh97/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,sreal/omnisharp-roslyn,khellang/omnisharp-roslyn,fishg/omnisharp-roslyn,haled/omnisharp-roslyn,hitesh97/omnisharp-roslyn,khellang/omnisharp-roslyn,hach-que/omnisharp-roslyn,jtbm37/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,sreal/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,nabychan/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,fishg/omnisharp-roslyn,nabychan/omnisharp-roslyn,hal-ler/omnisharp-roslyn,filipw/omnisharp-roslyn,hach-que/omnisharp-roslyn,filipw/omnisharp-roslyn,haled/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,hal-ler/omnisharp-roslyn,sriramgd/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,jtbm37/omnisharp-roslyn | src/OmniSharp/Api/Navigation/OmnisharpController.QuickFixes.cs | src/OmniSharp/Api/Navigation/OmnisharpController.QuickFixes.cs | using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
using System.Collections.Generic;
namespace OmniSharp
{
public partial class OmnisharpController
{
private async Task<QuickFix> GetQuickFix(Location location)
{
if (!location.IsInSource)
throw new Exception("Location is not in the source tree");
var lineSpan = location.GetLineSpan();
var path = lineSpan.Path;
var document = _workspace.GetDocument(path);
var line = lineSpan.StartLinePosition.Line;
var syntaxTree = await document.GetSyntaxTreeAsync();
var text = syntaxTree.GetText().Lines[line].ToString();
return new QuickFix
{
Text = text.Trim(),
FileName = path,
Line = line + 1,
Column = lineSpan.StartLinePosition.Character + 1,
EndLine = lineSpan.EndLinePosition.Line + 1,
EndColumn = lineSpan.EndLinePosition.Character + 1
};
}
private async Task AddQuickFix(ICollection<QuickFix> quickFixes, Location location)
{
if (location.IsInSource)
{
var quickFix = await GetQuickFix(location);
quickFixes.Add(quickFix);
}
}
}
} | using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
using System.Collections.Generic;
namespace OmniSharp
{
public partial class OmnisharpController
{
private async Task<QuickFix> GetQuickFix(Location location)
{
if (!location.IsInSource)
throw new Exception("Location is not in the source tree");
var lineSpan = location.GetLineSpan();
var path = lineSpan.Path;
var document = _workspace.GetDocument(path);
var line = lineSpan.StartLinePosition.Line;
var syntaxTree = await document.GetSyntaxTreeAsync();
var text = syntaxTree.GetText().Lines[line].ToString();
return new QuickFix
{
Text = text.Trim(),
FileName = path,
Line = line + 1,
Column = lineSpan.StartLinePosition.Character + 1
};
}
private async Task AddQuickFix(ICollection<QuickFix> quickFixes, Location location)
{
if (location.IsInSource)
{
var quickFix = await GetQuickFix(location);
quickFixes.Add(quickFix);
}
}
}
} | mit | C# |
b66087cc0718af4ef2f28e45ddf26657ae9ec04b | Change time type to long | insthync/LiteNetLibManager,insthync/LiteNetLibManager | Scripts/GameApi/Messages/ServerTimeMessage.cs | Scripts/GameApi/Messages/ServerTimeMessage.cs | using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public long serverUnixTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetPackedLong();
}
public void Serialize(NetDataWriter writer)
{
writer.PutPackedLong(serverUnixTime);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public int serverUnixTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetPackedInt();
}
public void Serialize(NetDataWriter writer)
{
writer.PutPackedInt(serverUnixTime);
}
}
}
| mit | C# |
5bfdb3206882c0bd6af96c076ef54e2fdd305b36 | fix path | jdehlin/Twitta,jdehlin/Twitta | Source/Twitta.Website/Views/Home/Index.cshtml | Source/Twitta.Website/Views/Home/Index.cshtml | @{
Layout = "~/views/shared/_LayoutSite.cshtml";
ViewBag.Title = "Index";
}
| @{
Layout = "_LayoutSite";
ViewBag.Title = "Index";
}
| mit | C# |
f661841ba0adced529faaf0c0e3b0f7505c50f39 | Add documentation for SuppressGCTransition (#27368) | cshung/coreclr,poizan42/coreclr,cshung/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,poizan42/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr | src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SuppressGCTransitionAttribute.cs | src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SuppressGCTransitionAttribute.cs | // 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.
namespace System.Runtime.InteropServices
{
/// <summary>
/// An attribute used to indicate a GC transition should be skipped when making an unmanaged function call.
/// </summary>
/// <example>
/// Example of a valid use case. The Win32 `GetTickCount()` function is a small performance related function
/// that reads some global memory and returns the value. In this case, the GC transition overhead is significantly
/// more than the memory read.
/// <code>
/// using System;
/// using System.Runtime.InteropServices;
/// class Program
/// {
/// [DllImport("Kernel32")]
/// [SuppressGCTransition]
/// static extern int GetTickCount();
/// static void Main()
/// {
/// Console.WriteLine($"{GetTickCount()}");
/// }
/// }
/// </code>
/// </example>
/// <remarks>
/// This attribute is ignored if applied to a method without the <see cref="System.Runtime.InteropServices.DllImportAttribute"/>.
///
/// Forgoing this transition can yield benefits when the cost of the transition is more than the execution time
/// of the unmanaged function. However, avoiding this transition removes some of the guarantees the runtime
/// provides through a normal P/Invoke. When exiting the managed runtime to enter an unmanaged function the
/// GC must transition from Cooperative mode into Preemptive mode. Full details on these modes can be found at
/// https://github.com/dotnet/coreclr/blob/master/Documentation/coding-guidelines/clr-code-guide.md#2.1.8.
/// Suppressing the GC transition is an advanced scenario and should not be done without fully understanding
/// potential consequences.
///
/// One of these consequences is an impact to Mixed-mode debugging (https://docs.microsoft.com/visualstudio/debugger/how-to-debug-in-mixed-mode).
/// During Mixed-mode debugging, it is not possible to step into or set breakpoints in a P/Invoke that
/// has been marked with this attribute. A workaround is to switch to native debugging and set a breakpoint in the native function.
/// In general, usage of this attribute is not recommended if debugging the P/Invoke is important, for example
/// stepping through the native code or diagnosing an exception thrown from the native code.
///
/// The P/Invoke method that this attribute is applied to must have all of the following properties:
/// * Native function always executes for a trivial amount of time (less than 1 microsecond).
/// * Native function does not perform a blocking syscall (e.g. any type of I/O).
/// * Native function does not call back into the runtime (e.g. Reverse P/Invoke).
/// * Native function does not throw exceptions.
/// * Native function does not manipulate locks or other concurrency primitives.
///
/// Consequences of invalid uses of this attribute:
/// * GC starvation.
/// * Immediate runtime termination.
/// * Data corruption.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class SuppressGCTransitionAttribute : Attribute
{
public SuppressGCTransitionAttribute()
{
}
}
} | // 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.
namespace System.Runtime.InteropServices
{
/// <summary>
/// An attribute used to indicate a GC transition should be skipped when making an unmanaged function call.
/// </summary>
/// <remarks>
/// The eventual public attribute should replace this one: https://github.com/dotnet/corefx/issues/40740
/// </remarks>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class SuppressGCTransitionAttribute : Attribute
{
public SuppressGCTransitionAttribute()
{
}
}
} | mit | C# |
664cdcca390ad5229b42f8643c06e737ef68fe25 | Add methods to return DataTables from Attributes | jnwatts/cs320_project2_group11,jnwatts/cs320_project2_group11 | Model/partentry.cs | Model/partentry.cs | using System;
using System.Data;
using System.Collections.Generic;
public class PartEntry
{
public string Part_num { get; set; }
public int Part_type_id { get; set; }
public string Part_type { get; set; }
public Dictionary<string, string> Attributes;
public Dictionary<string, string> ExtendedAttributes;
public PartEntry(string Part_num, int Part_type_id, string Part_type, DataRow attributesRow, DataRow extendedAttributesRow)
{
Attributes = new Dictionary<string, string>();
ExtendedAttributes = new Dictionary<string, string>();
this.Part_num = Part_num;
this.Part_type_id = Part_type_id;
this.Part_type = Part_type;
Util.FillAttributes(attributesRow, Attributes);
if (extendedAttributesRow != null) {
Util.FillAttributes(extendedAttributesRow, ExtendedAttributes);
}
}
public PartEntry(PartEntry other)
{
this.Part_num = other.Part_num;
this.Part_type_id = other.Part_type_id;
this.Part_type = other.Part_type;
this.Attributes = new Dictionary<string, string>(other.Attributes);
this.ExtendedAttributes = new Dictionary<string, string>(other.ExtendedAttributes);
}
public DataTable AttributesDataTable()
{
return Util.AttributesToDataTable("Attributes", Attributes);
}
public DataTable ExtendedAttributesDataTable()
{
return Util.AttributesToDataTable("ExtendedAttributes", ExtendedAttributes);
}
public override String ToString()
{
string str = "{" + Part_num;
foreach (KeyValuePair<string, string> entry in Attributes) {
str += ", " + entry.Key + ": " + entry.Value;
}
foreach (KeyValuePair<string, string> entry in ExtendedAttributes) {
str += ", " + entry.Key + ": " + entry.Value;
}
str += "}";
return str;
}
}
| using System;
using System.Data;
using System.Collections.Generic;
public class PartEntry
{
public string Part_num { get; set; }
public int Part_type_id { get; set; }
public string Part_type { get; set; }
public Dictionary<string, string> Attributes;
public Dictionary<string, string> ExtendedAttributes;
public PartEntry(string Part_num, int Part_type_id, string Part_type, DataRow attributesRow, DataRow extendedAttributesRow)
{
Attributes = new Dictionary<string, string>();
ExtendedAttributes = new Dictionary<string, string>();
this.Part_num = Part_num;
this.Part_type_id = Part_type_id;
this.Part_type = Part_type;
Util.FillAttributes(attributesRow, Attributes);
if (extendedAttributesRow != null) {
Util.FillAttributes(extendedAttributesRow, ExtendedAttributes);
}
}
public PartEntry(PartEntry other)
{
this.Part_num = other.Part_num;
this.Part_type_id = other.Part_type_id;
this.Part_type = other.Part_type;
this.Attributes = new Dictionary<string, string>(other.Attributes);
this.ExtendedAttributes = new Dictionary<string, string>(other.ExtendedAttributes);
}
public override String ToString()
{
string str = "{" + Part_num;
foreach (KeyValuePair<string, string> entry in Attributes) {
str += ", " + entry.Key + ": " + entry.Value;
}
foreach (KeyValuePair<string, string> entry in ExtendedAttributes) {
str += ", " + entry.Key + ": " + entry.Value;
}
str += "}";
return str;
}
}
| apache-2.0 | C# |
c18bd5083c9b1d0a88ac27ba9312ff055b9b4417 | Remove deprecated property Discovery.Parameters now that it is no longer used and now that Execution types can better provide parameter sources directly. | fixie/fixie | src/Fixie/Discovery.cs | src/Fixie/Discovery.cs | namespace Fixie
{
using Internal;
using Internal.Expressions;
/// <summary>
/// Subclass Discovery to customize test discovery rules.
///
/// The default discovery rules are applied to a test assembly whenever the test
/// assembly includes no such subclass.
///
/// By default,
///
/// <para>A class is a test class if its name ends with "Tests".</para>
///
/// <para>All public methods in a test class are test methods.</para>
/// </summary>
public class Discovery
{
public Discovery()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
}
/// <summary>
/// The current state describing the discovery rules. This state can be manipulated through
/// the other properties on Discovery.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
}
} | namespace Fixie
{
using Internal;
using Internal.Expressions;
/// <summary>
/// Subclass Discovery to customize test discovery rules.
///
/// The default discovery rules are applied to a test assembly whenever the test
/// assembly includes no such subclass.
///
/// By default,
///
/// <para>A class is a test class if its name ends with "Tests".</para>
///
/// <para>All public methods in a test class are test methods.</para>
/// </summary>
public class Discovery
{
public Discovery()
{
Config = new Configuration();
Classes = new ClassExpression(Config);
Methods = new MethodExpression(Config);
Parameters = Config.ParameterGenerator;
}
/// <summary>
/// The current state describing the discovery rules. This state can be manipulated through
/// the other properties on Discovery.
/// </summary>
internal Configuration Config { get; }
/// <summary>
/// Defines the set of conditions that describe which classes are test classes.
/// </summary>
public ClassExpression Classes { get; }
/// <summary>
/// Defines the set of conditions that describe which test class methods are test methods,
/// and what order to run them in.
/// </summary>
public MethodExpression Methods { get; }
/// <summary>
/// Defines the set of parameter sources, which provide inputs to parameterized test methods.
/// </summary>
public ParameterGenerator Parameters { get; }
}
} | mit | C# |
56459fb6d3db10e3a3e493b5d2046771a150fb96 | Fix `TemplateGame.iOS` failing to build | peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework | osu.Framework.Templates/templates/template-empty/TemplateGame.iOS/Application.cs | osu.Framework.Templates/templates/template-empty/TemplateGame.iOS/Application.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.iOS;
using UIKit;
namespace TemplateGame.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using UIKit;
namespace TemplateGame.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
| mit | C# |
da157fdc9b835301f103d02a10e706341f9dfd9b | Remove unnecessary using | Tom94/osu-framework,naoey/osu-framework,EVAST9919/osu-framework,default0/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,naoey/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,default0/osu-framework | osu.Framework.Testing/GridTestCase.cs | osu.Framework.Testing/GridTestCase.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Testing
{
/// <summary>
/// An abstract test case which exposes small cells arranged in a grid.
/// Useful for displaying multiple configurations of a tested component at a glance.
/// </summary>
public abstract class GridTestCase : TestCase
{
private FillFlowContainer<Container> testContainer;
/// <summary>
/// The amount of rows of the grid.
/// </summary>
protected int Rows { get; }
/// <summary>
/// The amount of columns of the grid.
/// </summary>
protected int Cols { get; }
/// <summary>
/// Constructs a grid test case with the given dimensions.
/// </summary>
/// <param name="rows">The amount of rows of the grid.</param>
/// <param name="cols">The amount of columns of the grid.</param>
protected GridTestCase(int rows, int cols)
{
Rows = rows;
Cols = cols;
}
private Container createCell() => new Container
{
RelativeSizeAxes = Axes.Both,
Size = new Vector2(1.0f / Cols, 1.0f / Rows),
};
public override void Reset()
{
base.Reset();
testContainer = new FillFlowContainer<Container> { RelativeSizeAxes = Axes.Both };
for (int i = 0; i < Rows * Cols; ++i)
testContainer.Add(createCell());
Add(testContainer);
}
/// <summary>
/// Access a cell by its index. Valid indices range from 0 to <see cref="Rows"/> * <see cref="Cols"/> - 1.
/// </summary>
protected Container Cell(int index) => testContainer.Children[index];
/// <summary>
/// Access a cell by its row and column.
/// </summary>
protected Container Cell(int row, int col) => Cell(col + row * Cols);
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using System.Linq;
namespace osu.Framework.Testing
{
/// <summary>
/// An abstract test case which exposes small cells arranged in a grid.
/// Useful for displaying multiple configurations of a tested component at a glance.
/// </summary>
public abstract class GridTestCase : TestCase
{
private FillFlowContainer<Container> testContainer;
/// <summary>
/// The amount of rows of the grid.
/// </summary>
protected int Rows { get; }
/// <summary>
/// The amount of columns of the grid.
/// </summary>
protected int Cols { get; }
/// <summary>
/// Constructs a grid test case with the given dimensions.
/// </summary>
/// <param name="rows">The amount of rows of the grid.</param>
/// <param name="cols">The amount of columns of the grid.</param>
protected GridTestCase(int rows, int cols)
{
Rows = rows;
Cols = cols;
}
private Container createCell() => new Container
{
RelativeSizeAxes = Axes.Both,
Size = new Vector2(1.0f / Cols, 1.0f / Rows),
};
public override void Reset()
{
base.Reset();
testContainer = new FillFlowContainer<Container> { RelativeSizeAxes = Axes.Both };
for (int i = 0; i < Rows * Cols; ++i)
testContainer.Add(createCell());
Add(testContainer);
}
/// <summary>
/// Access a cell by its index. Valid indices range from 0 to <see cref="Rows"/> * <see cref="Cols"/> - 1.
/// </summary>
protected Container Cell(int index) => testContainer.Children[index];
/// <summary>
/// Access a cell by its row and column.
/// </summary>
protected Container Cell(int row, int col) => Cell(col + row * Cols);
}
}
| mit | C# |
3318f4e909bc663c2033dca88a5665635280bcbc | Remove an assert to allow NecessaryCanonicalEETypeNode for UniversalCanon. | tijoytom/corert,krytarowski/corert,yizhang82/corert,botaberg/corert,botaberg/corert,gregkalapos/corert,krytarowski/corert,krytarowski/corert,shrah/corert,yizhang82/corert,gregkalapos/corert,yizhang82/corert,tijoytom/corert,shrah/corert,tijoytom/corert,gregkalapos/corert,shrah/corert,botaberg/corert,botaberg/corert,shrah/corert,tijoytom/corert,krytarowski/corert,yizhang82/corert,gregkalapos/corert | src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs | src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs | // 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.Diagnostics;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// The node is used in ProjectX to represent a canonical type that does not have a vtable.
/// </summary>
internal sealed class NecessaryCanonicalEETypeNode : EETypeNode
{
public NecessaryCanonicalEETypeNode(NodeFactory factory, TypeDesc type) : base(factory, type)
{
//TODO: This is used temporarily until we switch from STS dependency analysis.
Debug.Assert(factory.Target.Abi == TargetAbi.ProjectN);
Debug.Assert(!type.IsCanonicalDefinitionType(CanonicalFormKind.Any));
Debug.Assert(type.IsCanonicalSubtype(CanonicalFormKind.Any));
Debug.Assert(type == type.ConvertToCanonForm(CanonicalFormKind.Specific));
}
protected override ISymbolNode GetBaseTypeNode(NodeFactory factory)
{
return _type.BaseType != null ? factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(_type.BaseType)) : null;
}
}
} | // 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.Diagnostics;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// The node is used in ProjectX to represent a canonical type that does not have a vtable.
/// </summary>
internal sealed class NecessaryCanonicalEETypeNode : EETypeNode
{
public NecessaryCanonicalEETypeNode(NodeFactory factory, TypeDesc type) : base(factory, type)
{
//TODO: This is used temporarily until we switch from STS dependency analysis.
Debug.Assert(factory.Target.Abi == TargetAbi.ProjectN);
Debug.Assert(!type.IsCanonicalDefinitionType(CanonicalFormKind.Any));
Debug.Assert(type.IsCanonicalSubtype(CanonicalFormKind.Any));
Debug.Assert(type == type.ConvertToCanonForm(CanonicalFormKind.Specific));
Debug.Assert(!type.IsCanonicalSubtype(CanonicalFormKind.Universal));
}
protected override ISymbolNode GetBaseTypeNode(NodeFactory factory)
{
return _type.BaseType != null ? factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(_type.BaseType)) : null;
}
}
} | mit | C# |
703be2b86283a38efcd89fd96fc3d0bb6331085f | Add missing expansion test for EarlyFraudWarning (#1728) | stripe/stripe-dotnet | src/StripeTests/Entities/Radar/EarlyFraudWarnings/EarlyFraudWarningTest.cs | src/StripeTests/Entities/Radar/EarlyFraudWarnings/EarlyFraudWarningTest.cs | namespace StripeTests.Radar
{
using Newtonsoft.Json;
using Stripe;
using Stripe.Radar;
using Xunit;
public class EarlyFraudWarningTest : BaseStripeTest
{
public EarlyFraudWarningTest(StripeMockFixture stripeMockFixture)
: base(stripeMockFixture)
{
}
[Fact]
public void Deserialize()
{
string json = this.GetFixture("/v1/radar/early_fraud_warnings/issfr_123");
var warning = JsonConvert.DeserializeObject<EarlyFraudWarning>(json);
Assert.NotNull(warning);
Assert.IsType<EarlyFraudWarning>(warning);
Assert.NotNull(warning.Id);
Assert.Equal("radar.early_fraud_warning", warning.Object);
}
[Fact]
public void DeserializeWithExpansions()
{
string[] expansions =
{
"charge",
};
string json = this.GetFixture("/v1/radar/early_fraud_warnings/issfr_123", expansions);
var warning = JsonConvert.DeserializeObject<EarlyFraudWarning>(json);
Assert.NotNull(warning);
Assert.IsType<EarlyFraudWarning>(warning);
Assert.NotNull(warning.Id);
Assert.Equal("radar.early_fraud_warning", warning.Object);
Assert.NotNull(warning.Charge);
Assert.Equal("charge", warning.Charge.Object);
}
}
}
| namespace StripeTests.Radar
{
using Newtonsoft.Json;
using Stripe;
using Stripe.Radar;
using Xunit;
public class EarlyFraudWarningTest : BaseStripeTest
{
public EarlyFraudWarningTest(StripeMockFixture stripeMockFixture)
: base(stripeMockFixture)
{
}
[Fact]
public void Deserialize()
{
string json = this.GetFixture("/v1/radar/early_fraud_warnings/issfr_123");
var warning = JsonConvert.DeserializeObject<EarlyFraudWarning>(json);
Assert.NotNull(warning);
Assert.IsType<EarlyFraudWarning>(warning);
Assert.NotNull(warning.Id);
Assert.Equal("radar.early_fraud_warning", warning.Object);
}
}
}
| apache-2.0 | C# |
62d8c867d8fce8ca1e03db191b67f93152467639 | Add description on get custom attribute. | AxeDotNet/AxePractice.CSharpViaTest | src/CSharpViaTest.OtherBCLs/HandleReflections/GetCustomAttributeOfEnumValue.cs | src/CSharpViaTest.OtherBCLs/HandleReflections/GetCustomAttributeOfEnumValue.cs | using System;
using System.Linq;
using System.Reflection;
using Xunit;
namespace CSharpViaTest.OtherBCLs.HandleReflections
{
/*
* Description
* ===========
*
* This test will try get metadata information on MemberInfo. The Attribute class
* can be used on different senarios, which is specified by `AttributeUsage`.
* Since it is metadata, it could be annotated only on definition level, not runtime.
* To get that metadata, you should first get correspond reflection strcuture.
* e.g. Type, MemberInfo.
*
* This test will create an attribute only applied to fields of Enum. You should
* write an extension method to get description attached on metadata.
*
* Difficulty: Medium
*
* Knowledge Point
* ===============
*
* - Enum type.
* - GetType(), GetMember().
*/
static class EnumDescriptionExtension
{
#region Please modifies the code to pass the test
public static string GetDescription<T>(this T value)
{
throw new NotImplementedException();
}
#endregion
}
[AttributeUsage(AttributeTargets.Field)]
class MyEnumDescriptionAttribute : Attribute
{
public MyEnumDescriptionAttribute(string description)
{
Description = description;
}
public string Description { get; }
}
public class GetCustomAttributeOfEnumValue
{
enum ForTest
{
[MyEnumDescription("Awesome name!")]
ValueWithDescription,
ValueWithoutDescription
}
[Fact]
public void should_throw_if_null()
{
Assert.Throws<ArgumentNullException>(() => default(string).GetDescription());
}
[Fact]
public void should_throw_if_not_enum()
{
Assert.Throws<NotSupportedException>(() => 1.GetDescription());
}
[Fact]
public void should_get_custom_attribute()
{
Assert.Equal("Awesome name!", ForTest.ValueWithDescription.GetDescription());
}
[Fact]
public void should_get_origin_value()
{
Assert.Equal("ValueWithoutDescription", ForTest.ValueWithoutDescription.GetDescription());
}
}
} | using System;
using System.Linq;
using System.Reflection;
using Xunit;
namespace CSharpViaTest.OtherBCLs.HandleReflections
{
static class EnumDescriptionExtension
{
public static string GetDescription<T>(this T value)
{
if (!(value is Enum))
{
throw new NotSupportedException();
}
MyEnumDescriptionAttribute attribute = value.GetType()
.GetMember(value.ToString())
.Single()
.GetCustomAttribute<MyEnumDescriptionAttribute>();
return attribute == null ? value.ToString() : attribute.Description;
}
}
[AttributeUsage(AttributeTargets.Field)]
class MyEnumDescriptionAttribute : Attribute
{
public MyEnumDescriptionAttribute(string description)
{
Description = description;
}
public string Description { get; }
}
public class GetCustomAttributeOfEnumValue
{
enum ForTest
{
[MyEnumDescription("Awesome name!")]
ValueWithDescription,
ValueWithoutDescription
}
[Fact]
public void should_throw_if_null()
{
Assert.Throws<ArgumentNullException>(() => default(string).GetDescription());
}
[Fact]
public void should_throw_if_not_enum()
{
Assert.Throws<NotSupportedException>(() => 1.GetDescription());
}
[Fact]
public void should_get_custom_attribute()
{
Assert.Equal("Awesome name!", ForTest.ValueWithDescription.GetDescription());
}
[Fact]
public void should_get_origin_value()
{
Assert.Equal("ValueWithoutDescription", ForTest.ValueWithoutDescription.GetDescription());
}
}
} | mit | C# |
902ec4b7b5647cbb55ecfe9df907bb3d4be66838 | test compiles (does not fix test) | peacekeeper/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk | wrappers/dotnet/indy-sdk-dotnet-test/LedgerTests/PoolRestartRequestTest.cs | wrappers/dotnet/indy-sdk-dotnet-test/LedgerTests/PoolRestartRequestTest.cs | using Hyperledger.Indy.LedgerApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace Hyperledger.Indy.Test.LedgerTests
{
[TestClass]
class PoolRestartRequestTest : IndyIntegrationTestWithPoolAndSingleWallet
{
[TestMethod]
public async Task TestBuildPoolRestartRequestWorks()
{
var expectedResult = string.Format("\"identifier\":\"%s\"," +
"\"operation\":{\"type\":\"118\"," +
"\"action\":\"start\"," +
"\"schedule\":{}", DID1);
var action = "start";
var schedule = "{}";
var poolRestartRequest = ""; //TODO await Ledger.BuildPoolRestartRequestAsync(DID1, action, schedule);
Assert.IsTrue(poolRestartRequest.Replace("\\", "").Contains(expectedResult));
}
}
}
| using Hyperledger.Indy.LedgerApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace Hyperledger.Indy.Test.LedgerTests
{
[TestClass]
class PoolRestartRequestTest : IndyIntegrationTestWithPoolAndSingleWallet
{
[TestMethod]
public async Task TestBuildPoolRestartRequestWorks()
{
var expectedResult = string.Format("\"identifier\":\"%s\"," +
"\"operation\":{\"type\":\"118\"," +
"\"action\":\"start\"," +
"\"schedule\":{}", DID1);
var action = "start";
var schedule = "{}";
//var poolRestartRequest = await Ledger.BuildPoolRestartRequestAsync(DID1, action, schedule);
Assert.IsTrue(poolRestartRequest.Replace("\\", "").Contains(expectedResult));
}
}
}
| apache-2.0 | C# |
a9957c647cd3f4037dc151ae0118297e476c1bac | Fix build failure from the merge to master. | SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia | src/Avalonia.Base/Utilities/StyleClassParser.cs | src/Avalonia.Base/Utilities/StyleClassParser.cs | using System;
using System.Globalization;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class StyleClassParser
{
public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
{
if (IsValidIdentifierStart(r.PeekOneOrThrow))
{
return r.TakeWhile(c => IsValidIdentifierChar(c));
}
else
{
return ReadOnlySpan<char>.Empty;
}
}
private static bool IsValidIdentifierStart(char c)
{
return char.IsLetter(c) || c == '_';
}
private static bool IsValidIdentifierChar(char c)
{
if (IsValidIdentifierStart(c) || c == '-')
{
return true;
}
else
{
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
return cat == UnicodeCategory.NonSpacingMark ||
cat == UnicodeCategory.SpacingCombiningMark ||
cat == UnicodeCategory.ConnectorPunctuation ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.DecimalDigitNumber;
}
}
}
}
| using System;
using System.Globalization;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class StyleClassParser
{
public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
{
if (IsValidIdentifierStart(r.Peek))
{
return r.TakeWhile(c => IsValidIdentifierChar(c));
}
else
{
return ReadOnlySpan<char>.Empty;
}
}
private static bool IsValidIdentifierStart(char c)
{
return char.IsLetter(c) || c == '_';
}
private static bool IsValidIdentifierChar(char c)
{
if (IsValidIdentifierStart(c) || c == '-')
{
return true;
}
else
{
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
return cat == UnicodeCategory.NonSpacingMark ||
cat == UnicodeCategory.SpacingCombiningMark ||
cat == UnicodeCategory.ConnectorPunctuation ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.DecimalDigitNumber;
}
}
}
}
| mit | C# |
05e0b8f35cb83c167e1431a81590476302cf31ea | update AuthorizeAccountV1 to base64 encode id/key | NebulousConcept/b2-csharp-client | b2-csharp-client/B2.Client/Apis/AuthorizeAccountV1/AuthorizeAccountV1Request.cs | b2-csharp-client/B2.Client/Apis/AuthorizeAccountV1/AuthorizeAccountV1Request.cs | using System;
using System.Text;
using B2.Client.Rest.Request;
using B2.Client.Rest.Request.Param;
namespace B2.Client.Apis.AuthorizeAccountV1
{
/// <summary>
/// Request object for the 'b2_authorize_account' version 1 API.
/// </summary>
public class AuthorizeAccountV1Request : MultipartPostRestRequest
{
/// <summary>
/// Create a new authorization request.
/// </summary>
/// <param name="authorization">The authorization header value to use.</param>
/// <param name="accountId">The identifier of the B2 account.</param>
/// <param name="accountKey">The application key to use for the specified account.</param>
public AuthorizeAccountV1Request(string accountId, string accountKey)
: base(UrlParams.Empty,
new HeaderParams(
RequiredParam.Of("Authorization",
"Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(accountId + ":" + accountKey)))
),
BodyParams.Empty,
DataParams.Empty) { }
}
} | using B2.Client.Rest.Request;
using B2.Client.Rest.Request.Param;
namespace B2.Client.Apis.AuthorizeAccountV1
{
/// <summary>
/// Request object for the 'b2_authorize_account' version 1 API.
/// </summary>
public class AuthorizeAccountV1Request : MultipartPostRestRequest
{
/// <summary>
/// Create a new authorization request.
/// </summary>
/// <param name="authorization">The authorization header value to use.</param>
public AuthorizeAccountV1Request(string authorization)
: base(UrlParams.Empty,
new HeaderParams(
RequiredParam.Of("Authorization", authorization)
),
BodyParams.Empty,
DataParams.Empty) { }
}
} | mit | C# |
bc56d4fd341abb70847e22aa5ad19a6bd978f6d2 | Mark CharEnumerator as [Serializable] (dotnet/coreclr#11124) | wtgodbe/corefx,ericstj/corefx,ViktorHofer/corefx,mmitche/corefx,ravimeda/corefx,ViktorHofer/corefx,ravimeda/corefx,ericstj/corefx,mmitche/corefx,BrennanConroy/corefx,Ermiar/corefx,zhenlan/corefx,ericstj/corefx,Jiayili1/corefx,ptoonen/corefx,zhenlan/corefx,ravimeda/corefx,wtgodbe/corefx,mmitche/corefx,ravimeda/corefx,ericstj/corefx,ptoonen/corefx,ptoonen/corefx,Jiayili1/corefx,mmitche/corefx,ViktorHofer/corefx,mmitche/corefx,wtgodbe/corefx,ravimeda/corefx,Jiayili1/corefx,ericstj/corefx,Ermiar/corefx,Ermiar/corefx,shimingsg/corefx,ptoonen/corefx,BrennanConroy/corefx,mmitche/corefx,ViktorHofer/corefx,ptoonen/corefx,Jiayili1/corefx,ptoonen/corefx,BrennanConroy/corefx,zhenlan/corefx,wtgodbe/corefx,zhenlan/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx,zhenlan/corefx,wtgodbe/corefx,shimingsg/corefx,mmitche/corefx,ravimeda/corefx,zhenlan/corefx,Ermiar/corefx,ravimeda/corefx,Ermiar/corefx,Jiayili1/corefx,Ermiar/corefx,ViktorHofer/corefx,ViktorHofer/corefx,Ermiar/corefx,Jiayili1/corefx,zhenlan/corefx,shimingsg/corefx,shimingsg/corefx,ericstj/corefx,Jiayili1/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx | src/Common/src/CoreLib/System/CharEnumerator.cs | src/Common/src/CoreLib/System/CharEnumerator.cs | // 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.
/*============================================================
**
**
**
** Purpose: Enumerates the characters on a string. skips range
** checks.
**
**
============================================================*/
using System.Collections;
using System.Collections.Generic;
namespace System
{
[Serializable]
public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
{
private String _str;
private int _index;
private char _currentElement;
internal CharEnumerator(String str)
{
_str = str;
_index = -1;
}
public object Clone()
{
return MemberwiseClone();
}
public bool MoveNext()
{
if (_index < (_str.Length - 1))
{
_index++;
_currentElement = _str[_index];
return true;
}
else
_index = _str.Length;
return false;
}
public void Dispose()
{
if (_str != null)
_index = _str.Length;
_str = null;
}
Object IEnumerator.Current
{
get { return Current; }
}
public char Current
{
get
{
if (_index == -1)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_index >= _str.Length)
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return _currentElement;
}
}
public void Reset()
{
_currentElement = (char)0;
_index = -1;
}
}
}
| // 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.
/*============================================================
**
**
**
** Purpose: Enumerates the characters on a string. skips range
** checks.
**
**
============================================================*/
using System.Collections;
using System.Collections.Generic;
namespace System
{
public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
{
private String _str;
private int _index;
private char _currentElement;
internal CharEnumerator(String str)
{
_str = str;
_index = -1;
}
public object Clone()
{
return MemberwiseClone();
}
public bool MoveNext()
{
if (_index < (_str.Length - 1))
{
_index++;
_currentElement = _str[_index];
return true;
}
else
_index = _str.Length;
return false;
}
public void Dispose()
{
if (_str != null)
_index = _str.Length;
_str = null;
}
Object IEnumerator.Current
{
get { return Current; }
}
public char Current
{
get
{
if (_index == -1)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_index >= _str.Length)
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return _currentElement;
}
}
public void Reset()
{
_currentElement = (char)0;
_index = -1;
}
}
}
| mit | C# |
e7362f20a5a5522ebbef36559594e432e87ee234 | Update BaseShapeIconConverter.cs | Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D/Converters/BaseShapeIconConverter.cs | src/Core2D/Converters/BaseShapeIconConverter.cs | using System;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Core2D.Shapes;
namespace Core2D.Converters
{
public class BaseShapeIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is BaseShape shape)
{
var key = value.GetType().Name.Replace("Shape", "");
if (Application.Current.Styles.TryGetResource(key, out var resource))
{
return resource;
}
}
return AvaloniaProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Core2D.Shapes;
namespace Core2D.Converters
{
public class BaseShapeIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is BaseShape shape)
{
var key = value.GetType().Name.Replace("Shape", "");
if (Application.Current.Styles.TryGetResource(key, out object resource))
{
return resource;
}
}
return AvaloniaProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
e9b2b3011cccc8df9f356ae6d9737c0dce80fec4 | Make LoggerFactory static. | z000z/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,z000z/couchbase-lite-net,mpapp/couchbase-lite-net,mpapp/couchbase-lite-net,brettharrisonzya/couchbase-lite-net,couchbase/couchbase-lite-net,JiboStore/couchbase-lite-net,brettharrisonzya/couchbase-lite-net,JiboStore/couchbase-lite-net | src/Couchbase.Lite.Shared/Util/LoggerFactory.cs | src/Couchbase.Lite.Shared/Util/LoggerFactory.cs | //
// LoggerFactory.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using Couchbase.Lite.Util;
using Sharpen;
using System;
using System.Diagnostics;
namespace Couchbase.Lite.Util
{
public static class LoggerFactory
{
public static ILogger CreateLogger()
{
return new CustomLogger(SourceLevels.Information);
}
}
}
| //
// LoggerFactory.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using Couchbase.Lite.Util;
using Sharpen;
using System;
using System.Diagnostics;
namespace Couchbase.Lite.Util
{
public class LoggerFactory
{
public static ILogger CreateLogger()
{
return new CustomLogger(SourceLevels.Information);
}
}
}
| apache-2.0 | C# |
553e08e721292dbe21a93fc6f32980ed3a15b3fe | Update assembly version | Ackara/Daterpillar | src/Daterpillar.Core/Properties/AssemblyInfo.cs | src/Daterpillar.Core/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
// 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("Daterpillar.Core")]
[assembly: AssemblyDescription("Daterpillar is a data access and transformation technology for new applications.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Gigobyte")]
[assembly: AssemblyProduct("Daterpillar.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: CLSCompliantAttribute(true)]
// 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.2.16199.106")]
[assembly: AssemblyFileVersion("1.2.16199.106")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
// 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("Daterpillar.Core")]
[assembly: AssemblyDescription("Daterpillar is a data access and transformation technology for new applications.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Gigobyte")]
[assembly: AssemblyProduct("Daterpillar.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: CLSCompliantAttribute(true)]
// 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.2.16171.104")]
[assembly: AssemblyFileVersion("1.2.16171.104")]
| mit | C# |
a3712439f1902f3709ef01296f49c800153df831 | Use RuntimeInfo.IsLinux to check for Linux | EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,Tom94/osu-framework,peppy/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,default0/osu-framework,RedNesto/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,RedNesto/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,default0/osu-framework,naoey/osu-framework,EVAST9919/osu-framework | osu.Framework.Desktop/Platform/Architecture.cs | osu.Framework.Desktop/Platform/Architecture.cs | // Copyright (c) 2007-2016 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Desktop.Platform
{
internal static class Architecture
{
public static string NativeIncludePath => $@"{Environment.CurrentDirectory}/{arch}/";
private static string arch => Is64Bit ? @"x64" : @"x86";
internal static bool Is64Bit => IntPtr.Size == 8;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
internal static void SetIncludePath()
{
if (RuntimeInfo.IsWindows)
SetDllDirectory(NativeIncludePath);
}
}
}
| // Copyright (c) 2007-2016 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Desktop.Platform
{
internal static class Architecture
{
public static string NativeIncludePath => $@"{Environment.CurrentDirectory}/{arch}/";
private static string arch => Is64Bit ? @"x64" : @"x86";
internal static bool Is64Bit => IntPtr.Size == 8;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
internal static void SetIncludePath()
{
//todo: make this not a thing for linux or whatever
try
{
SetDllDirectory(NativeIncludePath);
}
catch { }
}
}
}
| mit | C# |
5b8e35c98cec02b359eb2cf598713638538d349a | Make settings dropdown abstract | peppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu | osu.Game/Overlays/Settings/SettingsDropdown.cs | osu.Game/Overlays/Settings/SettingsDropdown.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public abstract class SettingsDropdown<T> : SettingsItem<T>
{
protected new OsuDropdown<T> Control => (OsuDropdown<T>)base.Control;
public IEnumerable<T> Items
{
get => Control.Items;
set => Control.Items = value;
}
public IBindableList<T> ItemSource
{
get => Control.ItemSource;
set => Control.ItemSource = value;
}
public override IEnumerable<string> FilterTerms => base.FilterTerms.Concat(Control.Items.Select(i => i.ToString()));
protected sealed override Drawable CreateControl() => CreateDropdown();
protected virtual OsuDropdown<T> CreateDropdown() => new DropdownControl();
protected class DropdownControl : OsuDropdown<T>
{
public DropdownControl()
{
Margin = new MarginPadding { Top = 5 };
RelativeSizeAxes = Axes.X;
}
protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 200);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsDropdown<T> : SettingsItem<T>
{
protected new OsuDropdown<T> Control => (OsuDropdown<T>)base.Control;
public IEnumerable<T> Items
{
get => Control.Items;
set => Control.Items = value;
}
public IBindableList<T> ItemSource
{
get => Control.ItemSource;
set => Control.ItemSource = value;
}
public override IEnumerable<string> FilterTerms => base.FilterTerms.Concat(Control.Items.Select(i => i.ToString()));
protected sealed override Drawable CreateControl() => CreateDropdown();
protected virtual OsuDropdown<T> CreateDropdown() => new DropdownControl();
protected class DropdownControl : OsuDropdown<T>
{
public DropdownControl()
{
Margin = new MarginPadding { Top = 5 };
RelativeSizeAxes = Axes.X;
}
protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 200);
}
}
}
| mit | C# |
ac0d67f8e4ac33a1e68a4b58db753a44ce8c659e | fix test | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web.UnitTests/AuthenticationTests/UserServiceTests/UserServiceTestBase.cs | src/SFA.DAS.EmployerUsers.Web.UnitTests/AuthenticationTests/UserServiceTests/UserServiceTestBase.cs | using System.Collections.Generic;
using IdentityServer3.Core.Services;
using MediatR;
using Microsoft.Owin;
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerUsers.Web.Authentication;
namespace SFA.DAS.EmployerUsers.Web.UnitTests.AuthenticationTests.UserServiceTests
{
public abstract class UserServiceTestBase
{
protected Dictionary<string, string[]> _requestQueryString;
protected OwinEnvironmentService _owinEnvironmentService;
protected Mock<IMediator> _mediator;
protected UserService _userService;
[SetUp]
public virtual void Arrange()
{
_requestQueryString = new Dictionary<string, string[]>();
_owinEnvironmentService = new OwinEnvironmentService(new Dictionary<string, object>
{
{ "Microsoft.Owin.Query#dictionary", _requestQueryString }
});
_mediator = new Mock<IMediator>();
_userService = new UserService(_owinEnvironmentService, _mediator.Object);
}
}
}
| using System.Collections.Generic;
using IdentityServer3.Core.Services;
using MediatR;
using Microsoft.Owin;
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerUsers.Web.Authentication;
namespace SFA.DAS.EmployerUsers.Web.UnitTests.AuthenticationTests.UserServiceTests
{
public abstract class UserServiceTestBase
{
protected Dictionary<string, string[]> _requestQueryString;
protected OwinEnvironmentService _owinEnvironmentService;
protected Mock<IMediator> _mediator;
protected UserService _userService;
[SetUp]
public virtual void Arrange()
{
_requestQueryString = new Dictionary<string, string[]>();
_owinEnvironmentService = new OwinEnvironmentService(new Dictionary<string, object>
{
{ "Microsoft.Owin.Query#dictionary", _requestQueryString }
});
_mediator = new Mock<IMediator>();
_userService = new UserService(new OwinContext(_owinEnvironmentService.Environment), _mediator.Object);
}
}
}
| mit | C# |
098000573ab6e9baf31164d1e30c77956aacda12 | Change property name | dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers | src/Services/Catalog/Catalog.API/IntegrationEvents/Events/OrderStockNotConfirmedIntegrationEvent.cs | src/Services/Catalog/Catalog.API/IntegrationEvents/Events/OrderStockNotConfirmedIntegrationEvent.cs | namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
{
using BuildingBlocks.EventBus.Events;
using System.Collections.Generic;
public class OrderStockNotConfirmedIntegrationEvent : IntegrationEvent
{
public int OrderId { get; }
public List<ConfirmedOrderStockItem> OrderStockItems { get; }
public OrderStockNotConfirmedIntegrationEvent(int orderId,
List<ConfirmedOrderStockItem> orderStockItems)
{
OrderId = orderId;
OrderStockItems = orderStockItems;
}
}
public class ConfirmedOrderStockItem
{
public int ProductId { get; }
public bool Confirmed { get; }
public ConfirmedOrderStockItem(int productId, bool confirmed)
{
ProductId = productId;
Confirmed = confirmed;
}
}
} | namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
{
using BuildingBlocks.EventBus.Events;
using System.Collections.Generic;
public class OrderStockNotConfirmedIntegrationEvent : IntegrationEvent
{
public int OrderId { get; }
public IEnumerable<ConfirmedOrderStockItem> OrderStockItem { get; }
public OrderStockNotConfirmedIntegrationEvent(int orderId,
IEnumerable<ConfirmedOrderStockItem> orderStockItem)
{
OrderId = orderId;
OrderStockItem = orderStockItem;
}
}
public class ConfirmedOrderStockItem
{
public int ProductId { get; }
public bool Confirmed { get; }
public ConfirmedOrderStockItem(int productId, bool confirmed)
{
ProductId = productId;
Confirmed = confirmed;
}
}
} | mit | C# |
9ccdb2acc9e79ea3366fdd34fd97397fc353757e | Rename tests to match convention | 7digital/SevenDigital.Api.Schema,scooper91/SevenDigital.Api.Schema | src/Schema.Unit.Tests/Packages/DownloadTests.cs | src/Schema.Unit.Tests/Packages/DownloadTests.cs | using System.Collections.Generic;
using NUnit.Framework;
using SevenDigital.Api.Schema.Packages;
namespace SevenDigital.Api.Schema.Unit.Tests.Packages
{
[TestFixture]
public class PackagesTests
{
[Test]
public void Should_have_no_primary_package_when_there_are_no_packages()
{
var download = new Download();
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Null);
}
[Test]
public void Should_have_primary_package_when_there_is_one_package()
{
var download = new Download
{
Packages = new List<Package>
{
new Package {Id = 123}
}
};
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Not.Null);
Assert.That(primaryPackage.Id, Is.EqualTo(123));
}
[Test]
public void Should_pick_standard_package_if_present()
{
var download = new Download
{
Packages = new List<Package>
{
new Package {Id = 123},
new Package {Id = 456},
new Package {Id = 2},
new Package {Id = 789}
}
};
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Not.Null);
Assert.That(primaryPackage.Id, Is.EqualTo(2));
}
[Test]
public void Should_fall_back_to_first_package()
{
var download = new Download
{
Packages = new List<Package>
{
new Package {Id = 123},
new Package {Id = 456},
new Package {Id = 789}
}
};
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Not.Null);
Assert.That(primaryPackage.Id, Is.EqualTo(123));
}
}
}
| using System.Collections.Generic;
using NUnit.Framework;
using SevenDigital.Api.Schema.Packages;
namespace SevenDigital.Api.Schema.Unit.Tests.Packages
{
[TestFixture]
public class PackagesTests
{
[Test]
public void ShouldHaveNoPrimaryPackageWhenThereAreNoPackages()
{
var download = new Download();
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Null);
}
[Test]
public void ShouldHavePrimaryPackageWhenThereIsOnePackage()
{
var download = new Download
{
Packages = new List<Package>
{
new Package {Id = 123}
}
};
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Not.Null);
Assert.That(primaryPackage.Id, Is.EqualTo(123));
}
[Test]
public void ShouldPickStandardPackageIfPresent()
{
var download = new Download
{
Packages = new List<Package>
{
new Package {Id = 123},
new Package {Id = 456},
new Package {Id = 2},
new Package {Id = 789}
}
};
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Not.Null);
Assert.That(primaryPackage.Id, Is.EqualTo(2));
}
[Test]
public void ShouldFallBackToFirstPackage()
{
var download = new Download
{
Packages = new List<Package>
{
new Package {Id = 123},
new Package {Id = 456},
new Package {Id = 789}
}
};
var primaryPackage = download.PrimaryPackage();
Assert.That(primaryPackage, Is.Not.Null);
Assert.That(primaryPackage.Id, Is.EqualTo(123));
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.