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 |
---|---|---|---|---|---|---|---|---|
43201625c4eed27bfa19c63c38bcda26fb371538 | Fix typo in GetOptimalStringAlignmentDistance doc | MarinAtanasov/AppBrix.NetCore,MarinAtanasov/AppBrix | Modules/AppBrix.Text/IStringDistanceService.cs | Modules/AppBrix.Text/IStringDistanceService.cs | // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
namespace AppBrix.Text
{
/// <summary>
/// Service for getting the distance between strings.
/// </summary>
public interface IStringDistanceService
{
/// <summary>
/// Gets the minimal number of insertions, deletions, symbol substitutions and transpositions
/// required to transform one string into another.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns>The Damerau-Levenshtein distance between the strings.</returns>
int GetDamerauLevenshteinDistance(string left, string right);
/// <summary>
/// Gets the minimal number of insertions, deletions and symbol substitutions
/// required to transform one string into another.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns>The Levenshtein distance between the strings.</returns>
int GetLevenshteinDistance(string left, string right);
/// <summary>
/// Gets the minimal number of insertions, deletions, symbol substitutions and transpositions
/// required to transform one string into another where no substring is edited more than once.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns>The Optimal String Alignment distance between the strings.</returns>
int GetOptimalStringAlignmentDistance(string left, string right);
}
}
| // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
namespace AppBrix.Text
{
/// <summary>
/// Service for getting the distance between strings.
/// </summary>
public interface IStringDistanceService
{
/// <summary>
/// Gets the minimal number of insertions, deletions, symbol substitutions and transpositions
/// required to transform one string into another.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns>The Damerau-Levenshtein distance between the strings.</returns>
int GetDamerauLevenshteinDistance(string left, string right);
/// <summary>
/// Gets the minimal number of insertions, deletions and symbol substitutions
/// required to transform one string into another.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns>The Levenshtein distance between the strings.</returns>
int GetLevenshteinDistance(string left, string right);
/// <summary>
/// Gets the minimal number of insertions, deletions, symbol substitutions and transpositions
/// required to transform one string into another where no substring is edited more than once.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns>The Damerau-Levenshtein distance between the strings.</returns>
int GetOptimalStringAlignmentDistance(string left, string right);
}
}
| mit | C# |
977fffb4697d0bb4e8c6cfa3b76dbc30ffd0211d | Add OrganizationName to OrderAddressDetails (#166) | Viincenttt/MollieApi,Viincenttt/MollieApi | Mollie.Api/Models/Order/OrderAddressDetails.cs | Mollie.Api/Models/Order/OrderAddressDetails.cs | namespace Mollie.Api.Models.Order {
public class OrderAddressDetails : AddressObject {
/// <summary>
/// The person’s organization, if applicable.
/// </summary>
public string OrganizationName { get; set; }
/// <summary>
/// The title of the person, for example Mr. or Mrs..
/// </summary>
public string Title { get; set; }
/// <summary>
/// The given name (first name) of the person.
/// </summary>
public string GivenName { get; set; }
/// <summary>
/// The family name (surname) of the person.
/// </summary>
public string FamilyName { get; set; }
/// <summary>
/// The email address of the person.
/// </summary>
public string Email { get; set; }
/// <summary>
/// The phone number of the person. Some payment methods require this information. If you have it, you
/// should pass it so that your customer does not have to enter it again in the checkout. Must be in
/// the E.164 format. For example +31208202070.
/// </summary>
public string Phone { get; set; }
}
} | namespace Mollie.Api.Models.Order {
public class OrderAddressDetails : AddressObject {
/// <summary>
/// The title of the person, for example Mr. or Mrs..
/// </summary>
public string Title { get; set; }
/// <summary>
/// The given name (first name) of the person.
/// </summary>
public string GivenName { get; set; }
/// <summary>
/// The family name (surname) of the person.
/// </summary>
public string FamilyName { get; set; }
/// <summary>
/// The email address of the person.
/// </summary>
public string Email { get; set; }
/// <summary>
/// The phone number of the person. Some payment methods require this information. If you have it, you
/// should pass it so that your customer does not have to enter it again in the checkout. Must be in
/// the E.164 format. For example +31208202070.
/// </summary>
public string Phone { get; set; }
}
} | mit | C# |
db4033d52f3f74742206f716480f166fae457521 | Improve PluralConverter for XAML | rudyhuyn/PluralNet | PluralNet.Shared/Converters/PluralConverter.cs | PluralNet.Shared/Converters/PluralConverter.cs | #if WINRT || SILVERLIGHT
using System;
using System.Globalization;
#if WINRT
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml.Data;
#elif SILVERLIGHT
using System.Windows.Data;
using System.Resources;
#endif
namespace Huyn.PluralNet.Converters
{
public class PluralConverter : IValueConverter
{
#if SILVERLIGHT
public ResourceManager ResourceManager { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (ResourceManager == null)
{
throw new NullReferenceException("PluralConverter.ResourceManager can't be null");
}
#elif WINRT
public object Convert(object value, Type targetType, object parameter, string language)
{
var culture = !string.IsNullOrWhiteSpace(language) ? new CultureInfo(language) : null;
#endif
var key = parameter as string;
if (string.IsNullOrWhiteSpace(key))
{
return string.Empty;
}
var number = System.Convert.ToDecimal(value);
#if SILVERLIGHT
var pluralFormat = ResourceManager.GetPlural(key, number);
#elif WINRT
var resource = ResourceLoader.GetForCurrentView();
var pluralFormat = resource.GetPlural(key, number);
#endif
return string.Format(culture, pluralFormat, number);
}
#if SILVERLIGHT || DESKTOP
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
#elif WINRT
public object ConvertBack(object value, Type targetType, object parameter, string language)
#endif
{
return null;
}
}
}
#endif | #if WINRT || SILVERLIGHT
using Huyn.PluralNet;
using System;
using System.Globalization;
#if WINRT
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml.Data;
#endif
#if SILVERLIGHT
using System.Windows.Data;
using System.Resources;
#endif
namespace Huyn.PluralNet.Converters
{
public class PluralConverter : IValueConverter
{
#if SILVERLIGHT
public ResourceManager ResourceManager { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (ResourceManager == null)
{
throw new NullReferenceException("PluralConverter.ResourceManager can't be null");
}
var key = parameter as string;
if (string.IsNullOrWhiteSpace(key))
return "";
var number = (decimal)value;
return string.Format(ResourceManager.GetPlural(key, number),number);
}
#endif
#if WINRT
public object Convert(object value, Type targetType, object parameter, string language)
{
var key = parameter as string;
if (string.IsNullOrWhiteSpace(key))
return "";
var number = (decimal)value;
var resource = ResourceLoader.GetForCurrentView();
return string.Format(resource.GetPlural(key, number),number);
}
#endif
#if SILVERLIGHT || DESKTOP
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
#endif
#if WINRT
public object ConvertBack(object value, Type targetType, object parameter, string language)
#endif
{
return null;
}
}
}
#endif | mit | C# |
13dd4face4095db334d02db702f3a4d49c704bb8 | clean up | dkataskin/bstrkr | bstrkr.mobile/bstrkr.tests/MainViewModelTests.cs | bstrkr.mobile/bstrkr.tests/MainViewModelTests.cs | using System;
using System.Threading;
using NUnit.Framework;
using bstrkr.core.config;
using bstrkr.core.services.location;
using bstrkr.core.spatial;
using bstrkr.mvvm.viewmodels;
using bstrkr.tests.infrastructure.services;
namespace bstrkr.mobile.tests
{
[TestFixture]
public class MainViewModelTests
{
private const string Config = @"{
""locations"":[
{
""name"": ""Саранск"",
""locationId"": ""saransk"",
""latitude"": 54.1813447,
""longitude"": 45.1818003,
""endpoint"": ""http://bus13.ru/""
},
{
""name"": ""Рязань"",
""locationId"": ""ryazan"",
""latitude"": 54.6137424,
""longitude"": 39.7211313,
""endpoint"": ""http://bus62.ru/""
},
{
""name"": ""Курск"",
""locationId"": ""kursk"",
""latitude"": 51.7563926,
""longitude"": 36.1851959,
""endpoint"": ""http://bus46.ru/""
}
]
}";
private IConfigManager _configManager;
private ILocationService _locationService;
private MainViewModel _mainViewModel;
[SetUp]
public void SetUp()
{
_configManager = new ConfigManagerStub(Config);
_locationService = new LocationServiceStub(new GeoPoint(54.6, 39.7));
_mainViewModel = new MainViewModel(_configManager, _locationService);
}
[Test]
public void CanDetectLocation()
{
_locationService.StartUpdating();
Thread.Sleep(900);
var location = _mainViewModel.CoarseLocation;
Assert.IsNotNull(location);
Assert.AreEqual("ryazan", location.LocationId);
}
}
} | using System;
using System.Threading;
using NUnit.Framework;
using bstrkr.core.config;
using bstrkr.core.services.location;
using bstrkr.core.spatial;
using bstrkr.mvvm.viewmodels;
using bstrkr.mvvm.viewmodels;
using bstrkr.tests.infrastructure.services;
namespace bstrkr.mobile.tests
{
[TestFixture]
public class MainViewModelTests
{
private const string Config = @"{
""locations"":[
{
""name"": ""Саранск"",
""locationId"": ""saransk"",
""latitude"": 54.1813447,
""longitude"": 45.1818003,
""endpoint"": ""http://bus13.ru/""
},
{
""name"": ""Рязань"",
""locationId"": ""ryazan"",
""latitude"": 54.6137424,
""longitude"": 39.7211313,
""endpoint"": ""http://bus62.ru/""
},
{
""name"": ""Курск"",
""locationId"": ""kursk"",
""latitude"": 51.7563926,
""longitude"": 36.1851959,
""endpoint"": ""http://bus46.ru/""
}
]
}";
private IConfigManager _configManager;
private ILocationService _locationService;
private MainViewModel _mainViewModel;
[SetUp]
public void SetUp()
{
_configManager = new ConfigManagerStub(Config);
_locationService = new LocationServiceStub(new GeoPoint(54.6, 39.7));
_mainViewModel = new MainViewModel(_configManager, _locationService);
}
[Test]
public void CanDetectLocation()
{
_locationService.StartUpdating();
Thread.Sleep(900);
var location = _mainViewModel.CoarseLocation;
Assert.IsNotNull(location);
Assert.AreEqual("ryazan", location.LocationId);
}
}
} | bsd-2-clause | C# |
89e7ba48c01676495eb2e03993d367e9931df546 | Extend interface to support non filesystem based entries. | McNeight/SharpZipLib | src/Zip/IEntryFactory.cs | src/Zip/IEntryFactory.cs | // IEntryFactory.cs
//
// Copyright 2006 John Reilly
//
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// Defines factory methods for creating new <see cref="ZipEntry"></see> values.
/// </summary>
public interface IEntryFactory
{
/// <summary>
/// Create a <see cref="ZipEntry"/> for a file given its name
/// </summary>
/// <param name="fileName">The name of the file to create an entry for.</param>
/// <returns>Returns a <see cref="ZipEntry">file entry</see> based on the <paramref name="fileName"/> passed.</returns>
ZipEntry MakeFileEntry(string fileName);
/// <summary>
/// Create a <see cref="ZipEntry"/> for a file given its name
/// </summary>
/// <param name="fileName">The name of the file to create an entry for.</param>
/// <param name="useFileSystem">If true get details from the file system if the file exists.</param>
/// <returns>Returns a <see cref="ZipEntry">file entry</see> based on the <paramref name="fileName"/> passed.</returns>
ZipEntry MakeFileEntry(string fileName, bool useFileSystem);
/// <summary>
/// Create a <see cref="ZipEntry"/> for a directory given its name
/// </summary>
/// <param name="directoryName">The name of the directory to create an entry for.</param>
/// <returns>Returns a <see cref="ZipEntry">directory entry</see> based on the <paramref name="directoryName"/> passed.</returns>
ZipEntry MakeDirectoryEntry(string directoryName);
/// <summary>
/// Create a <see cref="ZipEntry"/> for a directory given its name
/// </summary>
/// <param name="directoryName">The name of the directory to create an entry for.</param>
/// <param name="useFileSystem">If true get details from the file system for this directory if it exists.</param>
/// <returns>Returns a <see cref="ZipEntry">directory entry</see> based on the <paramref name="directoryName"/> passed.</returns>
ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem);
/// <summary>
/// Get/set the <see cref="INameTransform"></see> applicable.
/// </summary>
INameTransform NameTransform { get; set; }
}
}
| // IEntryFactory.cs
//
// Copyright 2006 John Reilly
//
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// Defines factory methods for creating new <see cref="ZipEntry"></see> values.
/// </summary>
public interface IEntryFactory
{
/// <summary>
/// Create a <see cref="ZipEntry"/> for a file given its name
/// </summary>
/// <param name="fileName">The name of the file to create an entry for.</param>
/// <returns></returns>
ZipEntry MakeFileEntry(string fileName);
/// <summary>
/// Create a <see cref="ZipEntry"/> for a directory given its name
/// </summary>
/// <param name="directoryName">The name of the directory to create an entry for.</param>
/// <returns></returns>
ZipEntry MakeDirectoryEntry(string directoryName);
/// <summary>
/// Get/set the <see cref="INameTransform"></see> applicable.
/// </summary>
INameTransform NameTransform { get; set; }
}
}
| mit | C# |
7fafaebcf606a8c9b35648d8315dbfc58f1d3d01 | Fix for older C# version. (#100) | jesterret/ReClass.NET,KN4CK3R/ReClass.NET,KN4CK3R/ReClass.NET,jesterret/ReClass.NET,jesterret/ReClass.NET,KN4CK3R/ReClass.NET | ReClass.NET/Extensions/XAttributeExtensions.cs | ReClass.NET/Extensions/XAttributeExtensions.cs | using System;
using System.Xml.Linq;
namespace ReClassNET.Extensions
{
public static class XAttributeExtensions
{
public static TEnum GetEnumValue<TEnum>(this XAttribute attribute) where TEnum : struct
{
TEnum @enum = default(TEnum);
if (attribute != null)
{
Enum.TryParse(attribute.Value, out @enum);
}
return @enum;
}
}
}
| using System;
using System.Xml.Linq;
namespace ReClassNET.Extensions
{
public static class XAttributeExtensions
{
public static TEnum GetEnumValue<TEnum>(this XAttribute attribute) where TEnum : struct, Enum
{
TEnum @enum = default;
if (attribute != null)
{
Enum.TryParse(attribute.Value, out @enum);
}
return @enum;
}
}
}
| mit | C# |
ca20a57c2a4b3a491468708b2e797006a36a01eb | Add change missed in #6106. (#6119) | yevhen/orleans,ElanHasson/orleans,hoopsomuah/orleans,dotnet/orleans,veikkoeeva/orleans,dotnet/orleans,amccool/orleans,waynemunro/orleans,yevhen/orleans,ElanHasson/orleans,ibondy/orleans,jason-bragg/orleans,waynemunro/orleans,ReubenBond/orleans,galvesribeiro/orleans,galvesribeiro/orleans,ibondy/orleans,hoopsomuah/orleans,amccool/orleans,benjaminpetit/orleans,amccool/orleans,jthelin/orleans | Samples/3.0/HelloWorld/src/SiloHost/Program.cs | Samples/3.0/HelloWorld/src/SiloHost/Program.cs | using System.Net;
using System.Threading.Tasks;
using HelloWorld.Grains;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
namespace OrleansSiloHost
{
public class Program
{
public static Task Main(string[] args)
{
return new HostBuilder()
.UseOrleans(builder =>
{
builder
.UseLocalhostClustering()
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "dev";
options.ServiceId = "HelloWorldApp";
})
.Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback)
.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(HelloGrain).Assembly).WithReferences())
.AddMemoryGrainStorage(name: "ArchiveStorage")
.AddAzureBlobGrainStorage(
name: "profileStore",
configureOptions: options =>
{
// Use JSON for serializing the state in storage
options.UseJson = true;
// Configure the storage connection key
options.ConnectionString = "DefaultEndpointsProtocol=https;AccountName=data1;AccountKey=SOMETHING1";
});
})
.ConfigureServices(services =>
{
services.Configure<ConsoleLifetimeOptions>(options =>
{
options.SuppressStatusMessages = true;
});
})
.ConfigureLogging(builder =>
{
builder.AddConsole();
})
.RunConsoleAsync();
}
}
}
| using System.Net;
using System.Threading.Tasks;
using HelloWorld.Grains;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
namespace OrleansSiloHost
{
public class Program
{
public static Task Main(string[] args)
{
return new HostBuilder()
.UseOrleans(builder =>
{
builder
.UseLocalhostClustering()
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "dev";
options.ServiceId = "HelloWorldApp";
})
.Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback)
.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(HelloGrain).Assembly).WithReferences())
.AddMemoryGrainStorage(name: "ArchiveStorage");
})
.ConfigureServices(services =>
{
services.Configure<ConsoleLifetimeOptions>(options =>
{
options.SuppressStatusMessages = true;
});
})
.ConfigureLogging(builder =>
{
builder.AddConsole();
})
.RunConsoleAsync();
}
}
}
| mit | C# |
fc9229f562fa115f3e0d18bcb2bf661074157d2a | Update test cases again | ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp | source/Htc.Vita.Core.Tests/TestCase.UsbManager.cs | source/Htc.Vita.Core.Tests/TestCase.UsbManager.cs | using System;
using Htc.Vita.Core.IO;
using Htc.Vita.Core.Runtime;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public partial class TestCase
{
[Fact]
public void UsbManager_Default_0_GetDevices()
{
if (!Platform.IsWindows)
{
return;
}
var deviceInfos = UsbManager.GetHidDevices();
foreach (var deviceInfo in deviceInfos) {
Console.WriteLine("deviceInfo.Path: " + deviceInfo.Path);
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Path));
var productId = deviceInfo.ProductId;
if (!string.IsNullOrEmpty(productId))
{
Assert.True(productId.Length == 4);
}
var vendorId = deviceInfo.VendorId;
if (!string.IsNullOrEmpty(vendorId))
{
Assert.True(vendorId.Length == 4);
}
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Description));
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Manufecturer));
var optional = deviceInfo.Optional;
if (optional.ContainsKey("type"))
{
Assert.False(string.IsNullOrWhiteSpace(optional["type"]));
}
}
}
}
}
| using System;
using Htc.Vita.Core.IO;
using Htc.Vita.Core.Runtime;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public partial class TestCase
{
[Fact]
public void UsbManager_Default_0_GetDevices()
{
if (!Platform.IsWindows)
{
return;
}
var deviceInfos = UsbManager.GetHidDevices();
foreach (var deviceInfo in deviceInfos) {
Console.WriteLine("deviceInfo.Path: " + deviceInfo.Path);
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Path));
Assert.True(string.IsNullOrEmpty(deviceInfo.ProductId) || deviceInfo.ProductId.Length == 4);
Assert.True(string.IsNullOrEmpty(deviceInfo.VendorId) || deviceInfo.VendorId.Length == 4);
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Description));
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Manufecturer));
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Optional["type"]));
}
}
}
}
| mit | C# |
82cadea3f23d2af8d1da6f92a48b5a2f0b784d2f | Fix issues with endpoint add of alert controller. | ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton | src/CK.Glouton.Web/Controllers/AlertController.cs | src/CK.Glouton.Web/Controllers/AlertController.cs | using CK.Glouton.Model.Server.Handlers.Implementation;
using CK.Glouton.Model.Services;
using Microsoft.AspNetCore.Mvc;
namespace CK.Glouton.Web.Controllers
{
[Route( "api/alert" )]
public class AlertController : Controller
{
private readonly IAlertService _alertService;
public AlertController( IAlertService alertService )
{
_alertService = alertService;
}
[HttpPost( "add" )]
public object AddAlert( [FromBody] AlertExpressionModel alertExpressionModel )
{
if( _alertService.NewAlertRequest( alertExpressionModel ) )
return NoContent();
return BadRequest();
}
[HttpGet( "configuration/{key}" )]
public object GetConfiguration( string key )
{
if( _alertService.TryGetConfiguration( key, out var configuration ) )
return configuration;
return BadRequest();
}
[HttpGet( "configuration" )]
public string[] GetAllConfiguration()
{
return _alertService.AvailableConfiguration;
}
[HttpGet( "all" )]
public object GetAllAlerts()
{
return _alertService.GetAllAlerts();
}
}
} | using CK.Glouton.Model.Server.Handlers.Implementation;
using CK.Glouton.Model.Services;
using Microsoft.AspNetCore.Mvc;
namespace CK.Glouton.Web.Controllers
{
[Route( "api/alert" )]
public class AlertController : Controller
{
private readonly IAlertService _alertService;
public AlertController( IAlertService alertService )
{
_alertService = alertService;
}
[HttpPost( "add" )]
public object AddAlert( [FromBody] AlertExpressionModel alertExpressionModel )
{
if( _alertService.NewAlertRequest( alertExpressionModel ) )
return Ok();
return BadRequest();
}
[HttpGet( "configuration/{key}" )]
public object GetConfiguration( string key )
{
if( _alertService.TryGetConfiguration( key, out var configuration ) )
return configuration;
return BadRequest();
}
[HttpGet( "configuration" )]
public string[] GetAllConfiguration()
{
return _alertService.AvailableConfiguration;
}
[HttpGet( "all" )]
public object GetAllAlerts()
{
return _alertService.GetAllAlerts();
}
}
} | mit | C# |
cc322956d7d0a196e4159c7b9ed3b4f3aecf77c0 | Set version 0.9.1 | hazzik/DelegateDecompiler,jaenyph/DelegateDecompiler,morgen2009/DelegateDecompiler | src/DelegateDecompiler/Properties/AssemblyInfo.cs | src/DelegateDecompiler/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DelegateDecompiler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DelegateDecompiler")]
[assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")]
// 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("0.9.1.0")]
[assembly: AssemblyFileVersion("0.9.1.0")]
[assembly: InternalsVisibleTo("DelegateDecompiler.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c96a47f445d38b9b23cbf52e405743481cb9bd2df4672ad6494abcdeb9daf5588eb6159cc88af5fd5a18cece1f05ecb3ddba4b6329535438f4d173f2b769c4715c136ce65c2f25e7360916737056bca40bee22ab2f178af4c5fdc0e5051a6b2630f31447885eb4f5273271c56bd7b8fb240ab453635a79ec2d8aae4a58a6439f")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DelegateDecompiler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DelegateDecompiler")]
[assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")]
// 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("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
[assembly: InternalsVisibleTo("DelegateDecompiler.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c96a47f445d38b9b23cbf52e405743481cb9bd2df4672ad6494abcdeb9daf5588eb6159cc88af5fd5a18cece1f05ecb3ddba4b6329535438f4d173f2b769c4715c136ce65c2f25e7360916737056bca40bee22ab2f178af4c5fdc0e5051a6b2630f31447885eb4f5273271c56bd7b8fb240ab453635a79ec2d8aae4a58a6439f")]
| mit | C# |
a171f004407218ca227cd128e8fd72e88cdb63cc | Fix broken link | martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site | src/LondonTravel.Site/Views/Shared/_Footer.cshtml | src/LondonTravel.Site/Views/Shared/_Footer.cshtml | @model SiteOptions
<hr />
<footer>
<p class="hidden-sm hidden-xs">
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a asp-route="PrivacyPolicy" title="View the London Travel Alexa skill's Privacy Policy">
Privacy Policy
</a>
|
<a asp-route="TermsOfService" title="View the London Travel Alexa skill's Terms of Service">
Terms of Service
</a>
|
<a href="@Model.ExternalLinks.Status.AbsoluteUri" rel="noopener" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
<span id="build-date" data-format="YYYY-MM-DD HH:mm Z" data-timestamp="@GitMetadata.Timestamp.ToString("u", CultureInfo.InvariantCulture)"></span>
</p>
<div class="row hidden-md hidden-lg">
<div class="col-sm-12 col-xs-12">
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year
</div>
<div class="col-sm-12 col-xs-12">
<a asp-route="PrivacyPolicy" title="View the London Travel Alexa skill's Privacy Policy">
Privacy Policy
</a>
|
<a asp-route="TermsOfService" title="View the London Travel Alexa skill's Terms of Service">
Terms of Service
</a>
</div>
</div>
</footer>
| @model SiteOptions
<hr />
<footer>
<p class="hidden-sm hidden-xs">
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a asp-route="PrivacyPolicy" title="View the London Travel Alexa skill's Privacy Policy">
Privacy Policy
</a>
|
<a asp-route="TermsOfService" title="View the London Travel Alexa skill's Terms of Service">
Terms of Service
</a>
|
<a ref="@Model.ExternalLinks.Status.AbsoluteUri" rel="noopener" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
<span id="build-date" data-format="YYYY-MM-DD HH:mm Z" data-timestamp="@GitMetadata.Timestamp.ToString("u", CultureInfo.InvariantCulture)"></span>
</p>
<div class="row hidden-md hidden-lg">
<div class="col-sm-12 col-xs-12">
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year
</div>
<div class="col-sm-12 col-xs-12">
<a asp-route="PrivacyPolicy" title="View the London Travel Alexa skill's Privacy Policy">
Privacy Policy
</a>
|
<a asp-route="TermsOfService" title="View the London Travel Alexa skill's Terms of Service">
Terms of Service
</a>
</div>
</div>
</footer>
| apache-2.0 | C# |
ed366dc423d6755f8821d4adb1c9903816223e55 | Add 7 | wallyjue/online_judge,wallyjue/online_judge,wallyjue/online_judge,wallyjue/online_judge,wallyjue/online_judge | leetcode/C_sharp/online_judge/leetcode/easy/Problem_7.cs | leetcode/C_sharp/online_judge/leetcode/easy/Problem_7.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace online_judge.leetcode.easy
{
class Problem_7
{
public int Reverse(int x)
{
bool isNegative = x < 0;
int[] numbers = new int[10];
int decimals = 0;
int ret = 0;
x = isNegative ? -x : x;
for(int radix = 0, number = 0, mod = 10, power = 1; radix < 10; radix++)
{
numbers[radix] = radix < 9 ? (x % mod) / power : x / power;
if (numbers[radix] != 0) decimals = radix;
mod *= 10;
power *= 10;
}
for (int cnt = 0; cnt <= decimals; cnt++)
{
if (ret * 10 / 10 != ret) return 0;
ret = ret * 10 + numbers[cnt];
}
return isNegative ? -ret : ret;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace online_judge.leetcode.easy
{
class Problem_7
{
public int Reverse(int x)
{
for(int radix = 0; radix < 10; radix++)
{
}
return 0;
}
}
}
| mit | C# |
f439ab6eaa61ddfb8ac37390756432657e615c0d | Fix async warning in toggle block comment. | bartdesmet/roslyn,davkean/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,sharwell/roslyn,physhi/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,panopticoncentral/roslyn,brettfo/roslyn,reaction1989/roslyn,diryboy/roslyn,genlu/roslyn,stephentoub/roslyn,bartdesmet/roslyn,abock/roslyn,davkean/roslyn,gafter/roslyn,abock/roslyn,KirillOsenkov/roslyn,abock/roslyn,wvdd007/roslyn,mavasani/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,physhi/roslyn,KevinRansom/roslyn,gafter/roslyn,tannergooding/roslyn,eriawan/roslyn,diryboy/roslyn,genlu/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,agocke/roslyn,tmat/roslyn,heejaechang/roslyn,dotnet/roslyn,aelij/roslyn,eriawan/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,jmarolf/roslyn,tmat/roslyn,weltkante/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,agocke/roslyn,dotnet/roslyn,stephentoub/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,jmarolf/roslyn,sharwell/roslyn,weltkante/roslyn,AlekseyTs/roslyn,mavasani/roslyn,physhi/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,aelij/roslyn,sharwell/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,agocke/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,mavasani/roslyn,AmadeusW/roslyn,wvdd007/roslyn,eriawan/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,dotnet/roslyn,davkean/roslyn,aelij/roslyn | src/EditorFeatures/Core/Implementation/CommentSelection/ToggleBlockCommentCommandHandler.cs | src/EditorFeatures/Core/Implementation/CommentSelection/ToggleBlockCommentCommandHandler.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 System;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection
{
/* TODO - Modify these once the toggle block comment handler is added.
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(PredefinedCommandHandlerNames.CommentSelection)]*/
internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase
{
[ImportingConstructor]
internal ToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
: base(undoHistoryRegistry, editorOperationsFactoryService)
{
}
/// <summary>
/// Gets the default text based document data provider for block comments.
/// </summary>
protected override Task<IToggleBlockCommentDocumentDataProvider> GetBlockCommentDocumentDataProvider(Document document, ITextSnapshot snapshot,
CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
IToggleBlockCommentDocumentDataProvider provider = new ToggleBlockCommentDocumentDataProvider(snapshot, commentInfo);
return Task.FromResult(provider);
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection
{
/* TODO - Modify these once the toggle block comment handler is added.
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(PredefinedCommandHandlerNames.CommentSelection)]*/
internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase
{
[ImportingConstructor]
internal ToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
: base(undoHistoryRegistry, editorOperationsFactoryService)
{
}
/// <summary>
/// Gets the default text based document data provider for block comments.
/// </summary>
protected override async Task<IToggleBlockCommentDocumentDataProvider> GetBlockCommentDocumentDataProvider(Document document, ITextSnapshot snapshot,
CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
return new ToggleBlockCommentDocumentDataProvider(snapshot, commentInfo);
}
}
}
| mit | C# |
6724a4cdb5d49521564c028f7fb4df74a62c1936 | test cosmetics. | modulexcite/lokad-cqrs | Framework/Lokad.Cqrs.Tests/Feature.AtomicStorage/Run_all_AtomicStorage_scenarios_on_Azure.cs | Framework/Lokad.Cqrs.Tests/Feature.AtomicStorage/Run_all_AtomicStorage_scenarios_on_Azure.cs | using System;
using Lokad.Cqrs.Build.Engine;
using Microsoft.WindowsAzure;
using NUnit.Framework;
// ReSharper disable InconsistentNaming
namespace Lokad.Cqrs.Feature.AtomicStorage
{
[TestFixture]
public sealed class Run_all_AtomicStorage_scenarios_on_Azure
{
[Test]
public void When_atomic_config_is_requested()
{
new Engine_scenario_for_AtomicStorage_in_partition()
.TestConfiguration(CurrentConfig);
}
[Test]
public void When_nuclear_config_is_requested()
{
new Engine_scenario_for_NuclearStorage_in_partition()
.TestConfiguration(CurrentConfig);
}
[Test]
public void When_custom_view_domain()
{
new Engine_scenario_for_custom_view_domain()
.TestConfiguration(CurrentConfig);
}
static void CurrentConfig(CloudEngineBuilder b)
{
b.Azure(m =>
{
m.AddAzureAccount("azure-dev", CloudStorageAccount.DevelopmentStorageAccount);
m.AddAzureProcess("azure-dev", new[] { "incoming" }, c => c.QueueVisibility(1));
m.AddAzureSender("azure-dev", "incoming", x => x.IdGeneratorForTests());
m.WipeAccountsAtStartUp = true;
});
b.Storage(m => m.AtomicStorageIsAzure("azure-dev", c => c.WithStrategy(DefaultWithCustomConfig)));
}
static void DefaultWithCustomConfig(DefaultAzureAtomicStorageStrategyBuilder builder)
{
builder.WhereEntity(type =>
{
if (typeof(Define.AtomicEntity).IsAssignableFrom(type))
return true;
if (type.Name.Contains("CustomDomainView"))
return true;
return false;
});
}
}
} | using System;
using Lokad.Cqrs.Build.Engine;
using Microsoft.WindowsAzure;
using NUnit.Framework;
// ReSharper disable InconsistentNaming
namespace Lokad.Cqrs.Feature.AtomicStorage
{
[TestFixture]
public sealed class Run_all_AtomicStorage_scenarios_on_Azure
{
[Test]
public void When_atomic_config_is_requested()
{
new Engine_scenario_for_AtomicStorage_in_partition()
.TestConfiguration(CurrentConfig);
}
[Test]
public void When_nuclear_config_is_requested()
{
new Engine_scenario_for_NuclearStorage_in_partition()
.TestConfiguration(CurrentConfig);
}
[Test]
public void When_custom_view_domain()
{
new Engine_scenario_for_custom_view_domain()
.TestConfiguration(CurrentConfig);
}
static void CurrentConfig(CloudEngineBuilder b)
{
b.Azure(m =>
{
m.AddAzureAccount("azure-dev", CloudStorageAccount.DevelopmentStorageAccount);
m.AddAzureProcess("azure-dev", new[] { "incoming" }, c => c.QueueVisibility(1));
m.AddAzureSender("azure-dev", "incoming", x => x.IdGeneratorForTests());
m.WipeAccountsAtStartUp = true;
});
b.Storage(m => m.AtomicStorageIsAzure("azure-dev", c => c.WithStrategy(x => x.WhereEntity(EntityFilter))));
}
static bool EntityFilter(Type type)
{
if (typeof(Define.AtomicEntity).IsAssignableFrom(type))
return true;
if (type.Name.Contains("CustomDomainView"))
return true;
return false;
}
}
} | bsd-3-clause | C# |
4009952d05b3de80661f122ae299d748ddd92fae | Update VariablesExtension.cs | kasubram/vsts-agent,Microsoft/vsts-agent,lkillgore/vsts-agent,kasubram/vsts-agent,Microsoft/vsts-agent,Microsoft/vsts-agent,Microsoft/vsts-agent,lkillgore/vsts-agent,lkillgore/vsts-agent,lkillgore/vsts-agent,kasubram/vsts-agent,kasubram/vsts-agent | src/Agent.Worker/Extensions/VariablesExtension.cs | src/Agent.Worker/Extensions/VariablesExtension.cs | // TODO: Delete this file. This file unnecessarily starts a new convention (extensions namespace and variables extentension class for a function that is called from exactly one place).
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using Microsoft.TeamFoundation.DistributedTask.WebApi;
//namespace Microsoft.VisualStudio.Services.Agent.Worker.Extensions
//{
// public static class VariablesExtension
// {
// public static Dictionary<string, VariableValue> ToJobCompletedEventOutputVariables(this IEnumerable<Variable> outputVariables)
// {
// var webApiVariables = new Dictionary<string, VariableValue>(StringComparer.OrdinalIgnoreCase);
// if (outputVariables == null || !outputVariables.Any())
// {
// return webApiVariables;
// }
// foreach (Variable outputVariable in outputVariables)
// {
// var variableValue = new VariableValue
// {
// Value = outputVariable.Value,
// IsSecret = outputVariable.Secret
// };
// webApiVariables.Add(outputVariable.Name, variableValue);
// }
// return webApiVariables;
// }
// }
//}
| //using System;
//using System.Collections.Generic;
//using System.Linq;
//using Microsoft.TeamFoundation.DistributedTask.WebApi;
//namespace Microsoft.VisualStudio.Services.Agent.Worker.Extensions
//{
// public static class VariablesExtension
// {
// public static Dictionary<string, VariableValue> ToJobCompletedEventOutputVariables(this IEnumerable<Variable> outputVariables)
// {
// var webApiVariables = new Dictionary<string, VariableValue>(StringComparer.OrdinalIgnoreCase);
// if (outputVariables == null || !outputVariables.Any())
// {
// return webApiVariables;
// }
// foreach (Variable outputVariable in outputVariables)
// {
// var variableValue = new VariableValue
// {
// Value = outputVariable.Value,
// IsSecret = outputVariable.Secret
// };
// webApiVariables.Add(outputVariable.Name, variableValue);
// }
// return webApiVariables;
// }
// }
//} | mit | C# |
401cc6f0998de4150e82493558810b24a33bb8ca | update extension impl | dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP.MySql/ICapTransaction.MySql.cs | src/DotNetCore.CAP.MySql/ICapTransaction.MySql.cs | using System.Data;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
public class MySqlCapTransaction : CapTransactionBase
{
public MySqlCapTransaction(IDispatcher dispatcher) : base(dispatcher)
{
}
public override void Commit()
{
Debug.Assert(DbTransaction != null);
switch (DbTransaction)
{
case IDbTransaction dbTransaction:
dbTransaction.Commit();
break;
case IDbContextTransaction dbContextTransaction:
dbContextTransaction.Commit();
break;
}
Flush();
}
public override void Rollback()
{
Debug.Assert(DbTransaction != null);
switch (DbTransaction)
{
case IDbTransaction dbTransaction:
dbTransaction.Rollback();
break;
case IDbContextTransaction dbContextTransaction:
dbContextTransaction.Rollback();
break;
}
}
public override void Dispose()
{
(DbTransaction as IDbTransaction)?.Dispose();
}
}
public static class CapTransactionExtensions
{
public static ICapTransaction Begin(this ICapTransaction transaction,
IDbContextTransaction dbTransaction, bool autoCommit = false)
{
transaction.DbTransaction = dbTransaction;
transaction.AutoCommit = autoCommit;
return transaction;
}
}
} | using System.Data;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
public class MySqlCapTransaction : CapTransactionBase
{
public MySqlCapTransaction(IDispatcher dispatcher) : base(dispatcher) { }
public override void Commit()
{
Debug.Assert(DbTransaction != null);
switch (DbTransaction)
{
case IDbTransaction dbTransaction:
dbTransaction.Commit();
break;
case IDbContextTransaction dbContextTransaction:
dbContextTransaction.Commit();
break;
}
Flush();
}
public override void Rollback()
{
Debug.Assert(DbTransaction != null);
switch (DbTransaction)
{
case IDbTransaction dbTransaction:
dbTransaction.Rollback();
break;
case IDbContextTransaction dbContextTransaction:
dbContextTransaction.Rollback();
break;
}
}
public override void Dispose()
{
(DbTransaction as IDbTransaction)?.Dispose();
}
}
public static class CapTransactionExtensions
{
public static ICapTransaction Begin(this ICapTransaction transaction,
IDbTransaction dbTransaction, bool autoCommit = false)
{
transaction.DbTransaction = dbTransaction;
transaction.AutoCommit = autoCommit;
return transaction;
}
public static ICapTransaction Begin(this ICapTransaction transaction,
IDbContextTransaction dbTransaction, bool autoCommit = false)
{
transaction.DbTransaction = dbTransaction;
transaction.AutoCommit = autoCommit;
return transaction;
}
}
}
| mit | C# |
7319c5fe9ab1ff0edddb0458abcb36cc0f7a6f0f | Fix PrintView path | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.FlowDocument/PrintView/PrintViewApi.cs | InfinniPlatform.FlowDocument/PrintView/PrintViewApi.cs | using System;
using System.IO;
using InfinniPlatform.Core.Extensions;
using InfinniPlatform.Core.Metadata;
using InfinniPlatform.Core.PrintView;
using InfinniPlatform.Sdk.Dynamic;
using InfinniPlatform.Sdk.PrintView;
using InfinniPlatform.Sdk.Serialization;
namespace InfinniPlatform.FlowDocument.PrintView
{
/// <summary>
/// Предоставляет методы для работы с печатными представлениями.
/// </summary>
internal sealed class PrintViewApi : IPrintViewApi
{
public PrintViewApi(IPrintViewBuilder printViewBuilder,
MetadataSettings metadataSettings)
{
_printViewBuilder = printViewBuilder;
_metadataSettings = metadataSettings;
}
private readonly MetadataSettings _metadataSettings;
private readonly IPrintViewBuilder _printViewBuilder;
public byte[] Build(string documentType, string printViewName, object printViewSource, PrintViewFileFormat printViewFormat = PrintViewFileFormat.Pdf)
{
if (string.IsNullOrEmpty(documentType))
{
throw new ArgumentNullException(nameof(documentType));
}
if (string.IsNullOrEmpty(printViewName))
{
throw new ArgumentNullException(nameof(printViewName));
}
//Build view name
var printViewPath = Path.Combine(_metadataSettings.PrintViewsPath, documentType, $"{printViewName}.json").ToFileSystemPath();
var bytes = File.ReadAllBytes(printViewPath);
var printViewMetadata = JsonObjectSerializer.Default.Deserialize<DynamicWrapper>(bytes);
if (printViewMetadata == null)
{
throw new ArgumentException($"Print view '{documentType}/{printViewName}' not found.");
}
var printViewData = _printViewBuilder.BuildFile(printViewMetadata, printViewSource, printViewFormat);
return printViewData;
}
}
} | using System;
using System.IO;
using InfinniPlatform.Core.Extensions;
using InfinniPlatform.Core.Metadata;
using InfinniPlatform.Core.PrintView;
using InfinniPlatform.Sdk.Dynamic;
using InfinniPlatform.Sdk.PrintView;
using InfinniPlatform.Sdk.Serialization;
namespace InfinniPlatform.FlowDocument.PrintView
{
/// <summary>
/// Предоставляет методы для работы с печатными представлениями.
/// </summary>
internal sealed class PrintViewApi : IPrintViewApi
{
public PrintViewApi(IPrintViewBuilder printViewBuilder,
MetadataSettings metadataSettings)
{
_printViewBuilder = printViewBuilder;
_metadataSettings = metadataSettings;
}
private readonly MetadataSettings _metadataSettings;
private readonly IPrintViewBuilder _printViewBuilder;
public byte[] Build(string documentType, string printViewName, object printViewSource, PrintViewFileFormat printViewFormat = PrintViewFileFormat.Pdf)
{
if (string.IsNullOrEmpty(documentType))
{
throw new ArgumentNullException(nameof(documentType));
}
if (string.IsNullOrEmpty(printViewName))
{
throw new ArgumentNullException(nameof(printViewName));
}
//Build view name
var printViewPath = Path.Combine(_metadataSettings.PrintViewsPath, documentType, printViewName, ".json").ToFileSystemPath();
var bytes = File.ReadAllBytes(printViewPath);
var printViewMetadata = JsonObjectSerializer.Default.Deserialize<DynamicWrapper>(bytes);
if (printViewMetadata == null)
{
throw new ArgumentException($"Print view '{documentType}/{printViewName}' not found.");
}
var printViewData = _printViewBuilder.BuildFile(printViewMetadata, printViewSource, printViewFormat);
return printViewData;
}
}
} | agpl-3.0 | C# |
04fbc1a60c428fdf8716b7d9ca32fdcff5752ef1 | Add Blob property to ContentAddressableStorage | studio-nine/Nine.Storage,yufeih/Nine.Storage | src/Portable/Storage/ContentAddressableStorage.cs | src/Portable/Storage/ContentAddressableStorage.cs | namespace Nine.Storage
{
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
public class ContentAddressableStorage : IContentAddressableStorage
{
private readonly IBlobStorage blob;
public IBlobStorage Blob => blob;
public ContentAddressableStorage(IBlobStorage blob)
{
if ((this.blob = blob) == null) throw new ArgumentNullException(nameof(blob));
}
public Task<bool> Exists(string key) => blob.Exists(VerifySha1(key));
public Task<string> GetUri(string key) => blob.GetUri(VerifySha1(key));
public Task<Stream> Get(string key, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => blob.Get(VerifySha1(key), progress, cancellationToken);
public Task<string> Put(Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => Put(null, stream, progress, cancellationToken);
public Task<string> Put(string key, Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(key))
{
key = Sha1.ComputeHashString(stream);
stream.Seek(0, SeekOrigin.Begin);
}
return blob.Put(key, stream, progress, cancellationToken);
}
private string VerifySha1(string key)
{
if (key == null) throw new ArgumentNullException("key");
if (key.Length != 40) throw new ArgumentException("key");
foreach (var c in key)
{
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z'))) throw new ArgumentException("key");
}
return key;
}
}
}
| namespace Nine.Storage
{
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
public class ContentAddressableStorage : IContentAddressableStorage
{
private readonly IBlobStorage blob;
public ContentAddressableStorage(IBlobStorage blob)
{
if ((this.blob = blob) == null) throw new ArgumentNullException(nameof(blob));
}
public Task<bool> Exists(string key) => blob.Exists(VerifySha1(key));
public Task<string> GetUri(string key) => blob.GetUri(VerifySha1(key));
public Task<Stream> Get(string key, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => blob.Get(VerifySha1(key), progress, cancellationToken);
public Task<string> Put(Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken)) => Put(null, stream, progress, cancellationToken);
public Task<string> Put(string key, Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(key))
{
key = Sha1.ComputeHashString(stream);
stream.Seek(0, SeekOrigin.Begin);
}
return blob.Put(key, stream, progress, cancellationToken);
}
private string VerifySha1(string key)
{
if (key == null) throw new ArgumentNullException("key");
if (key.Length != 40) throw new ArgumentException("key");
foreach (var c in key)
{
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z'))) throw new ArgumentException("key");
}
return key;
}
}
}
| mit | C# |
4eb25c6b34f7c6585d3215c879b6ebd6cbc56c41 | Remove unused using | ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework | osu.Framework/Statistics/DotNetRuntimeListener.cs | osu.Framework/Statistics/DotNetRuntimeListener.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.Diagnostics.Tracing;
namespace osu.Framework.Statistics
{
// https://medium.com/criteo-labs/c-in-process-clr-event-listeners-with-net-core-2-2-ef4075c14e87
internal sealed class DotNetRuntimeListener : EventListener
{
private const int gc_keyword = 0x0000001;
private const string statistics_grouping = "GC";
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name == "Microsoft-Windows-DotNETRuntime")
EnableEvents(eventSource, EventLevel.Verbose, (EventKeywords)gc_keyword);
}
protected override void OnEventWritten(EventWrittenEventArgs data)
{
switch ((EventType)data.EventId)
{
case EventType.GCStart_V1 when data.Payload != null:
// https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcstart_v1_event
GlobalStatistics.Get<int>(statistics_grouping, $"Collections Gen{data.Payload[1]}").Value++;
break;
case EventType.GCHeapStats_V1 when data.Payload != null:
// https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v1_event
for (int i = 0; i <= 6; i += 2)
addStatistic<ulong>("Size Gen{i / 2}", data.Payload[i]);
addStatistic<ulong>("Finalization queue length", data.Payload[9]);
addStatistic<uint>("Pinned objects", data.Payload[10]);
break;
}
}
private void addStatistic<T>(string name, object data)
=> GlobalStatistics.Get<T>(statistics_grouping, name).Value = (T)data;
private enum EventType
{
GCStart_V1 = 1,
GCHeapStats_V1 = 4,
}
}
}
| // 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.Diagnostics;
using System.Diagnostics.Tracing;
namespace osu.Framework.Statistics
{
// https://medium.com/criteo-labs/c-in-process-clr-event-listeners-with-net-core-2-2-ef4075c14e87
internal sealed class DotNetRuntimeListener : EventListener
{
private const int gc_keyword = 0x0000001;
private const string statistics_grouping = "GC";
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name == "Microsoft-Windows-DotNETRuntime")
EnableEvents(eventSource, EventLevel.Verbose, (EventKeywords)gc_keyword);
}
protected override void OnEventWritten(EventWrittenEventArgs data)
{
switch ((EventType)data.EventId)
{
case EventType.GCStart_V1 when data.Payload != null:
// https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcstart_v1_event
GlobalStatistics.Get<int>(statistics_grouping, $"Collections Gen{data.Payload[1]}").Value++;
break;
case EventType.GCHeapStats_V1 when data.Payload != null:
// https://docs.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v1_event
for (int i = 0; i <= 6; i += 2)
addStatistic<ulong>("Size Gen{i / 2}", data.Payload[i]);
addStatistic<ulong>("Finalization queue length", data.Payload[9]);
addStatistic<uint>("Pinned objects", data.Payload[10]);
break;
}
}
private void addStatistic<T>(string name, object data)
=> GlobalStatistics.Get<T>(statistics_grouping, name).Value = (T)data;
private enum EventType
{
GCStart_V1 = 1,
GCHeapStats_V1 = 4,
}
}
}
| mit | C# |
96c23d2a627ed60902897579f86b86c82a92f588 | Add override to fix left/right arrow control | EVAST9919/osu,Nabile-Rahmani/osu,ppy/osu,peppy/osu,ZLima12/osu,DrabWeb/osu,DrabWeb/osu,2yangk23/osu,smoogipooo/osu,johnneijzen/osu,2yangk23/osu,naoey/osu,peppy/osu,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,naoey/osu,NeoAdonis/osu,ppy/osu,naoey/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,Frontear/osuKyzer,DrabWeb/osu | osu.Game/Graphics/UserInterface/FocusedTextBox.cs | osu.Game/Graphics/UserInterface/FocusedTextBox.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using OpenTK.Input;
using osu.Framework.Input;
using System;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A textbox which holds focus eagerly.
/// </summary>
public class FocusedTextBox : OsuTextBox
{
protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255);
protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255);
public Action Exit;
public override bool HandleLeftRightArrows => false;
private bool focus;
public bool HoldFocus
{
get { return focus; }
set
{
focus = value;
if (!focus && HasFocus)
GetContainingInputManager().ChangeFocus(null);
}
}
protected override void OnFocus(InputState state)
{
base.OnFocus(state);
BorderThickness = 0;
}
protected override bool OnKeyDown(InputState state, KeyDownEventArgs args)
{
if (!args.Repeat && args.Key == Key.Escape)
{
if (Text.Length > 0)
Text = string.Empty;
else
Exit?.Invoke();
return true;
}
return base.OnKeyDown(state, args);
}
public override bool RequestsFocus => HoldFocus;
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using OpenTK.Input;
using osu.Framework.Input;
using System;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A textbox which holds focus eagerly.
/// </summary>
public class FocusedTextBox : OsuTextBox
{
protected override Color4 BackgroundUnfocused => new Color4(10, 10, 10, 255);
protected override Color4 BackgroundFocused => new Color4(10, 10, 10, 255);
public Action Exit;
private bool focus;
public bool HoldFocus
{
get { return focus; }
set
{
focus = value;
if (!focus && HasFocus)
GetContainingInputManager().ChangeFocus(null);
}
}
protected override void OnFocus(InputState state)
{
base.OnFocus(state);
BorderThickness = 0;
}
protected override bool OnKeyDown(InputState state, KeyDownEventArgs args)
{
if (!args.Repeat && args.Key == Key.Escape)
{
if (Text.Length > 0)
Text = string.Empty;
else
Exit?.Invoke();
return true;
}
return base.OnKeyDown(state, args);
}
public override bool RequestsFocus => HoldFocus;
}
}
| mit | C# |
84b3b1f8b7afeb4a427ff38c6edf0f889cd05e6c | Change assembly version to be major version | smithab/azure-sdk-for-net,jamestao/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,stankovski/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,r22016/azure-sdk-for-net,r22016/azure-sdk-for-net,AzCiS/azure-sdk-for-net,stankovski/azure-sdk-for-net,pilor/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,markcowl/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,shutchings/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,djyou/azure-sdk-for-net,atpham256/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,djyou/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,nathannfan/azure-sdk-for-net,peshen/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,AzCiS/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pilor/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,AzCiS/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,samtoubia/azure-sdk-for-net,r22016/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,jamestao/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jamestao/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,atpham256/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,pankajsn/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,nathannfan/azure-sdk-for-net,mihymel/azure-sdk-for-net,pankajsn/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,btasdoven/azure-sdk-for-net,smithab/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,shutchings/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,pankajsn/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,begoldsm/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,btasdoven/azure-sdk-for-net,olydis/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,atpham256/azure-sdk-for-net,olydis/azure-sdk-for-net,begoldsm/azure-sdk-for-net,begoldsm/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,peshen/azure-sdk-for-net,shutchings/azure-sdk-for-net,hyonholee/azure-sdk-for-net,hyonholee/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,mihymel/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,btasdoven/azure-sdk-for-net,hyonholee/azure-sdk-for-net,mihymel/azure-sdk-for-net,djyou/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,hyonholee/azure-sdk-for-net,nathannfan/azure-sdk-for-net,smithab/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,peshen/azure-sdk-for-net,samtoubia/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,samtoubia/azure-sdk-for-net,samtoubia/azure-sdk-for-net,olydis/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jamestao/azure-sdk-for-net,pilor/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net | src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Properties/AssemblyInfo.cs | src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Properties/AssemblyInfo.cs | //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Azure Network Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Network management functions for managing the Microsoft Azure Network service.")]
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.1.1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Azure Network Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Network management functions for managing the Microsoft Azure Network service.")]
[assembly: AssemblyVersion("6.1.1.0")]
[assembly: AssemblyFileVersion("6.1.1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| apache-2.0 | C# |
faed763192b92599f84d59f961c924f369eaac6c | Print the number of differences in the exception message | jamesfoster/DeepEqual | src/DeepEqual/Syntax/ObjectExtensions.cs | src/DeepEqual/Syntax/ObjectExtensions.cs | namespace DeepEqual.Syntax
{
using System;
using System.Diagnostics.Contracts;
using System.Text;
public static class ObjectExtensions
{
[Pure]
public static bool IsDeepEqual(this object actual, object expected)
{
var comparison = new ComparisonBuilder().Create();
return IsDeepEqual(actual, expected, comparison);
}
[Pure]
public static bool IsDeepEqual(this object actual, object expected, IComparison comparison)
{
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
return result == ComparisonResult.Pass;
}
public static void ShouldDeepEqual(this object actual, object expected)
{
var comparison = new ComparisonBuilder().Create();
ShouldDeepEqual(actual, expected, comparison);
}
public static void ShouldDeepEqual(this object actual, object expected, IComparison comparison)
{
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
if (result != ComparisonResult.Fail)
{
return;
}
var sb = new StringBuilder();
sb.Append("Comparison Failed");
if (context.Differences.Count > 0)
{
sb.AppendFormat(": The following {0} differences were found.", context.Differences.Count);
foreach (var difference in context.Differences)
{
var lines = difference.ToString().Split(new[] {"\n"}, StringSplitOptions.None);
sb.Append("\n\t");
sb.Append(string.Join("\n\t", lines));
}
}
throw new Exception(sb.ToString());
}
[Pure]
public static CompareSyntax<TActual, TExpected> WithDeepEqual<TActual, TExpected>(
this TActual actual,
TExpected expected)
{
return new CompareSyntax<TActual, TExpected>(actual, expected);
}
}
} | namespace DeepEqual.Syntax
{
using System;
using System.Diagnostics.Contracts;
using System.Text;
public static class ObjectExtensions
{
[Pure]
public static bool IsDeepEqual(this object actual, object expected)
{
var comparison = new ComparisonBuilder().Create();
return IsDeepEqual(actual, expected, comparison);
}
[Pure]
public static bool IsDeepEqual(this object actual, object expected, IComparison comparison)
{
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
return result == ComparisonResult.Pass;
}
public static void ShouldDeepEqual(this object actual, object expected)
{
var comparison = new ComparisonBuilder().Create();
ShouldDeepEqual(actual, expected, comparison);
}
public static void ShouldDeepEqual(this object actual, object expected, IComparison comparison)
{
var context = new ComparisonContext();
var result = comparison.Compare(context, actual, expected);
if (result != ComparisonResult.Fail)
{
return;
}
var sb = new StringBuilder();
sb.Append("Comparison Failed");
if (context.Differences.Count > 0)
{
sb.Append(": The following differences were found.");
foreach (var difference in context.Differences)
{
var lines = difference.ToString().Split(new[] {"\n"}, StringSplitOptions.None);
sb.Append("\n\t");
sb.Append(string.Join("\n\t", lines));
}
}
throw new Exception(sb.ToString());
}
[Pure]
public static CompareSyntax<TActual, TExpected> WithDeepEqual<TActual, TExpected>(
this TActual actual,
TExpected expected)
{
return new CompareSyntax<TActual, TExpected>(actual, expected);
}
}
} | mit | C# |
4e706e947ddad9c6075de6a11a0cd1cbe33c9be3 | Fix signature validation to handle query params | plivo/plivo-dotnet,plivo/plivo-dotnet | src/Plivo/Utilities/XPlivoSignatureV2.cs | src/Plivo/Utilities/XPlivoSignatureV2.cs | using System;
using System.Security.Cryptography;
using System.Text;
namespace Plivo.Utilities
{
public static class XPlivoSignatureV2
{
/// <summary>
/// Compute X-Plivo-Signature-V2
/// </summary>
/// <param name="uri"></param>
/// <param name="nonce"></param>
/// <param name="authToken"></param>
/// <returns></returns>
public static string ComputeSignature(string uri, string nonce, string authToken)
{
var url = new Uri(uri);
string absolutePath = url.AbsolutePath;
string pathToAppend = "";
int pathExists = uri.IndexOf(absolutePath);
if (pathExists > -1) {
pathToAppend = absolutePath;
} else {
pathToAppend = absolutePath.Remove(absolutePath.Length - 1);
}
string baseUrl = url.Scheme + "://" + url.Host + pathToAppend;
string payload = baseUrl + nonce;
var hash = new HMACSHA256(Encoding.UTF8.GetBytes(authToken));
var computedHash = hash.ComputeHash(Encoding.UTF8.GetBytes(payload));
return Convert.ToBase64String(computedHash);
}
/// <summary>
/// Verify X-Plivo-Signature-V2
/// </summary>
/// <param name="uri"></param>
/// <param name="nonce"></param>
/// <param name="xPlivoSignature"></param>
/// <param name="authToken"></param>
/// <returns></returns>
public static bool VerifySignature(string uri, string nonce, string xPlivoSignature, string authToken)
{
string computedSignature = ComputeSignature(uri, nonce, authToken);
if (computedSignature == xPlivoSignature) {
return true;
}
return false;
}
}
}
| using System;
using System.Security.Cryptography;
using System.Text;
namespace Plivo.Utilities
{
public static class XPlivoSignatureV2
{
/// <summary>
/// Compute X-Plivo-Signature-V2
/// </summary>
/// <param name="uri"></param>
/// <param name="nonce"></param>
/// <param name="authToken"></param>
/// <returns></returns>
public static string ComputeSignature(string uri, string nonce, string authToken)
{
var url = new Uri(uri);
string absolutePath = url.AbsolutePath;
string pathToAppend = "";
if (absolutePath[absolutePath.Length - 1] == '/') {
if (uri[uri.Length - 1] == '/') {
pathToAppend = absolutePath;
} else {
pathToAppend = absolutePath.Remove(absolutePath.Length - 1);
}
}
string baseUrl = url.Scheme + "://" + url.Host + pathToAppend;
string payload = baseUrl + nonce;
var hash = new HMACSHA256(Encoding.UTF8.GetBytes(authToken));
var computedHash = hash.ComputeHash(Encoding.UTF8.GetBytes(payload));
return Convert.ToBase64String(computedHash);
}
/// <summary>
/// Verify X-Plivo-Signature-V2
/// </summary>
/// <param name="uri"></param>
/// <param name="nonce"></param>
/// <param name="xPlivoSignature"></param>
/// <param name="authToken"></param>
/// <returns></returns>
public static bool VerifySignature(string uri, string nonce, string xPlivoSignature, string authToken)
{
string computedSignature = ComputeSignature(uri, nonce, authToken);
if (computedSignature == xPlivoSignature) {
return true;
}
return false;
}
}
}
| mit | C# |
7641ca3722650ac1f6576cc62f64631494191677 | Handle change to cookie parser. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/MusicStore.Spa.Test/ShoppingCartTest.cs | test/MusicStore.Spa.Test/ShoppingCartTest.cs | using System.Collections.Generic;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Core;
using Microsoft.AspNet.Http.Core.Collections;
using Xunit;
namespace MusicStore.Models
{
public class ShoppingCartTest
{
[Fact]
public void GetCartId_ReturnsCartIdFromCookies()
{
// Arrange
var cartId = "cartId_A";
var httpContext = new DefaultHttpContext();
httpContext.SetFeature<IRequestCookiesFeature>(new CookiesFeature("Session", cartId));
var cart = new ShoppingCart(new MusicStoreContext());
// Act
var result = cart.GetCartId(httpContext);
// Assert
Assert.NotNull(result);
Assert.Equal(cartId, result);
}
private class CookiesFeature : IRequestCookiesFeature
{
private readonly IReadableStringCollection _cookies;
public CookiesFeature(string key, string value)
{
_cookies = new ReadableStringCollection(new Dictionary<string, string[]>()
{
{ key, new[] { value } }
});
}
public IReadableStringCollection Cookies
{
get { return _cookies; }
}
}
}
}
| using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Core;
using Microsoft.AspNet.Http.Core.Collections;
using Xunit;
namespace MusicStore.Models
{
public class ShoppingCartTest
{
[Fact]
public void GetCartId_ReturnsCartIdFromCookies()
{
// Arrange
var cartId = "cartId_A";
var httpContext = new DefaultHttpContext();
httpContext.SetFeature<IRequestCookiesFeature>(new CookiesFeature("Session=" + cartId));
var cart = new ShoppingCart(new MusicStoreContext());
// Act
var result = cart.GetCartId(httpContext);
// Assert
Assert.NotNull(result);
Assert.Equal(cartId, result);
}
private class CookiesFeature : IRequestCookiesFeature
{
private readonly RequestCookiesCollection _cookies;
public CookiesFeature(string cookiesHeader)
{
_cookies = new RequestCookiesCollection();
_cookies.Reparse(cookiesHeader);
}
public IReadableStringCollection Cookies
{
get { return _cookies; }
}
}
}
}
| apache-2.0 | C# |
c8b5e7950f467e25a872bc1d1b9a574c562304b1 | 添加注释。 | yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate | src/YoYoCms.AbpProjectTemplate.EntityFramework/EntityFramework/AbpProjectTemplateDbContext.cs | src/YoYoCms.AbpProjectTemplate.EntityFramework/EntityFramework/AbpProjectTemplateDbContext.cs | using System.Data.Common;
using System.Data.Entity;
using Abp.Zero.EntityFramework;
using YoYoCms.AbpProjectTemplate.Authorization.Roles;
using YoYoCms.AbpProjectTemplate.Authorization.Users;
using YoYoCms.AbpProjectTemplate.Chat;
using YoYoCms.AbpProjectTemplate.EntityMapper.BinaryObjects;
using YoYoCms.AbpProjectTemplate.EntityMapper.ChatMessages;
using YoYoCms.AbpProjectTemplate.EntityMapper.FriendShips;
using YoYoCms.AbpProjectTemplate.Friendships;
using YoYoCms.AbpProjectTemplate.MultiTenancy;
using YoYoCms.AbpProjectTemplate.Storage;
namespace YoYoCms.AbpProjectTemplate.EntityFramework
{
/* Constructors of this DbContext is important and each one has it's own use case.
* - Default constructor is used by EF tooling on design time.
* - constructor(nameOrConnectionString) is used by ABP on runtime.
* - constructor(existingConnection) is used by unit tests.
* - constructor(existingConnection,contextOwnsConnection) can be used by ABP if DbContextEfTransactionStrategy is used.
* See http://www.aspnetboilerplate.com/Pages/Documents/EntityFramework-Integration for more.
*/
public class AbpProjectTemplateDbContext : AbpZeroDbContext<Tenant, Role, User>
{
/* Define an IDbSet for each entity of the application */
public virtual IDbSet<BinaryObject> BinaryObjects { get; set; }
public virtual IDbSet<Friendship> Friendships { get; set; }
public virtual IDbSet<ChatMessage> ChatMessages { get; set; }
public AbpProjectTemplateDbContext()
: base("Default")
{
}
public AbpProjectTemplateDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public AbpProjectTemplateDbContext(DbConnection existingConnection)
: base(existingConnection, false)
{
}
public AbpProjectTemplateDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
#region ABP默认功能图集
modelBuilder.ChangeAbpTablePrefix<Tenant, Role, User>("", "ABP");
modelBuilder.Configurations.Add(new BinaryObjectCfg());
modelBuilder.Configurations.Add(new FriendshipCfg());
modelBuilder.Configurations.Add(new ChatMessageCfg());
#endregion
base.OnModelCreating(modelBuilder);
}
}
}
| using System.Data.Common;
using System.Data.Entity;
using Abp.Zero.EntityFramework;
using YoYoCms.AbpProjectTemplate.Authorization.Roles;
using YoYoCms.AbpProjectTemplate.Authorization.Users;
using YoYoCms.AbpProjectTemplate.Chat;
using YoYoCms.AbpProjectTemplate.EntityMapper.BinaryObjects;
using YoYoCms.AbpProjectTemplate.EntityMapper.ChatMessages;
using YoYoCms.AbpProjectTemplate.EntityMapper.FriendShips;
using YoYoCms.AbpProjectTemplate.Friendships;
using YoYoCms.AbpProjectTemplate.MultiTenancy;
using YoYoCms.AbpProjectTemplate.Storage;
namespace YoYoCms.AbpProjectTemplate.EntityFramework
{
/* Constructors of this DbContext is important and each one has it's own use case.
* - Default constructor is used by EF tooling on design time.
* - constructor(nameOrConnectionString) is used by ABP on runtime.
* - constructor(existingConnection) is used by unit tests.
* - constructor(existingConnection,contextOwnsConnection) can be used by ABP if DbContextEfTransactionStrategy is used.
* See http://www.aspnetboilerplate.com/Pages/Documents/EntityFramework-Integration for more.
*/
public class AbpProjectTemplateDbContext : AbpZeroDbContext<Tenant, Role, User>
{
/* Define an IDbSet for each entity of the application */
public virtual IDbSet<BinaryObject> BinaryObjects { get; set; }
public virtual IDbSet<Friendship> Friendships { get; set; }
public virtual IDbSet<ChatMessage> ChatMessages { get; set; }
public AbpProjectTemplateDbContext()
: base("Default")
{
}
public AbpProjectTemplateDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public AbpProjectTemplateDbContext(DbConnection existingConnection)
: base(existingConnection, false)
{
}
public AbpProjectTemplateDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ChangeAbpTablePrefix<Tenant,Role,User>("","ABP");
modelBuilder.Configurations.Add(new BinaryObjectCfg());
modelBuilder.Configurations.Add(new FriendshipCfg());
modelBuilder.Configurations.Add(new ChatMessageCfg());
base.OnModelCreating(modelBuilder);
}
}
}
| apache-2.0 | C# |
a5625331a0603c76729b1b6922c59ff3a9e74c0f | Fix problem with invalid whitespaces and lower characters in input license key code | patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity | src/Assets/Scripts/Licensing/KeyLicenseObtainer.cs | src/Assets/Scripts/Licensing/KeyLicenseObtainer.cs | using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
namespace PatchKit.Unity.Patcher.Licensing
{
public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
{
private State _state = State.None;
private KeyLicense _keyLicense;
private Animator _animator;
public InputField KeyInputField;
public GameObject ErrorMessage;
private void Awake()
{
_animator = GetComponent<Animator>();
}
private void Update()
{
_animator.SetBool("IsOpened", _state == State.Obtaining);
ErrorMessage.SetActive(ShowError);
}
public void Cancel()
{
_state = State.Cancelled;
}
public void Confirm()
{
string key = KeyInputField.text;
key = key.ToUpper().Trim();
_keyLicense = new KeyLicense
{
Key = KeyInputField.text
};
_state = State.Confirmed;
}
public bool ShowError { get; set; }
ILicense ILicenseObtainer.Obtain()
{
_state = State.Obtaining;
while (_state != State.Confirmed && _state != State.Cancelled)
{
Thread.Sleep(10);
}
if (_state == State.Cancelled)
{
throw new OperationCanceledException();
}
return _keyLicense;
}
private enum State
{
None,
Obtaining,
Confirmed,
Cancelled
}
}
} | using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
namespace PatchKit.Unity.Patcher.Licensing
{
public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
{
private State _state = State.None;
private KeyLicense _keyLicense;
private Animator _animator;
public InputField KeyInputField;
public GameObject ErrorMessage;
private void Awake()
{
_animator = GetComponent<Animator>();
}
private void Update()
{
_animator.SetBool("IsOpened", _state == State.Obtaining);
ErrorMessage.SetActive(ShowError);
}
public void Cancel()
{
_state = State.Cancelled;
}
public void Confirm()
{
_keyLicense = new KeyLicense
{
Key = KeyInputField.text
};
_state = State.Confirmed;
}
public bool ShowError { get; set; }
ILicense ILicenseObtainer.Obtain()
{
_state = State.Obtaining;
while (_state != State.Confirmed && _state != State.Cancelled)
{
Thread.Sleep(10);
}
if (_state == State.Cancelled)
{
throw new OperationCanceledException();
}
return _keyLicense;
}
private enum State
{
None,
Obtaining,
Confirmed,
Cancelled
}
}
} | mit | C# |
4e09518059e5a787633aceaa08fd19e85e6a3717 | fix for #17 | esskar/Serialize.Linq | src/Serialize.Linq/Nodes/ListInitExpressionNode.cs | src/Serialize.Linq/Nodes/ListInitExpressionNode.cs | using System.Linq.Expressions;
using System.Runtime.Serialization;
using Serialize.Linq.Interfaces;
using Serialize.Linq.Internals;
namespace Serialize.Linq.Nodes
{
#region DataContract
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataContract]
#else
[DataContract(Name = "LI")]
#endif
#endregion
public class ListInitExpressionNode : ExpressionNode<ListInitExpression>
{
public ListInitExpressionNode() { }
public ListInitExpressionNode(INodeFactory factory, ListInitExpression expression)
: base(factory, expression) { }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "I")]
#endif
#endregion
public ElementInitNodeList Initializers { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "N")]
#endif
#endregion
public ExpressionNode NewExpression { get; set; }
protected override void Initialize(ListInitExpression expression)
{
this.Initializers = new ElementInitNodeList(this.Factory, expression.Initializers);
this.NewExpression = this.Factory.Create(expression.NewExpression);
}
public override Expression ToExpression(ExpressionContext context)
{
return Expression.ListInit((NewExpression)this.NewExpression.ToExpression(context), this.Initializers.GetElementInits(context));
}
}
}
| using System.Linq.Expressions;
using System.Runtime.Serialization;
using Serialize.Linq.Interfaces;
using Serialize.Linq.Internals;
namespace Serialize.Linq.Nodes
{
#region DataContract
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataContract]
#else
[DataContract(Name = "LI")]
#endif
#endregion
public class ListInitExpressionNode : ExpressionNode<ListInitExpression>
{
public ListInitExpressionNode() { }
public ListInitExpressionNode(INodeFactory factory, ListInitExpression expression)
: base(factory, expression) { }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "I")]
#endif
#endregion
public ElementInitNodeList Initializers { get; set; }
#region DataMember
#if !SERIALIZE_LINQ_OPTIMIZE_SIZE
[DataMember(EmitDefaultValue = false)]
#else
[DataMember(EmitDefaultValue = false, Name = "N")]
#endif
#endregion
public ExpressionNode NewExpression { get; set; }
protected override void Initialize(ListInitExpression expression)
{
this.Initializers = new ElementInitNodeList(this.Factory, expression.Initializers);
this.NewExpression = this.Factory.Create(expression);
}
public override Expression ToExpression(ExpressionContext context)
{
return Expression.ListInit((NewExpression)this.NewExpression.ToExpression(context), this.Initializers.GetElementInits(context));
}
}
}
| mit | C# |
4089ab789a16d4d4fb6eb7d58401b09ce78d9e02 | Revert "Added form initialization method in Presenter" | BartoszBaczek/WorkshopRequestsManager | Project/WorkshopManager/WorkshopManager/Forms/RequestsDatabaseView/RequestsDatabasePresenter.cs | Project/WorkshopManager/WorkshopManager/Forms/RequestsDatabaseView/RequestsDatabasePresenter.cs | namespace WorkshopManager.Forms.RequestsDatabaseView
{
public class RequestsDatabasePresenter
{
public RequestsDatabasePresenter(IRequestsDatabaseView view)
{
}
}
}
| using System;
namespace WorkshopManager.Forms.RequestsDatabaseView
{
public class RequestsDatabasePresenter
{
private IRequestsDatabaseView _view;
public RequestsDatabasePresenter(IRequestsDatabaseView view)
{
_view = view;
_view.Presenter = this;
Init();
}
public void Init()
{
SetActiveComboBoxDataSource();
}
private void SetActiveComboBoxDataSource()
{
_view.ActiveDataComboBox = Enum.GetValues(typeof (RequestsCategory));
}
}
}
| mit | C# |
cf61f531bd3a6e4eadb50060125e5e8a435fd6f8 | Add INPUT union memory alignment test | vbfox/pinvoke,AArnott/pinvoke,jmelosegui/pinvoke | src/User32.Tests/User32Facts.cs | src/User32.Tests/User32Facts.cs | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;
public partial class User32Facts
{
[Fact]
public void MessageBeep_Asterisk()
{
Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
}
[Fact]
public void INPUT_Union()
{
INPUT i = default(INPUT);
i.type = InputType.INPUT_HARDWARE;
// Assert that the first field (type) has its own memory space.
Assert.Equal(0u, i.Inputs.hi.uMsg);
Assert.Equal(0, (int)i.Inputs.ki.wScan);
Assert.Equal(0, i.Inputs.mi.dx);
// Assert that these three fields (hi, ki, mi) share memory space.
i.Inputs.hi.uMsg = 1;
Assert.Equal(1, (int)i.Inputs.ki.wVk);
Assert.Equal(1, i.Inputs.mi.dx);
}
/// <summary>
/// Validates that the union fields are all exactly 4 bytes (or 8 bytes on x64)
/// after the start of the struct.i
/// </summary>
/// <devremarks>
/// From http://www.pinvoke.net/default.aspx/Structures/INPUT.html:
/// The last 3 fields are a union, which is why they are all at the same memory offset.
/// On 64-Bit systems, the offset of the <see cref="mi"/>, <see cref="ki"/> and <see cref="hi"/> fields is 8,
/// because the nested struct uses the alignment of its biggest member, which is 8
/// (due to the 64-bit pointer in <see cref="KEYBDINPUT.dwExtraInfo"/>).
/// By separating the union into its own structure, rather than placing the
/// <see cref="mi"/>, <see cref="ki"/> and <see cref="hi"/> fields directly in the INPUT structure,
/// we assure that the .NET structure will have the correct alignment on both 32 and 64 bit.
/// </devremarks>
[Fact]
public unsafe void INPUT_UnionMemoryAlignment()
{
INPUT input;
Assert.Equal(IntPtr.Size, (long)&input.Inputs.hi - (long)&input);
Assert.Equal(IntPtr.Size, (long)&input.Inputs.mi - (long)&input);
Assert.Equal(IntPtr.Size, (long)&input.Inputs.ki - (long)&input);
}
}
| // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;
public partial class User32Facts
{
[Fact]
public void MessageBeep_Asterisk()
{
Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
}
[Fact]
public void INPUT_Union()
{
INPUT i = default(INPUT);
i.type = InputType.INPUT_HARDWARE;
// Assert that the first field (type) has its own memory space.
Assert.Equal(0u, i.Inputs.hi.uMsg);
Assert.Equal(0, (int)i.Inputs.ki.wScan);
Assert.Equal(0, i.Inputs.mi.dx);
// Assert that these three fields (hi, ki, mi) share memory space.
i.Inputs.hi.uMsg = 1;
Assert.Equal(1, (int)i.Inputs.ki.wVk);
Assert.Equal(1, i.Inputs.mi.dx);
}
}
| mit | C# |
33e44181c1d044f4c5a04a3a495290725df69d2a | Disable cached partials if in preview mode | marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS | src/Umbraco.Web/CacheHelperExtensions.cs | src/Umbraco.Web/CacheHelperExtensions.cs | using System;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Umbraco.Core.Cache;
namespace Umbraco.Web
{
/// <summary>
/// Extension methods for the cache helper
/// </summary>
public static class CacheHelperExtensions
{
public const string PartialViewCacheKey = "Umbraco.Web.PartialViewCacheKey";
/// <summary>
/// Outputs and caches a partial view in MVC
/// </summary>
/// <param name="appCaches"></param>
/// <param name="htmlHelper"></param>
/// <param name="partialViewName"></param>
/// <param name="model"></param>
/// <param name="cachedSeconds"></param>
/// <param name="cacheKey">used to cache the partial view, this key could change if it is cached by page or by member</param>
/// <param name="viewData"></param>
/// <returns></returns>
public static IHtmlString CachedPartialView(
this AppCaches appCaches,
HtmlHelper htmlHelper,
string partialViewName,
object model,
int cachedSeconds,
string cacheKey,
ViewDataDictionary viewData = null)
{
//disable cached partials in debug mode: http://issues.umbraco.org/issue/U4-5940
//disable cached partials in preview mode: https://github.com/umbraco/Umbraco-CMS/issues/10384
if (htmlHelper.ViewContext.HttpContext.IsDebuggingEnabled || Umbraco.Web.Composing.Current.UmbracoContext.InPreviewMode)
{
// just return a normal partial view instead
return htmlHelper.Partial(partialViewName, model, viewData);
}
return appCaches.RuntimeCache.GetCacheItem<IHtmlString>(
PartialViewCacheKey + cacheKey,
() => htmlHelper.Partial(partialViewName, model, viewData),
priority: CacheItemPriority.NotRemovable, //not removable, the same as macros (apparently issue #27610)
timeout: new TimeSpan(0, 0, 0, cachedSeconds));
}
/// <summary>
/// Clears the cache for partial views
/// </summary>
/// <param name="appCaches"></param>
public static void ClearPartialViewCache(this AppCaches appCaches)
{
appCaches.RuntimeCache.ClearByKey(PartialViewCacheKey);
}
}
}
| using System;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Umbraco.Core.Cache;
namespace Umbraco.Web
{
/// <summary>
/// Extension methods for the cache helper
/// </summary>
public static class CacheHelperExtensions
{
public const string PartialViewCacheKey = "Umbraco.Web.PartialViewCacheKey";
/// <summary>
/// Outputs and caches a partial view in MVC
/// </summary>
/// <param name="appCaches"></param>
/// <param name="htmlHelper"></param>
/// <param name="partialViewName"></param>
/// <param name="model"></param>
/// <param name="cachedSeconds"></param>
/// <param name="cacheKey">used to cache the partial view, this key could change if it is cached by page or by member</param>
/// <param name="viewData"></param>
/// <returns></returns>
public static IHtmlString CachedPartialView(
this AppCaches appCaches,
HtmlHelper htmlHelper,
string partialViewName,
object model,
int cachedSeconds,
string cacheKey,
ViewDataDictionary viewData = null)
{
//disable cached partials in debug mode: http://issues.umbraco.org/issue/U4-5940
if (htmlHelper.ViewContext.HttpContext.IsDebuggingEnabled)
{
// just return a normal partial view instead
return htmlHelper.Partial(partialViewName, model, viewData);
}
return appCaches.RuntimeCache.GetCacheItem<IHtmlString>(
PartialViewCacheKey + cacheKey,
() => htmlHelper.Partial(partialViewName, model, viewData),
priority: CacheItemPriority.NotRemovable, //not removable, the same as macros (apparently issue #27610)
timeout: new TimeSpan(0, 0, 0, cachedSeconds));
}
/// <summary>
/// Clears the cache for partial views
/// </summary>
/// <param name="appCaches"></param>
public static void ClearPartialViewCache(this AppCaches appCaches)
{
appCaches.RuntimeCache.ClearByKey(PartialViewCacheKey);
}
}
}
| mit | C# |
04097853cdfe93c776ef5bfa796c894e01c90d75 | Fix JavaScript loading in production | martincostello/website,martincostello/website,martincostello/website,martincostello/website | src/Website/Views/Shared/_Scripts.cshtml | src/Website/Views/Shared/_Scripts.cshtml | @model BowerVersions
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js" asp-append-version="true"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js" asp-append-version="true"></script>
<script src="~/lib/jquery.lazyload/jquery.lazyload.min.js" asp-append-version="true"></script>
<script src="~/lib/moment/moment.js" asp-append-version="true"></script>
<script src="~/assets/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/@Model["jquery"]/jquery.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous" defer>
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/@Model["bootstrap"]/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous" defer>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/@Model["jquery.lazyload"]/jquery.lazyload.min.js" integrity="sha256-rXnOfjTRp4iAm7hTAxEz3irkXzwZrElV2uRsdJAYjC4=" crossorigin="anonymous" defer>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/@Model["moment"]/moment.min.js" integrity="sha384-7pfELK0arQ3VANqV4kiPWPh5wOsrfitjFGF/NdyHXUJ3JJPy/rNhasPtdkaNKhul" crossorigin="anonymous" defer>
</script>
<script src="~/assets/js/site.min.js" asp-append-version="true" defer></script>
</environment>
| @model BowerVersions
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js" asp-append-version="true"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js" asp-append-version="true"></script>
<script src="~/lib/jquery.lazyload/jquery.lazyload.min.js" asp-append-version="true"></script>
<script src="~/lib/moment/moment.js" asp-append-version="true"></script>
<script src="~/assets/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/@Model["jquery"]/jquery.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous" async
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/@Model["bootstrap"]/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous" defer
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/@Model["jquery.lazyload"]/jquery.lazyload.min.js" integrity="sha256-rXnOfjTRp4iAm7hTAxEz3irkXzwZrElV2uRsdJAYjC4=" crossorigin="anonymous" defer
asp-fallback-src="~/lib/jquery.lazyload/jquery.lazyload.min.js"
asp-fallback-test="window.$.fn.lazyload">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/@Model["moment"]/moment.min.js" integrity="sha384-7pfELK0arQ3VANqV4kiPWPh5wOsrfitjFGF/NdyHXUJ3JJPy/rNhasPtdkaNKhul" crossorigin="anonymous" async
asp-fallback-src="~/lib/moment/min/moment.min.js"
asp-fallback-test="window.moment">
</script>
<script src="~/assets/js/site.min.js" asp-append-version="true" defer></script>
</environment>
| apache-2.0 | C# |
148ff561cdd079896f00b435646ab2cb389d391c | Add I8 and UI8 fields to the VariantType enum | jbevain/cecil,mono/cecil,fnajera-rac-de/cecil | Mono.Cecil/VariantType.cs | Mono.Cecil/VariantType.cs | //
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
namespace Mono.Cecil {
public enum VariantType {
None = 0,
I2 = 2,
I4 = 3,
R4 = 4,
R8 = 5,
CY = 6,
Date = 7,
BStr = 8,
Dispatch = 9,
Error = 10,
Bool = 11,
Variant = 12,
Unknown = 13,
Decimal = 14,
I1 = 16,
UI1 = 17,
UI2 = 18,
UI4 = 19,
I8 = 20,
UI8 = 21,
Int = 22,
UInt = 23
}
}
| //
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
namespace Mono.Cecil {
public enum VariantType {
None = 0,
I2 = 2,
I4 = 3,
R4 = 4,
R8 = 5,
CY = 6,
Date = 7,
BStr = 8,
Dispatch = 9,
Error = 10,
Bool = 11,
Variant = 12,
Unknown = 13,
Decimal = 14,
I1 = 16,
UI1 = 17,
UI2 = 18,
UI4 = 19,
Int = 22,
UInt = 23
}
}
| mit | C# |
4db6c1606874d23472d587fed3decc80e02b41e4 | Improve U2F view | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Manage/U2FAuthentication.cshtml | BTCPayServer/Views/Manage/U2FAuthentication.cshtml | @model BTCPayServer.U2F.Models.U2FAuthenticationViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.U2F, "Registered U2F devices");
}
<partial name="_StatusMessage" />
<form asp-action="AddU2FDevice" method="get">
<table class="table table-lg mb-4">
<thead>
<tr>
<th>Name</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var device in Model.Devices)
{
<tr>
<td>@device.Name</td>
<td class="text-right" >
<a asp-action="RemoveU2FDevice" asp-route-id="@device.Id">Remove</a>
</td>
</tr>
}
@if (!Model.Devices.Any())
{
<tr>
<td colspan="2" class="text-center h5 py-2">
No registered devices
</td>
</tr>
}
</tbody>
</table>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" name="Name" placeholder="New Device Name"/>
<button type="submit" class="btn btn-primary ml-2">
<span class="fa fa-plus"></span>
Add New Device
</button>
</div>
</div>
</form>
| @model BTCPayServer.U2F.Models.U2FAuthenticationViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.U2F, "Manage your registered U2F devices");
}
<partial name="_StatusMessage" />
<h4>Registered U2F Devices</h4>
<form asp-action="AddU2FDevice" method="get">
<table class="table table-lg">
<thead>
<tr>
<th >Name</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var device in Model.Devices)
{
<tr>
<td>@device.Name</td>
<td class="text-right" >
<a asp-action="RemoveU2FDevice" asp-route-id="@device.Id">Remove</a>
</td>
</tr>
}
@if (!Model.Devices.Any())
{
<tr>
<td colspan="2" class="text-center h5 py-2">
No registered devices
</td>
</tr>
}
<tr class="bg-gray">
<td>
<input type="text" class="form-control" name="Name" placeholder="New Device Name"/>
</td>
<td>
<div class="pull-right">
<button type="submit" class="btn btn-primary">Add New Device</button>
</div>
</td>
</tr>
</tbody>
</table>
</form>
| mit | C# |
41289acd9ab2e3a7b5f23b4160d31f6c2a3a5c21 | refactor event save+load tests | Pondidum/Ledger,Pondidum/Ledger | Ledger.Stores.Postgres.Tests/EventSaveLoadTests.cs | Ledger.Stores.Postgres.Tests/EventSaveLoadTests.cs | using System;
using System.Linq;
using Shouldly;
using TestsDomain.Events;
using Xunit;
namespace Ledger.Stores.Postgres.Tests
{
public class EventSaveLoadTests : PostgresTestBase
{
private readonly PostgresEventStore<Guid> _store;
public EventSaveLoadTests()
{
CleanupTables();
var create = new CreateGuidKeyedTablesCommand(ConnectionString);
create.Execute();
_store = new PostgresEventStore<Guid>(ConnectionString);
}
[Fact]
public void Events_should_keep_types_and_be_ordered()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll {SequenceID = 0, NewName = "Deed"},
new FixNameSpelling {SequenceID = 1, NewName = "Fix"},
};
var id = Guid.NewGuid();
_store.SaveEvents(id, toSave);
var loaded = _store.LoadEvents(id);
loaded.First().ShouldBeOfType<NameChangedByDeedPoll>();
loaded.Last().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_events_for_the_correct_aggregate_are_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
_store.SaveEvents(first, new[] { new FixNameSpelling { NewName = "Fix" } });
_store.SaveEvents(second, new[] { new NameChangedByDeedPoll { NewName = "Deed" } });
var loaded = _store.LoadEvents(first);
loaded.Single().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_the_latest_sequence_is_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
_store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 4 } });
_store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 5 } });
_store.SaveEvents(second, new[] { new NameChangedByDeedPoll { SequenceID = 6 } });
_store
.GetLatestSequenceFor(first)
.ShouldBe(5);
}
[Fact]
public void Loading_events_since_only_gets_events_after_the_sequence()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll { SequenceID = 3 },
new FixNameSpelling { SequenceID = 4 },
new FixNameSpelling { SequenceID = 5 },
new FixNameSpelling { SequenceID = 6 },
};
var id = Guid.NewGuid();
_store.SaveEvents(id, toSave);
var loaded = _store.LoadEventsSince(id, 4);
loaded.Select(x => x.SequenceID).ShouldBe(new[] { 5, 6 });
}
[Fact]
public void When_there_are_no_events_and_load_is_called()
{
var id = Guid.NewGuid();
var loaded = _store.LoadEventsSince(id, 4);
loaded.ShouldBeEmpty();
}
}
}
| using System;
using System.Linq;
using Shouldly;
using TestsDomain.Events;
using Xunit;
namespace Ledger.Stores.Postgres.Tests
{
public class EventSaveLoadTests : PostgresTestBase
{
public EventSaveLoadTests()
{
CleanupTables();
var create = new CreateGuidKeyedTablesCommand(ConnectionString);
create.Execute();
}
[Fact]
public void Events_should_keep_types_and_be_ordered()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll {SequenceID = 0, NewName = "Deed"},
new FixNameSpelling {SequenceID = 1, NewName = "Fix"},
};
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(id, toSave);
var loaded = store.LoadEvents(id);
loaded.First().ShouldBeOfType<NameChangedByDeedPoll>();
loaded.Last().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_events_for_the_correct_aggregate_are_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(first, new[] { new FixNameSpelling { NewName = "Fix" } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { NewName = "Deed" } });
var loaded = store.LoadEvents(first);
loaded.Single().ShouldBeOfType<FixNameSpelling>();
}
[Fact]
public void Only_the_latest_sequence_is_returned()
{
var first = Guid.NewGuid();
var second = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 4 } });
store.SaveEvents(first, new[] { new FixNameSpelling { SequenceID = 5 } });
store.SaveEvents(second, new[] { new NameChangedByDeedPoll { SequenceID = 6 } });
store
.GetLatestSequenceFor(first)
.ShouldBe(5);
}
[Fact]
public void Loading_events_since_only_gets_events_after_the_sequence()
{
var toSave = new DomainEvent[]
{
new NameChangedByDeedPoll { SequenceID = 3 },
new FixNameSpelling { SequenceID = 4 },
new FixNameSpelling { SequenceID = 5 },
new FixNameSpelling { SequenceID = 6 },
};
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
store.SaveEvents(id, toSave);
var loaded = store.LoadEventsSince(id, 4);
loaded.Select(x => x.SequenceID).ShouldBe(new[] { 5, 6 });
}
[Fact]
public void When_there_are_no_events_and_load_is_called()
{
var id = Guid.NewGuid();
var store = new PostgresEventStore<Guid>(ConnectionString);
var loaded = store.LoadEventsSince(id, 4);
loaded.ShouldBeEmpty();
}
}
}
| lgpl-2.1 | C# |
f42ea0fc6bd6741a1cf8b9528a6a0e319aeff570 | Add boat move logic | Powersource/boat-ggj17 | Assets/GameLogic.cs | Assets/GameLogic.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameLogic : MonoBehaviour {
public GameObject myFishToSpawn;
public GameObject wavePrefab;
public float minSpawnDelay = 1.5f;
public float maxSpawnDelay = 2.5f;
private float myNextSpawnDelay = 1f;
private float mySpawnTimer;
private float myMinYSpawn = -3.5f;
private float myMaxYSpawn = -2.5f;
private int myScore = 0;
private GameObject myGUIScoreText;
public Text myScoreText;
private GameObject waves;
private float waveWidth = 140/100f; // 100 pixels per unit
private float waveSpeed = 0.05f;
private GameObject boat;
private Vector2 driveDir = Vector2.zero;
private float boatSpeed = 0.08f;
// Use this for initialization
void Start () {
//set myMinYSpawn and myMaxYSpawn depending on screen size
myGUIScoreText = GameObject.FindGameObjectWithTag("GUIScoreText");
waves = new GameObject ("waves");
for (int i = 0; i < 20; i++) {
Debug.Log ("i: " + i);
GameObject newWave = (GameObject)Instantiate (wavePrefab);
newWave.transform.localPosition = new Vector2 (i * waveWidth - 10 * waveWidth, 0);
newWave.transform.parent = waves.transform;
}
boat = GameObject.Find ("boat");
}
// Update is called once per frame
void Update () {
mySpawnTimer += Time.deltaTime;
if (mySpawnTimer > myNextSpawnDelay)
{
myNextSpawnDelay = Random.Range(minSpawnDelay, maxSpawnDelay);
mySpawnTimer = 0;
GameObject newFish = (GameObject)Instantiate(myFishToSpawn);
newFish.transform.position = new Vector3(16, Random.Range(myMinYSpawn, myMaxYSpawn));
}
driveDir = new Vector2(Input.GetAxisRaw ("Horizontal"), 0);
}
void FixedUpdate() {
updateWaves ();
steerBoat ();
}
void updateWaves() {
for (int i = 0; i<20; i++) {
GameObject child = waves.transform.GetChild (i).gameObject;
child.transform.Translate (Vector2.left * waveSpeed);
if (child.transform.position.x < -10 * waveWidth) {
child.transform.Translate (Vector2.right * 20f * waveWidth);
}
}
}
void steerBoat() {
boat.transform.Translate (driveDir * boatSpeed);
boat.transform.
}
void UpdateScore(int aAddToScore)
{
myScore += aAddToScore;
myScoreText.SendMessage("UpdateScore", myScore);
//Debug.Log(myScore);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameLogic : MonoBehaviour {
public GameObject myFishToSpawn;
public GameObject wavePrefab;
public float minSpawnDelay = 1.5f;
public float maxSpawnDelay = 2.5f;
private float myNextSpawnDelay = 1f;
private float mySpawnTimer;
private float myMinYSpawn = -3.5f;
private float myMaxYSpawn = -2.5f;
private int myScore = 0;
private GameObject myGUIScoreText;
public Text myScoreText;
private GameObject waves;
private float waveWidth = 140/100f; // 100 pixels per unit
private float waveSpeed = 0.05f;
// Use this for initialization
void Start () {
//set myMinYSpawn and myMaxYSpawn depending on screen size
myGUIScoreText = GameObject.FindGameObjectWithTag("GUIScoreText");
waves = new GameObject ("waves");
for (int i = 0; i < 20; i++) {
Debug.Log ("i: " + i);
GameObject newWave = (GameObject)Instantiate (wavePrefab);
newWave.transform.localPosition = new Vector2 (i * waveWidth - 10 * waveWidth, 0);
newWave.transform.parent = waves.transform;
}
}
// Update is called once per frame
void Update () {
mySpawnTimer += Time.deltaTime;
if (mySpawnTimer > myNextSpawnDelay)
{
myNextSpawnDelay = Random.Range(minSpawnDelay, maxSpawnDelay);
mySpawnTimer = 0;
GameObject newFish = (GameObject)Instantiate(myFishToSpawn);
newFish.transform.position = new Vector3(16, Random.Range(myMinYSpawn, myMaxYSpawn));
}
}
void FixedUpdate() {
updateWaves ();
}
void updateWaves() {
for (int i = 0; i<20; i++) {
GameObject child = waves.transform.GetChild (i).gameObject;
child.transform.Translate (Vector2.left * waveSpeed);
if (child.transform.position.x < -10 * waveWidth) {
child.transform.Translate (Vector2.right * 20f * waveWidth);
}
}
}
void UpdateScore(int aAddToScore)
{
myScore += aAddToScore;
myScoreText.SendMessage("UpdateScore", myScore);
//Debug.Log(myScore);
}
}
| mit | C# |
f552d2313b6d5fe7ceed65318db809b9831efb58 | add trace stack in Coroutine -> resume | zhukunqian/slua-1,soulgame/slua,haolly/slua_source_note,Roland0511/slua,dayongxie/slua,angeldnd/slua,lingkeyang/slua,dayongxie/slua,LacusCon/slua,angeldnd/slua,chiuan/slua,chiuan/slua,jiangzhhhh/slua,yaukeywang/slua,jiangzhhhh/slua,DebugClub/slua,Salada/slua,Salada/slua,lingkeyang/slua,haolly/slua_source_note,thing-nacho/slua,LacusCon/slua,zhukunqian/slua-1,dayongxie/slua,dayongxie/slua,haolly/slua_source_note,chiuan/slua,thing-nacho/slua,zhukunqian/slua-1,lingkeyang/slua,pangweiwei/slua,soulgame/slua,mr-kelly/slua,yaukeywang/slua,pangweiwei/slua,lingkeyang/slua,LacusCon/slua,luzexi/slua-3rd-lib,Roland0511/slua,haolly/slua_source_note,luzexi/slua-3rd,jiangzhhhh/slua,DebugClub/slua,lingkeyang/slua,Salada/slua,Roland0511/slua,mr-kelly/slua,luzexi/slua-3rd-lib,Salada/slua,soulgame/slua,luzexi/slua-3rd-lib,DebugClub/slua,yaukeywang/slua,luzexi/slua-3rd-lib,soulgame/slua,pangweiwei/slua,Roland0511/slua,angeldnd/slua,DebugClub/slua,soulgame/slua,chiuan/slua,chiuan/slua,thing-nacho/slua,thing-nacho/slua,haolly/slua_source_note,thing-nacho/slua,Roland0511/slua,DebugClub/slua,yaukeywang/slua,thing-nacho/slua,shrimpz/slua,soulgame/slua,mr-kelly/slua,lingkeyang/slua,luzexi/slua-3rd-lib,LacusCon/slua,angeldnd/slua,haolly/slua_source_note,pangweiwei/slua,yaukeywang/slua,Roland0511/slua,jiangzhhhh/slua,Salada/slua,luzexi/slua-3rd,luzexi/slua-3rd,luzexi/slua-3rd-lib,zhukunqian/slua-1,chiuan/slua,shrimpz/slua,Salada/slua,mr-kelly/slua,luzexi/slua-3rd,zhukunqian/slua-1,angeldnd/slua,yaukeywang/slua,luzexi/slua-3rd,DebugClub/slua,mr-kelly/slua,LacusCon/slua,LacusCon/slua,dayongxie/slua,pangweiwei/slua,angeldnd/slua,mr-kelly/slua,jiangzhhhh/slua,jiangzhhhh/slua,luzexi/slua-3rd | Assets/Slua/Script/Coroutine.cs | Assets/Slua/Script/Coroutine.cs | // The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei [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 UnityEngine;
using System.Collections;
using LuaInterface;
using SLua;
using System;
namespace SLua
{
public class LuaCoroutine : LuaObject
{
static MonoBehaviour mb;
static public void reg(IntPtr l, MonoBehaviour m)
{
mb = m;
reg(l, Yield, "UnityEngine");
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
static public int Yield(IntPtr l)
{
try
{
if (LuaDLL.lua_pushthread(l) == 1)
{
LuaDLL.luaL_error(l, "should put Yield call into lua coroutine.");
return 0;
}
object y = checkObj(l, 1);
Action act = () =>
{
#if LUA_5_3
if(LuaDLL.lua_resume(l,IntPtr.Zero,0) != 0)
{
LuaState.errorReport(l);
}
#else
if (LuaDLL.lua_resume(l, 0) != 0)
{
LuaState.errorReport(l);
}
#endif
};
mb.StartCoroutine(yieldReturn(y, act));
#if LUA_5_3
return LuaDLL.luaS_yield(l, 0);
#else
return LuaDLL.lua_yield(l, 0);
#endif
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
static public IEnumerator yieldReturn(object y, Action act)
{
if (y is IEnumerator)
yield return mb.StartCoroutine((IEnumerator)y);
else
yield return y;
act();
}
}
}
| // The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei [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 UnityEngine;
using System.Collections;
using LuaInterface;
using SLua;
using System;
namespace SLua
{
public class LuaCoroutine : LuaObject
{
static MonoBehaviour mb;
static public void reg(IntPtr l, MonoBehaviour m)
{
mb = m;
reg(l, Yield, "UnityEngine");
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
static public int Yield(IntPtr l)
{
try
{
if (LuaDLL.lua_pushthread(l) == 1)
{
LuaDLL.luaL_error(l, "should put Yield call into lua coroutine.");
return 0;
}
object y = checkObj(l, 1);
Action act = () =>
{
#if LUA_5_3
LuaDLL.lua_resume(l,IntPtr.Zero,0);
#else
LuaDLL.lua_resume(l, 0);
#endif
};
mb.StartCoroutine(yieldReturn(y, act));
#if LUA_5_3
return LuaDLL.luaS_yield(l, 0);
#else
return LuaDLL.lua_yield(l, 0);
#endif
}
catch (Exception e)
{
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
static public IEnumerator yieldReturn(object y, Action act)
{
if (y is IEnumerator)
yield return mb.StartCoroutine((IEnumerator)y);
else
yield return y;
act();
}
}
}
| mit | C# |
123f1dbe39075e798b72eabbefd1d053e3a48df2 | build non profit tables and add to items table | kevinphelps/base-rest | BaseDomain/Models/BaseDomain.cs | BaseDomain/Models/BaseDomain.cs | using BaseDomain.General;
using General;
using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
namespace BaseDomain.Models
{
public abstract class BaseDomain : IDomain
{
[Key]
public int Id { get; private set; }
public DateTime UtcDateCreated { get; private set; }
public DateTime UtcDateModified { get; private set; }
public DateTime? UtcDateDeleted { get; private set; }
public void InitializeId(int id)
{
if (this.Id != 0)
{
throw new RestfulException(HttpStatusCode.Conflict, "Id already initialized");
}
this.Id = id;
}
public void Create()
{
if (this.UtcDateCreated != default(DateTime))
{
throw new RestfulException(HttpStatusCode.Conflict, "Domain already created.");
}
this.UtcDateCreated = DateTime.UtcNow;
this.UtcDateModified = DateTime.UtcNow;
}
public void Modify()
{
this.UtcDateModified = DateTime.UtcNow;
}
public void Delete()
{
if (this.UtcDateDeleted.HasValue)
{
throw new RestfulException(HttpStatusCode.Conflict, "Domain already deleted.");
}
this.UtcDateDeleted = DateTime.UtcNow;
}
}
}
| using BaseDomain.General;
using General;
using System;
using System.Net;
namespace BaseDomain.Models
{
public abstract class BaseDomain : IDomain
{
public int Id { get; private set; }
public DateTime UtcDateCreated { get; private set; }
public DateTime UtcDateModified { get; private set; }
public DateTime? UtcDateDeleted { get; private set; }
public void InitializeId(int id)
{
if (this.Id != 0)
{
throw new RestfulException(HttpStatusCode.Conflict, "Id already initialized");
}
this.Id = id;
}
public void Create()
{
if (this.UtcDateCreated != default(DateTime))
{
throw new RestfulException(HttpStatusCode.Conflict, "Domain already created.");
}
this.UtcDateCreated = DateTime.UtcNow;
this.UtcDateModified = DateTime.UtcNow;
}
public void Modify()
{
this.UtcDateModified = DateTime.UtcNow;
}
public void Delete()
{
if (this.UtcDateDeleted.HasValue)
{
throw new RestfulException(HttpStatusCode.Conflict, "Domain already deleted.");
}
this.UtcDateDeleted = DateTime.UtcNow;
}
}
}
| mit | C# |
77cc99331f2b0a1db9f6421c7908b5227034dd2e | Add short link to Service | KpdApps/KpdApps.Common.MsCrm2015 | BasePluginAction.cs | BasePluginAction.cs | using System;
using Microsoft.Xrm.Sdk;
namespace KpdApps.Common.MsCrm2015
{
public class BasePluginAction
{
public PluginState State { get; set; }
public IOrganizationService Service => State.Service;
public BasePluginAction(PluginState state)
{
State = state;
}
public virtual void Execute()
{
throw new NotImplementedException();
}
}
}
| using System;
namespace KpdApps.Common.MsCrm2015
{
public class BasePluginAction
{
public PluginState State { get; set; }
public BasePluginAction(PluginState state)
{
State = state;
}
public virtual void Execute()
{
throw new NotImplementedException();
}
}
}
| mit | C# |
97ea1a3f3200404c94a5cdc42bd15326be7841f3 | Remove unused NullGestureMachine class. | rubyu/CreviceApp,rubyu/CreviceApp | CreviceApp/GM.GestureMachine.cs | CreviceApp/GM.GestureMachine.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Crevice.GestureMachine
{
using System.Threading;
using System.Drawing;
using Crevice.Core.FSM;
using Crevice.Core.Events;
using Crevice.Threading;
public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext>
{
public GestureMachine(
GestureMachineConfig gestureMachineConfig,
CallbackManager callbackManager)
: base(gestureMachineConfig, callbackManager, new ContextManager())
{ }
private readonly LowLatencyScheduler _strokeWatcherScheduler =
new LowLatencyScheduler( "StrokeWatcherTaskScheduler", ThreadPriority.AboveNormal, 1);
protected override TaskFactory StrokeWatcherTaskFactory
=> new TaskFactory(_strokeWatcherScheduler);
public override bool Input(IPhysicalEvent evnt, Point? point)
{
lock (lockObject)
{
if (point.HasValue)
{
ContextManager.CursorPosition = point.Value;
}
return base.Input(evnt, point);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
ContextManager.Dispose();
_strokeWatcherScheduler.Dispose();
}
base.Dispose(disposing);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Crevice.GestureMachine
{
using System.Threading;
using System.Drawing;
using Crevice.Core.FSM;
using Crevice.Core.Events;
using Crevice.Threading;
public class NullGestureMachine : GestureMachine
{
public NullGestureMachine()
: base(new GestureMachineConfig(), new CallbackManager())
{ }
}
public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext>
{
public GestureMachine(
GestureMachineConfig gestureMachineConfig,
CallbackManager callbackManager)
: base(gestureMachineConfig, callbackManager, new ContextManager())
{ }
private readonly LowLatencyScheduler _strokeWatcherScheduler =
new LowLatencyScheduler( "StrokeWatcherTaskScheduler", ThreadPriority.AboveNormal, 1);
protected override TaskFactory StrokeWatcherTaskFactory
=> new TaskFactory(_strokeWatcherScheduler);
public override bool Input(IPhysicalEvent evnt, Point? point)
{
lock (lockObject)
{
if (point.HasValue)
{
ContextManager.CursorPosition = point.Value;
}
return base.Input(evnt, point);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
ContextManager.Dispose();
_strokeWatcherScheduler.Dispose();
}
base.Dispose(disposing);
}
}
}
| mit | C# |
5ae642d42b38a951150dd6de5cdabc8629bd052a | Make Group.Participants an ICollection | ermau/Tempest.Social | Desktop/Tempest.Social/Group.cs | Desktop/Tempest.Social/Group.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Tempest.Social
{
public class Group
{
public Group (int id)
{
Id = id;
}
public Group (int id, IEnumerable<string> participants)
: this (id)
{
if (participants == null)
throw new ArgumentNullException ("participants");
foreach (string participant in participants)
this.participants.Add (participant);
}
public int Id
{
get;
private set;
}
public ICollection<string> Participants
{
get { return this.participants; }
}
private readonly ObservableCollection<string> participants = new ObservableCollection<string>();
}
public class GroupSerializer
: ISerializer<Group>
{
public static readonly GroupSerializer Instance = new GroupSerializer();
public void Serialize (ISerializationContext context, IValueWriter writer, Group element)
{
writer.WriteInt32 (element.Id);
writer.WriteEnumerable (context, Serializer<string>.Default, element.Participants);
}
public Group Deserialize (ISerializationContext context, IValueReader reader)
{
return new Group (reader.ReadInt32(), reader.ReadEnumerable (context, Serializer<string>.Default));
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Tempest.Social
{
public class Group
{
public Group (int id)
{
Id = id;
}
public Group (int id, IEnumerable<string> participants)
: this (id)
{
if (participants == null)
throw new ArgumentNullException ("participants");
foreach (string participant in participants)
this.participants.Add (participant);
}
public int Id
{
get;
private set;
}
public IEnumerable<string> Participants
{
get { return this.participants; }
}
internal readonly ObservableCollection<string> participants = new ObservableCollection<string>();
}
public class GroupSerializer
: ISerializer<Group>
{
public static readonly GroupSerializer Instance = new GroupSerializer();
public void Serialize (ISerializationContext context, IValueWriter writer, Group element)
{
writer.WriteInt32 (element.Id);
writer.WriteEnumerable (context, Serializer<string>.Default, element.Participants);
}
public Group Deserialize (ISerializationContext context, IValueReader reader)
{
return new Group (reader.ReadInt32(), reader.ReadEnumerable (context, Serializer<string>.Default));
}
}
} | mit | C# |
7c39a9a794e4284d3261035b94c0690328b014b9 | fix gameover | enpel/ggj2017-deliciousset | UnityProject/Assets/Scripts/State/GameOverState.cs | UnityProject/Assets/Scripts/State/GameOverState.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
using UnityEngine.SceneManagement;
using System.Linq;
public class GameOverState : SceneState
{
[SerializeField]
SceneState nextState;
public override void Initialize ()
{
base.Initialize ();
UIManager.Instance.SwitchPhase (UIPhase.GAMEOVER);
MyInput.GetInputStream().Merge(UIManager.Instance.GetOnClickRetryStream ()).First().Subscribe (x => {
GameManager.Instance.State.Value = nextState;
}).AddTo (this);
GameObject.FindObjectsOfType<Enemy> ().ToList ().ForEach (enemy => {
enemy.hp.OnDamage(enemy.hp.MaxHP);
});
}
public override void End ()
{
base.End ();
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
using UnityEngine.SceneManagement;
public class GameOverState : SceneState
{
[SerializeField]
SceneState nextState;
public override void Initialize ()
{
base.Initialize ();
UIManager.Instance.SwitchPhase (UIPhase.GAMEOVER);
MyInput.GetInputStream().Merge(UIManager.Instance.GetOnClickRetryStream ()).First().Subscribe (x => {
GameManager.Instance.State.Value = nextState;
}).AddTo (this);
}
public override void End ()
{
base.End ();
}
}
| mit | C# |
07ff547da3fe0c55ecf3142eac5c954183bbaa02 | add comment on allowed LINQ usage | isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,maul-esel/ssharp | models/SelfOrganizingPillProduction/Modeling/Recipe.cs | models/SelfOrganizingPillProduction/Modeling/Recipe.cs | using System.Collections.Generic;
using System.Linq;
namespace SelfOrganizingPillProduction.Modeling
{
/// <summary>
/// Describes how a container should be processed.
/// </summary>
public class Recipe
{
/// <summary>
/// Creates a new recipe with the specified sequence of ingredients.
/// </summary>
/// <param name="ingredients">The sequence of ingredients to add to the containers.</param>
/// <param name="amount">The number of containers to produce for this recipe.</param>
public Recipe(Ingredient[] ingredients, uint amount)
{
ActiveContainers = new List<PillContainer>((int)amount);
Amount = amount;
// only executed during setup; can therefore use LINQ (and create objects)
RequiredCapabilities = new Capability[] { ProduceCapability.Instance }
.Concat(ingredients)
.Concat(new[] { ConsumeCapability.Instance })
.ToArray();
}
/// <summary>
/// A list of all containers processed according to this recipe that are currently in the system.
/// </summary>
public List<PillContainer> ActiveContainers { get; }
/// <summary>
/// The sequence of capabilities defining this recipe.
/// </summary>
public Capability[] RequiredCapabilities { get; }
/// <summary>
/// The total number of containers to be produced for this recipe.
/// </summary>
public uint Amount { get; }
}
}
| using System.Collections.Generic;
using System.Linq;
namespace SelfOrganizingPillProduction.Modeling
{
/// <summary>
/// Describes how a container should be processed.
/// </summary>
public class Recipe
{
/// <summary>
/// Creates a new recipe with the specified sequence of ingredients.
/// </summary>
/// <param name="ingredients">The sequence of ingredients to add to the containers.</param>
/// <param name="amount">The number of containers to produce for this recipe.</param>
public Recipe(Ingredient[] ingredients, uint amount)
{
ActiveContainers = new List<PillContainer>((int)amount);
Amount = amount;
RequiredCapabilities = new Capability[] { ProduceCapability.Instance }
.Concat(ingredients)
.Concat(new[] { ConsumeCapability.Instance })
.ToArray();
}
/// <summary>
/// A list of all containers processed according to this recipe that are currently in the system.
/// </summary>
public List<PillContainer> ActiveContainers { get; }
/// <summary>
/// The sequence of capabilities defining this recipe.
/// </summary>
public Capability[] RequiredCapabilities { get; }
/// <summary>
/// The total number of containers to be produced for this recipe.
/// </summary>
public uint Amount { get; }
}
}
| mit | C# |
4bcab1d57fe2803e95bf366f5488a311eef16435 | Clarify the apparently unused generic type parameter. | damiensawyer/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,honestegg/cassette,honestegg/cassette,BluewireTechnologies/cassette,damiensawyer/cassette,andrewdavey/cassette,damiensawyer/cassette,honestegg/cassette,andrewdavey/cassette | src/Cassette/Configuration/IFileSearchModifier.cs | src/Cassette/Configuration/IFileSearchModifier.cs | namespace Cassette.Configuration
{
// ReSharper disable UnusedTypeParameter
// The T type parameter makes it easy to distinguish between file search modifiers for the different type of bundles
public interface IFileSearchModifier<T>
where T : Bundle
// ReSharper restore UnusedTypeParameter
{
void Modify(FileSearch fileSearch);
}
} | namespace Cassette.Configuration
{
public interface IFileSearchModifier<T>
{
void Modify(FileSearch fileSearch);
}
} | mit | C# |
0072842b13aee54d5f1519f8732b5cb282f2a5f4 | Add test. | JetBrains/Nitra,rsdn/nitra,rsdn/nitra,JetBrains/Nitra | Tests/!Positive/Json-2.cs | Tests/!Positive/Json-2.cs | // REFERENCE: Json.Grammar.dll
using N2;
using N2.Tests;
using System;
using System.IO;
namespace Sample.Json.Cs
{
class Program
{
static void Main()
{
Test(@"{ : 1}");
Test(@"{ a }");
Test(@"{ a: }");
Test(@"{ a:, }");
Test(@"{ 'a':, a:1}")
}
static void Test(string text)
{
var source = new SourceSnapshot(text);
var parserHost = new ParserHost();
var parseResult = JsonParser.Start(source, parserHost);
var ast = JsonParserAstWalkers.Start(parseResult);
Console.WriteLine("Pretty print: " + ast.ToString(ToStringOptions.DebugIndent | ToStringOptions.MissingNodes));
}
}
}
/*
BEGIN-OUTPUT
Pretty print: {
### MISSING ###: 1
}
Pretty print: {
a: ### MISSING ###
}
Pretty print: {
a: ### MISSING ###
}
Pretty print: {
a: ### MISSING ###,
### MISSING ###
}
Pretty print: {
'a': ### MISSING ###,
a: 1
}
END-OUTPUT
*/
| // REFERENCE: Json.Grammar.dll
using N2;
using N2.Tests;
using System;
using System.IO;
namespace Sample.Json.Cs
{
class Program
{
static void Main()
{
Test(@"{ : 1}");
Test(@"{ a }");
Test(@"{ a: }");
Test(@"{ a:, }");
}
static void Test(string text)
{
var source = new SourceSnapshot(text);
var parserHost = new ParserHost();
var parseResult = JsonParser.Start(source, parserHost);
var ast = JsonParserAstWalkers.Start(parseResult);
Console.WriteLine("Pretty print: " + ast.ToString(ToStringOptions.DebugIndent | ToStringOptions.MissingNodes));
}
}
}
/*
BEGIN-OUTPUT
Pretty print: {
### MISSING ###: 1
}
Pretty print: {
a: ### MISSING ###
}
Pretty print: {
a: ### MISSING ###
}
Pretty print: {
a: ### MISSING ###,
### MISSING ###
}
END-OUTPUT
*/
| apache-2.0 | C# |
afa31ac8b25d9ed3fac1d5531cb83c897e876b4f | Add option for allowed user roles | mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Server.Web/GlimpseServerWebOptions.cs | src/Glimpse.Server.Web/GlimpseServerWebOptions.cs | using System;
using System.Collections.Generic;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public GlimpseServerWebOptions()
{
AllowedUserRoles = new List<string>();
}
public bool AllowRemote { get; set; }
public IList<string> AllowedUserRoles { get; }
}
} | using System;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public bool AllowRemote { get; set; }
}
} | mit | C# |
cbe6125a10081ab232c363acff36aa3bd8b477d2 | handle errors in event chanel consumers | LykkeCity/MT,LykkeCity/MT,LykkeCity/MT | src/MarginTrading.Services/Events/EventChannel.cs | src/MarginTrading.Services/Events/EventChannel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Common;
using Common.Log;
namespace MarginTrading.Services.Events
{
public class EventChannel<TEventArgs> : IEventChannel<TEventArgs>, IDisposable
{
private IComponentContext _container;
private readonly ILog _log;
private IEventConsumer<TEventArgs>[] _consumers;
private readonly object _sync = new object();
public EventChannel(IComponentContext container, ILog log)
{
_container = container;
_log = log;
}
public void SendEvent(object sender, TEventArgs ea)
{
AssertInitialized();
foreach (var consumer in _consumers)
{
try
{
consumer.ConsumeEvent(sender, ea);
}
catch (Exception e)
{
_log.WriteErrorAsync($"Event chanel {typeof(TEventArgs).Name}", "SendEvent", ea.ToJson(), e);
}
}
}
public void Dispose()
{
_consumers = null;
_container = null;
}
public int AssertInitialized()
{
if (null != _consumers)
return _consumers.Length;
lock (_sync)
{
if (null != _consumers)
return _consumers.Length;
if (null == _container)
throw new ObjectDisposedException(GetType().Name);
_consumers =
Enumerable.OrderBy(_container.Resolve<IEnumerable<IEventConsumer<TEventArgs>>>(), x => x.ConsumerRank).ToArray();
_container = null;
}
return _consumers.Length;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
namespace MarginTrading.Services.Events
{
public class EventChannel<TEventArgs> : IEventChannel<TEventArgs>, IDisposable
{
private IComponentContext _container;
private IEventConsumer<TEventArgs>[] _consumers;
private readonly object _sync = new object();
public EventChannel(IComponentContext container)
{
_container = container;
}
public void SendEvent(object sender, TEventArgs ea)
{
AssertInitialized();
foreach (var consumer in _consumers)
consumer.ConsumeEvent(sender, ea);
}
public void Dispose()
{
_consumers = null;
_container = null;
}
public int AssertInitialized()
{
if (null != _consumers)
return _consumers.Length;
lock (_sync)
{
if (null != _consumers)
return _consumers.Length;
if (null == _container)
throw new ObjectDisposedException(GetType().Name);
_consumers =
Enumerable.OrderBy(_container.Resolve<IEnumerable<IEventConsumer<TEventArgs>>>(), x => x.ConsumerRank).ToArray();
_container = null;
}
return _consumers.Length;
}
}
}
| mit | C# |
ff5c6882632d7a5b87006446ab78e53f3e356e23 | bump version | cuongtranba/DateTimeExtensions,kappy/DateTimeExtensions,cuongtranba/DateTimeExtensions,cuongtranba/DateTimeExtensions | DateTimeExtensions/Properties/AssemblyInfo.cs | DateTimeExtensions/Properties/AssemblyInfo.cs | 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("DateTimeExtensions")]
[assembly: AssemblyDescription("Merge of extensions for System.DateTime like localized working days with holidays calculations and natural time date difference")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kappy")]
[assembly: AssemblyProduct("DateTimeExtensions")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("28ebf94f-cb26-4d0a-916e-9317bb4c7392")]
// 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("2.0.5.0")]
[assembly: AssemblyFileVersion("2.0.5.0")]
[assembly: CLSCompliant(true)] | 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("DateTimeExtensions")]
[assembly: AssemblyDescription("Merge of extensions for System.DateTime like localized working days with holidays calculations and natural time date difference")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kappy")]
[assembly: AssemblyProduct("DateTimeExtensions")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("28ebf94f-cb26-4d0a-916e-9317bb4c7392")]
// 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("2.0.4.0")]
[assembly: AssemblyFileVersion("2.0.4.0")]
[assembly: CLSCompliant(true)] | apache-2.0 | C# |
278584de99e416aed21ef3034a88d072d61de2c4 | Disable optimisations validator (in line with framework project) | NeoAdonis/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu | osu.Game.Benchmarks/Program.cs | osu.Game.Benchmarks/Program.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 BenchmarkDotNet.Configs;
using BenchmarkDotNet.Running;
namespace osu.Game.Benchmarks
{
public static class Program
{
public static void Main(string[] args)
{
BenchmarkSwitcher
.FromAssembly(typeof(Program).Assembly)
.Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true));
}
}
}
| // 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 BenchmarkDotNet.Running;
namespace osu.Game.Benchmarks
{
public static class Program
{
public static void Main(string[] args)
{
BenchmarkSwitcher
.FromAssembly(typeof(Program).Assembly)
.Run(args);
}
}
}
| mit | C# |
b63a90966ba260c5122203c4b06299d2af40aa52 | Remove misplaced access modifier in interface specification | ppy/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu | osu.Game/Scoring/IScoreInfo.cs | osu.Game/Scoring/IScoreInfo.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 osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Rulesets;
using osu.Game.Users;
namespace osu.Game.Scoring
{
public interface IScoreInfo : IHasOnlineID<long>
{
User User { get; }
long TotalScore { get; }
int MaxCombo { get; }
double Accuracy { get; }
bool HasReplay { get; }
DateTimeOffset Date { get; }
double? PP { get; }
IBeatmapInfo Beatmap { get; }
IRulesetInfo Ruleset { get; }
ScoreRank Rank { get; }
// Mods is currently missing from this interface as the `IMod` class has properties which can't be fulfilled by `APIMod`,
// but also doesn't expose `Settings`. We can consider how to implement this in the future if required.
// Statistics is also missing. This can be reconsidered once changes in serialisation have been completed.
}
}
| // 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 osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Rulesets;
using osu.Game.Users;
namespace osu.Game.Scoring
{
public interface IScoreInfo : IHasOnlineID<long>
{
User User { get; }
long TotalScore { get; }
int MaxCombo { get; }
double Accuracy { get; }
bool HasReplay { get; }
DateTimeOffset Date { get; }
double? PP { get; }
IBeatmapInfo Beatmap { get; }
IRulesetInfo Ruleset { get; }
public ScoreRank Rank { get; }
// Mods is currently missing from this interface as the `IMod` class has properties which can't be fulfilled by `APIMod`,
// but also doesn't expose `Settings`. We can consider how to implement this in the future if required.
// Statistics is also missing. This can be reconsidered once changes in serialisation have been completed.
}
}
| mit | C# |
df5bf741b163717721c330e9827014c0bd27efd4 | Implement basic constant folding of Add operator in ConstantFoldingExprBuilder. This fixes several tests that depend on this behaviour. | symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix | src/Symbooglix/Expr/ConstantFoldingExprBuilder.cs | src/Symbooglix/Expr/ConstantFoldingExprBuilder.cs | using System;
using Microsoft.Boogie;
using Microsoft.Basetypes;
using System.Collections.Generic;
using System.Diagnostics;
namespace Symbooglix
{
public class ConstantFoldingExprBuilder : DecoratorExprBuilder
{
public ConstantFoldingExprBuilder(IExprBuilder underlyingBuilder) : base(underlyingBuilder)
{
}
// TODO Overload methods that we can constant fold
public override Expr Add(Expr lhs, Expr rhs)
{
if (lhs is LiteralExpr && rhs is LiteralExpr)
{
var literalLhs = lhs as LiteralExpr;
var literalRhs = rhs as LiteralExpr;
if (literalLhs.isBigNum && literalRhs.isBigNum)
{
// Int
var result = literalLhs.asBigNum + literalRhs.asBigNum;
return UB.ConstantInt(result.ToBigInteger);
}
else if (literalLhs.isBigDec && literalRhs.isBigDec)
{
// Real
return UB.ConstantReal(literalLhs.asBigDec + literalRhs.asBigDec);
}
}
return UB.Add(lhs, rhs);
}
}
}
| using System;
namespace Symbooglix
{
public class ConstantFoldingExprBuilder : DecoratorExprBuilder
{
public ConstantFoldingExprBuilder(IExprBuilder underlyingBuilder) : base(underlyingBuilder)
{
}
// TODO Overload methods that we can constant fold
}
}
| bsd-2-clause | C# |
a365d56d84672dd9af64d95c9eddf1b607eb7ce3 | use != | NServiceBusSqlPersistence/NServiceBus.SqlPersistence | src/SqlPersistence/SynchronizedStorage/StorageAdapter.cs | src/SqlPersistence/SynchronizedStorage/StorageAdapter.cs | using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Transactions;
using NServiceBus;
using NServiceBus.Extensibility;
using NServiceBus.Outbox;
using NServiceBus.Persistence;
using NServiceBus.Transport;
class StorageAdapter : ISynchronizedStorageAdapter
{
static Task<CompletableSynchronizedStorageSession> EmptyResultTask = Task.FromResult(default(CompletableSynchronizedStorageSession));
SagaInfoCache infoCache;
Func<DbConnection> connectionBuilder;
public StorageAdapter(Func<DbConnection> connectionBuilder, SagaInfoCache infoCache)
{
this.connectionBuilder = connectionBuilder;
this.infoCache = infoCache;
}
public Task<CompletableSynchronizedStorageSession> TryAdapt(OutboxTransaction transaction, ContextBag context)
{
var outboxTransaction = transaction as SqlOutboxTransaction;
if (outboxTransaction == null)
{
return EmptyResultTask;
}
CompletableSynchronizedStorageSession session = new StorageSession(outboxTransaction.Connection, outboxTransaction.Transaction, false, infoCache);
return Task.FromResult(session);
}
public async Task<CompletableSynchronizedStorageSession> TryAdapt(TransportTransaction transportTransaction, ContextBag context)
{
SqlConnection existingSqlConnection;
SqlTransaction existingSqlTransaction;
//SQL server transport in native TX mode
if (transportTransaction.TryGet(out existingSqlConnection) &&
transportTransaction.TryGet(out existingSqlTransaction))
{
return new StorageSession(existingSqlConnection, existingSqlTransaction, false, infoCache);
}
// Transport supports DTC and uses TxScope owned by the transport
Transaction transportTx;
var scopeTx = Transaction.Current;
if (transportTransaction.TryGet(out transportTx) &&
scopeTx != null &&
transportTx != scopeTx)
{
throw new Exception("A TransactionScope has been opened in the current context overriding the one created by the transport. "
+ "This setup can result in inconsistent data because operations done via connections enlisted in the context scope won't be committed "
+ "atomically with the receive transaction. To manually control the TransactionScope in the pipeline switch the transport transaction mode "
+ $"to values lower than '{nameof(TransportTransactionMode.TransactionScope)}'.");
}
var ambientTransaction = transportTx ?? scopeTx;
if (ambientTransaction != null)
{
var connection = await connectionBuilder.OpenConnection();
connection.EnlistTransaction(ambientTransaction);
return new StorageSession(connection, null, true, infoCache);
}
//Other modes handled by creating a new session.
return null;
}
} | using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Transactions;
using NServiceBus;
using NServiceBus.Extensibility;
using NServiceBus.Outbox;
using NServiceBus.Persistence;
using NServiceBus.Transport;
class StorageAdapter : ISynchronizedStorageAdapter
{
static Task<CompletableSynchronizedStorageSession> EmptyResultTask = Task.FromResult(default(CompletableSynchronizedStorageSession));
SagaInfoCache infoCache;
Func<DbConnection> connectionBuilder;
public StorageAdapter(Func<DbConnection> connectionBuilder, SagaInfoCache infoCache)
{
this.connectionBuilder = connectionBuilder;
this.infoCache = infoCache;
}
public Task<CompletableSynchronizedStorageSession> TryAdapt(OutboxTransaction transaction, ContextBag context)
{
var outboxTransaction = transaction as SqlOutboxTransaction;
if (outboxTransaction == null)
{
return EmptyResultTask;
}
CompletableSynchronizedStorageSession session = new StorageSession(outboxTransaction.Connection, outboxTransaction.Transaction, false, infoCache);
return Task.FromResult(session);
}
public async Task<CompletableSynchronizedStorageSession> TryAdapt(TransportTransaction transportTransaction, ContextBag context)
{
SqlConnection existingSqlConnection;
SqlTransaction existingSqlTransaction;
//SQL server transport in native TX mode
if (transportTransaction.TryGet(out existingSqlConnection) && transportTransaction.TryGet(out existingSqlTransaction))
{
return new StorageSession(existingSqlConnection, existingSqlTransaction, false, infoCache);
}
// Transport supports DTC and uses TxScope owned by the transport
Transaction transportTx;
var scopeTx = Transaction.Current;
if (transportTransaction.TryGet(out transportTx) && scopeTx != null && !transportTx.Equals(scopeTx))
{
throw new Exception("A TransactionScope has been opened in the current context overriding the one created by the transport. "
+ "This setup can result in inconsistent data because operations done via connections enlisted in the context scope won't be committed "
+ "atomically with the receive transaction. To manually control the TransactionScope in the pipeline switch the transport transaction mode "
+ $"to values lower than '{nameof(TransportTransactionMode.TransactionScope)}'.");
}
var ambientTransaction = transportTx ?? scopeTx;
if (ambientTransaction != null)
{
var connection = await connectionBuilder.OpenConnection();
connection.EnlistTransaction(ambientTransaction);
return new StorageSession(connection, null, true, infoCache);
}
//Other modes handled by creating a new session.
return null;
}
} | mit | C# |
f194d693d6e9b7d1a3c77be5dc93e386b8bd9ed7 | add comment for empty method required to implement interface | fluffynuts/PeanutButter,fluffynuts/PeanutButter,fluffynuts/PeanutButter | source/Utils/PeanutButter.DuckTyping/Extensions/DictionaryWrappingNameValueCollectionEnumerator.cs | source/Utils/PeanutButter.DuckTyping/Extensions/DictionaryWrappingNameValueCollectionEnumerator.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace PeanutButter.DuckTyping.Extensions
{
// TODO: add expllicit tests around this class, which is currently only tested by indirection
/// <summary>
/// Wraps a NameValueCollection in a Dictionary interface
/// </summary>
internal class DictionaryWrappingNameValueCollectionEnumerator : IEnumerator<KeyValuePair<string, object>>
{
internal DictionaryWrappingNameValueCollection Data => _data;
private readonly DictionaryWrappingNameValueCollection _data;
private string[] _keys;
private int _current;
/// <summary>
/// Provides an IEnumerator for a DictionaryWrappingNameValueCollection
/// </summary>
/// <param name="data"></param>
public DictionaryWrappingNameValueCollectionEnumerator(
DictionaryWrappingNameValueCollection data
)
{
_data = data;
Reset();
}
/// <inheritdoc />
public void Dispose()
{
/* empty on purpose, just need to implement IEnumerator */
}
/// <inheritdoc />
public bool MoveNext()
{
RefreshKeys();
_current++;
return _current < _keys.Length;
}
/// <inheritdoc />
public void Reset()
{
_current = -1;
_keys = new string[] { };
}
public KeyValuePair<string, object> Current
{
get
{
RefreshKeys();
if (_current >= _keys.Length)
throw new InvalidOperationException("Current index is out of bounds");
return new KeyValuePair<string, object>(_keys[_current], _data[_keys[_current]]);
}
}
private void RefreshKeys()
{
if (!_keys.Any())
_keys = _data.Keys.ToArray();
}
object IEnumerator.Current => Current;
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace PeanutButter.DuckTyping.Extensions
{
// TODO: add expllicit tests around this class, which is currently only tested by indirection
/// <summary>
/// Wraps a NameValueCollection in a Dictionary interface
/// </summary>
internal class DictionaryWrappingNameValueCollectionEnumerator : IEnumerator<KeyValuePair<string, object>>
{
internal DictionaryWrappingNameValueCollection Data => _data;
private readonly DictionaryWrappingNameValueCollection _data;
private string[] _keys;
private int _current;
/// <summary>
/// Provides an IEnumerator for a DictionaryWrappingNameValueCollection
/// </summary>
/// <param name="data"></param>
public DictionaryWrappingNameValueCollectionEnumerator(
DictionaryWrappingNameValueCollection data
)
{
_data = data;
Reset();
}
/// <inheritdoc />
public void Dispose()
{
}
/// <inheritdoc />
public bool MoveNext()
{
RefreshKeys();
_current++;
return _current < _keys.Length;
}
/// <inheritdoc />
public void Reset()
{
_current = -1;
_keys = new string[] { };
}
public KeyValuePair<string, object> Current
{
get
{
RefreshKeys();
if (_current >= _keys.Length)
throw new InvalidOperationException("Current index is out of bounds");
return new KeyValuePair<string, object>(_keys[_current], _data[_keys[_current]]);
}
}
private void RefreshKeys()
{
if (!_keys.Any())
_keys = _data.Keys.ToArray();
}
object IEnumerator.Current => Current;
}
} | bsd-3-clause | C# |
8fba75eeb36ba4e1ce18fe7dfc549133ae8e1f73 | Add a few compile time features to calling a field on a string literal... - Crash at COMPILE TIME if you call .join and explain that the string joiner is done by calling .join on a list with a string as an argument. - Crash at COMPILE TIME when you call .size and redirect the user to .length - Swap out string.length with the actual length when the string is an inline constant. | blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon | csharp/Crayon/ParseTree/DotStep.cs | csharp/Crayon/ParseTree/DotStep.cs | using System.Linq;
namespace Crayon.ParseTree
{
internal class DotStep : Expression
{
public Expression Root { get; set; }
public Token DotToken { get; private set; }
public Token StepToken { get; private set; }
public DotStep(Expression root, Token dotToken, Token stepToken)
: base(root.FirstToken)
{
this.Root = root;
this.DotToken = dotToken;
this.StepToken = stepToken;
}
public override Expression Resolve(Parser parser)
{
this.Root = this.Root.Resolve(parser);
string step = this.StepToken.Value;
Variable variable = this.Root as Variable;
if (variable != null)
{
string varName = variable.Name;
EnumDefinition enumDef = parser.GetEnumDefinition(varName);
if (enumDef != null)
{
if (enumDef.IntValue.ContainsKey(step))
{
return new IntegerConstant(this.FirstToken, enumDef.IntValue[step]);
}
throw new ParserException(this.StepToken, "The enum '" + variable.Name + "' does not contain a definition for '" + step + "'");
}
if (parser.IsTranslateMode && varName.Contains('$'))
{
string[] parts = varName.Split('$');
if (parts.Length == 2 && parts[0].Length > 0 && parts[1].Length > 0)
{
// struct casting
string structName = parts[0];
string realVarName = parts[1];
StructDefinition structDef = parser.GetStructDefinition(structName);
if (!structDef.IndexByField.ContainsKey(step))
{
throw new ParserException(this.StepToken, "The struct '" + structDef.Name.Value + "' does not contain a field called '" + step + "'");
}
return new DotStepStruct(this.FirstToken, structDef, this);
}
}
}
if (this.Root is StringConstant)
{
if (step == "join")
{
throw new ParserException(this.StepToken,
"There is no join method on strings, you silly Python user. Did you mean to do list.join(string) instead?");
}
else if (step == "size")
{
throw new ParserException(this.StepToken, "String size is indicated by string.length.");
}
else if (step == "length")
{
int length = ((StringConstant)this.Root).Value.Length;
return new IntegerConstant(this.FirstToken, length);
}
}
return this;
}
}
}
| using System.Linq;
namespace Crayon.ParseTree
{
internal class DotStep : Expression
{
public Expression Root { get; set; }
public Token DotToken { get; private set; }
public Token StepToken { get; private set; }
public DotStep(Expression root, Token dotToken, Token stepToken)
: base(root.FirstToken)
{
this.Root = root;
this.DotToken = dotToken;
this.StepToken = stepToken;
}
public override Expression Resolve(Parser parser)
{
this.Root = this.Root.Resolve(parser);
string step = this.StepToken.Value;
Variable variable = this.Root as Variable;
if (variable != null)
{
string varName = variable.Name;
EnumDefinition enumDef = parser.GetEnumDefinition(varName);
if (enumDef != null)
{
if (enumDef.IntValue.ContainsKey(step))
{
return new IntegerConstant(this.FirstToken, enumDef.IntValue[step]);
}
throw new ParserException(this.StepToken, "The enum '" + variable.Name + "' does not contain a definition for '" + step + "'");
}
if (parser.IsTranslateMode && varName.Contains('$'))
{
string[] parts = varName.Split('$');
if (parts.Length == 2 && parts[0].Length > 0 && parts[1].Length > 0)
{
// struct casting
string structName = parts[0];
string realVarName = parts[1];
StructDefinition structDef = parser.GetStructDefinition(structName);
if (!structDef.IndexByField.ContainsKey(step))
{
throw new ParserException(this.StepToken, "The struct '" + structDef.Name.Value + "' does not contain a field called '" + step + "'");
}
return new DotStepStruct(this.FirstToken, structDef, this);
}
}
}
return this;
}
}
}
| mit | C# |
8735897526b4fee856a089f13afd0c48ca78c5d4 | Remove XML formatter | thack/CodeForAmerica,thack/CodeForAmerica | 2013February/ApiProxy/API/App_Start/WebApiConfig.cs | 2013February/ApiProxy/API/App_Start/WebApiConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// use json as default, remove xml formatter http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
}
}
| mit | C# |
b18f5b0562da4d179ca191d7ce5aa065bd23c742 | Declare storage permission at assembly level | ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework.Android/Properties/AssemblyInfo.cs | osu.Framework.Android/Properties/AssemblyInfo.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.Runtime.CompilerServices;
using Android.App;
// We publish our internal attributes to other sub-projects of the framework.
// Note, that we omit visual tests as they are meant to test the framework
// behavior "in the wild".
[assembly: InternalsVisibleTo("osu.Framework.Tests")]
[assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")]
// https://docs.microsoft.com/en-us/answers/questions/182601/does-xamarinandroid-suppor-manifest-merging.html
[assembly: UsesPermission(Android.Manifest.Permission.ReadExternalStorage)]
| // 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.Runtime.CompilerServices;
// We publish our internal attributes to other sub-projects of the framework.
// Note, that we omit visual tests as they are meant to test the framework
// behavior "in the wild".
[assembly: InternalsVisibleTo("osu.Framework.Tests")]
[assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")]
| mit | C# |
434d7d1809d1c72436fa41aeb15088522bb030de | Replace piecewise linear function + rebalance | ppy/osu,2yangk23/osu,DrabWeb/osu,smoogipoo/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,2yangk23/osu,DrabWeb/osu,EVAST9919/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,ppy/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu,naoey/osu,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ZLima12/osu,peppy/osu-new,naoey/osu,peppy/osu,ZLima12/osu | osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs | osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Rulesets.Osu.Difficulty.Preprocessing;
using osuTK;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
/// </summary>
public class Speed : Skill
{
private const double min_angle_bonus = 1.0;
private const double max_angle_bonus = 1.25;
private const double angle_bonus_begin = 3 * Math.PI / 4;
private const double pi_over_4 = Math.PI / 4;
protected override double SkillMultiplier => 1400;
protected override double StrainDecayBase => 0.3;
private const double min_speed_bonus = 75; // ~200BPM
private const double max_speed_bonus = 45; // ~330BPM
private const double speed_balancing_factor = 40;
protected override double StrainValueOf(OsuDifficultyHitObject current)
{
double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance);
double deltaTime = Math.Max(max_speed_bonus, current.DeltaTime);
double speedBonus = 1.0;
if (deltaTime < min_speed_bonus)
speedBonus = 1 + Math.Pow((min_speed_bonus - deltaTime) / speed_balancing_factor, 2);
double angleBonus = 1.0;
if (current.Angle != null)
angleBonus = MathHelper.Clamp((angle_bonus_begin - current.Angle.Value) / pi_over_4 * 0.5 + 1.0, min_angle_bonus, max_angle_bonus);
return angleBonus * (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Rulesets.Osu.Difficulty.Preprocessing;
using osuTK;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
/// </summary>
public class Speed : Skill
{
private const double min_angle_bonus = 1.0;
private const double max_angle_bonus = 1.25;
private const double angle_bonus_begin = 3 * Math.PI / 4;
private const double pi_over_4 = Math.PI / 4;
protected override double SkillMultiplier => 1400;
protected override double StrainDecayBase => 0.3;
private const double min_speed_bonus = 75; // ~200BPM
private const double max_speed_bonus = 45; // ~330BPM
private const double speed_balancing_factor = 40;
protected override double StrainValueOf(OsuDifficultyHitObject current)
{
double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance);
double deltaTime = Math.Max(max_speed_bonus, current.DeltaTime);
double speedBonus = 1.0;
if (deltaTime < min_speed_bonus)
speedBonus = 1 + Math.Pow((min_speed_bonus - deltaTime) / speed_balancing_factor, 2);
double angleBonus = 1.0;
if (current.Angle != null)
angleBonus = MathHelper.Clamp((angle_bonus_begin - current.Angle.Value) / pi_over_4 * 0.25 + 1.0, min_angle_bonus, max_angle_bonus);
return angleBonus * (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
}
}
}
| mit | C# |
06cde2b0c22feca53459df4213f46eb82ca6d0c1 | remove unused using directive | UselessToucan/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,2yangk23/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,johnneijzen/osu | osu.Game.Rulesets.Osu/Skinning/LegacyCursor.cs | osu.Game.Rulesets.Osu/Skinning/LegacyCursor.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.Allocation;
using osu.Framework.Graphics;
using osu.Game.Skinning;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osuTK;
namespace osu.Game.Rulesets.Osu.Skinning
{
public class LegacyCursor : OsuCursorSprite
{
private bool spin;
public LegacyCursor()
{
Size = new Vector2(50);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
spin = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.CursorRotate)?.Value ?? true;
InternalChildren = new Drawable[]
{
new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursormiddle"),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
ExpandTarget = new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursor"),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
};
}
protected override void LoadComplete()
{
if (spin)
ExpandTarget.Spin(10000, RotationDirection.Clockwise);
}
}
}
| // 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Skinning;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osuTK;
namespace osu.Game.Rulesets.Osu.Skinning
{
public class LegacyCursor : OsuCursorSprite
{
private bool spin;
public LegacyCursor()
{
Size = new Vector2(50);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
spin = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.CursorRotate)?.Value ?? true;
InternalChildren = new Drawable[]
{
new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursormiddle"),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
ExpandTarget = new NonPlayfieldSprite
{
Texture = skin.GetTexture("cursor"),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
};
}
protected override void LoadComplete()
{
if (spin)
ExpandTarget.Spin(10000, RotationDirection.Clockwise);
}
}
}
| mit | C# |
0e1236b0f1e40cbc3cdf37ffd9fc7584ef4a4154 | Update Viktor.cs | FireBuddy/adevade | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
var endpoint = sender.Path.Last();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
var endpoint = sender.Path;
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| mit | C# |
e0d9f1bc2e87e3aab94b215e3d7c8dcf3eedf0e9 | Add rank to evals list | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Evaluations/List.cshtml | Battery-Commander.Web/Views/Evaluations/List.cshtml | @model IEnumerable<Evaluation>
<h2>Evaluations @Html.ActionLink("Add New", "New", "Evaluations", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Ratee.Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Ratee)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().ThruDate)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Delinquency)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastUpdated)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rater)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().SeniorRater)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var evaluation in Model)
{
<tr>
<td>@Html.DisplayFor(_ => evaluation.Ratee.Rank)</td>
<td>@Html.DisplayFor(_ => evaluation.Ratee)</td>
<td>@Html.DisplayFor(_ => evaluation.ThruDate)</td>
<td>@Html.DisplayFor(_ => evaluation.Status)</td>
<td>@Html.DisplayFor(_ => evaluation.Delinquency)</td>
<td>@Html.DisplayFor(_ => evaluation.LastUpdated)</td>
<td>@Html.DisplayFor(_ => evaluation.Type)</td>
<td>@Html.DisplayFor(_ => evaluation.Rater)</td>
<td>@Html.DisplayFor(_ => evaluation.SeniorRater)</td>
<td>@Html.ActionLink("Details", "Details", new { evaluation.Id })</td>
</tr>
}
</tbody>
</table> | @model IEnumerable<Evaluation>
<h2>Evaluations @Html.ActionLink("Add New", "New", "Evaluations", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Ratee)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().ThruDate)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Delinquency)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastUpdated)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rater)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().SeniorRater)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var evaluation in Model)
{
<tr>
<td>@Html.DisplayFor(_ => evaluation.Ratee)</td>
<td>@Html.DisplayFor(_ => evaluation.ThruDate)</td>
<td>@Html.DisplayFor(_ => evaluation.Status)</td>
<td>@Html.DisplayFor(_ => evaluation.Delinquency)</td>
<td>@Html.DisplayFor(_ => evaluation.LastUpdated)</td>
<td>@Html.DisplayFor(_ => evaluation.Type)</td>
<td>@Html.DisplayFor(_ => evaluation.Rater)</td>
<td>@Html.DisplayFor(_ => evaluation.SeniorRater)</td>
<td>@Html.ActionLink("Details", "Details", new { evaluation.Id })</td>
</tr>
}
</tbody>
</table> | mit | C# |
9fc3556cf879b05415280132ecd19ba5a6234596 | Add some more tests. | srivatsn/MSBuildSdkDiffer | MSBuildSdkDiffer.Tests/PropertiesDiffTests.cs | MSBuildSdkDiffer.Tests/PropertiesDiffTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSBuildSdkDiffer.Tests.Mocks;
using Xunit;
namespace MSBuildSdkDiffer.Tests
{
public class PropertiesDiffTests
{
[Theory]
[InlineData("A=B", "A", "A=B", "A", null, null)]
[InlineData("A=B", "A", "D=E", null, "A", null)]
[InlineData("A=B;C=D", "A", "C=D", null, "A", null)]
[InlineData("A=B;C=D", "A", "A=C", null, null, "A")]
[InlineData("A=B;C=D", "A;C", "C=E", null, "A", "C")]
[InlineData("A=B;C=D;E=F", "A;C;E", "C=E;E=F", "E", "A", "C")]
public void PropertiesDiff_GetLines(string projectProps, string propsInFile, string sdkBaselineProps, string expectedDefaultedProps, string expectedNotDefaultedProps, string expectedChangedProps)
{
var project = IProjectFactory.Create(projectProps);
var sdkBaselineProject = IProjectFactory.Create(sdkBaselineProps);
var differ = new Differ(project, propsInFile.Split(';'), sdkBaselineProject);
var diff = differ.GetPropertiesDiff();
if (expectedDefaultedProps == null)
{
Assert.Empty(diff.DefaultedProperties);
}
else
{
Assert.Equal(diff.DefaultedProperties.Select(p=> p.Name), expectedDefaultedProps.Split(';'));
}
if (expectedNotDefaultedProps == null)
{
Assert.Empty(diff.NotDefaultedProperties);
}
else
{
Assert.Equal(diff.NotDefaultedProperties.Select(p => p.Name), expectedNotDefaultedProps.Split(';'));
}
if (expectedChangedProps == null)
{
Assert.Empty(diff.ChangedProperties);
}
else
{
Assert.Equal(diff.ChangedProperties.Select(p => p.oldProp.Name), expectedChangedProps.Split(';'));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSBuildSdkDiffer.Tests.Mocks;
using Xunit;
namespace MSBuildSdkDiffer.Tests
{
public class PropertiesDiffTests
{
[Theory]
[InlineData("A=B", "A", "A=B", "A", null, null)]
[InlineData("A=B", "A", "D=E", null, "A", null)]
public void PropertiesDiff_GetLines(string projectProps, string propsInFile, string sdkBaselineProps, string expectedDefaultedProps, string expectedNotDefaultedProps, string expectedChangedProps)
{
var project = IProjectFactory.Create(projectProps);
var sdkBaselineProject = IProjectFactory.Create(sdkBaselineProps);
var differ = new Differ(project, propsInFile.Split(';'), sdkBaselineProject);
var diff = differ.GetPropertiesDiff();
if (expectedDefaultedProps == null)
{
Assert.Empty(diff.DefaultedProperties);
}
else
{
Assert.Equal(diff.DefaultedProperties.Select(p=> p.Name), expectedDefaultedProps.Split(';'));
}
if (expectedNotDefaultedProps == null)
{
Assert.Empty(diff.NotDefaultedProperties);
}
else
{
Assert.Equal(diff.NotDefaultedProperties.Select(p => p.Name), expectedNotDefaultedProps.Split(';'));
}
if (expectedChangedProps == null)
{
Assert.Empty(diff.ChangedProperties);
}
else
{
Assert.Equal(diff.ChangedProperties.Select(p => p.oldProp.Name), expectedChangedProps.Split(';'));
}
}
}
}
| mit | C# |
546e9f7b2ada33a3b68bc74440c4aa631e37345c | Fix mistake in registration (method not on interface) | csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay | CSF.Screenplay/Scenarios/IServiceRegistryBuilder.cs | CSF.Screenplay/Scenarios/IServiceRegistryBuilder.cs | using System;
namespace CSF.Screenplay.Scenarios
{
/// <summary>
/// Builder service which assists in the creation of service registrations.
/// </summary>
public interface IServiceRegistryBuilder
{
/// <summary>
/// Registers a service which will be used across all scenarios within a test run.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterSingleton<TService>(TService instance, string name = null) where TService : class;
/// <summary>
/// Registers a service which will be used across all scenarios within a test run.
/// </summary>
/// <param name="initialiser">Initialiser.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterSingleton<TService>(Func<TService> initialiser, string name = null) where TService : class;
/// <summary>
/// Registers a service which will be constructed afresh (using the given factory function) for
/// each scenario within a test run.
/// </summary>
/// <param name="factory">Factory.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterPerScenario<TService>(Func<IServiceResolver,TService> factory, string name = null) where TService : class;
}
}
| using System;
namespace CSF.Screenplay.Scenarios
{
/// <summary>
/// Builder service which assists in the creation of service registrations.
/// </summary>
public interface IServiceRegistryBuilder
{
/// <summary>
/// Registers a service which will be used across all scenarios within a test run.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterSingleton<TService>(TService instance, string name = null) where TService : class;
/// <summary>
/// Registers a service which will be constructed afresh (using the given factory function) for
/// each scenario within a test run.
/// </summary>
/// <param name="factory">Factory.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterPerScenario<TService>(Func<IServiceResolver,TService> factory, string name = null) where TService : class;
}
}
| mit | C# |
e29d78a8a56df7663232e56e2ce025445bcdb759 | Hide getters from NodeMethods | mcintyre321/Noodles,mcintyre321/Noodles | Noodles/NodeMethodExtensions.cs | Noodles/NodeMethodExtensions.cs | using System.Collections.Generic;
using System.Linq;
using Noodles.Models;
using Noodles.Requests;
namespace Noodles
{
public static class NodeMethodExtensions
{
public static IEnumerable<NodeMethod> NodeMethods(this object o, Resource resource)
{
return NodeMethodsReflectionLogic.YieldFindNodeMethodsUsingReflection(o, resource)
.Where(nm => !nm.Name.StartsWith("set_")).Where(nm => !nm.Name.StartsWith("get_"));
}
public static NodeMethod NodeMethod(this object o, string methodName, Resource resource)
{
return o.NodeMethods(resource).SingleOrDefault(m => m.Name.ToLowerInvariant() == methodName.ToLowerInvariant());
}
public static IEnumerable<IInvokeable> Actions(this object obj, Resource resource)
{
return obj.NodeMethods(resource).Cast<IInvokeable>()
.Concat(obj.NodeProperties(resource).Where(p => !p.Readonly).Select(p => p.Setter));
}
}
} | using System.Collections.Generic;
using System.Linq;
using Noodles.Models;
using Noodles.Requests;
namespace Noodles
{
public static class NodeMethodExtensions
{
public static IEnumerable<NodeMethod> NodeMethods(this object o, Resource resource)
{
return NodeMethodsReflectionLogic.YieldFindNodeMethodsUsingReflection(o, resource)
.Where(nm => !nm.Name.StartsWith("set_"));
}
public static NodeMethod NodeMethod(this object o, string methodName, Resource resource)
{
return o.NodeMethods(resource).SingleOrDefault(m => m.Name.ToLowerInvariant() == methodName.ToLowerInvariant());
}
public static IEnumerable<IInvokeable> Actions(this object obj, Resource resource)
{
return obj.NodeMethods(resource).Cast<IInvokeable>()
.Concat(obj.NodeProperties(resource).Where(p => !p.Readonly).Select(p => p.Setter));
}
}
} | mit | C# |
14ab71003ce6325d43adcd2133100cefc8d422f8 | Upgrade OData WebAPI Version to 5.6.0 | lungisam/WebApi,chimpinano/WebApi,abkmr/WebApi,congysu/WebApi,scz2011/WebApi,chimpinano/WebApi,lewischeng-ms/WebApi,yonglehou/WebApi,scz2011/WebApi,LianwMS/WebApi,congysu/WebApi,lungisam/WebApi,lewischeng-ms/WebApi,abkmr/WebApi,yonglehou/WebApi,LianwMS/WebApi | OData/src/CommonAssemblyInfo.cs | OData/src/CommonAssemblyInfo.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.6.0.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.6.0.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.5.2.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.5.2.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif | mit | C# |
2e7d8eaeaf3bbf7244c6668d43446e5a10f926b1 | Make base abstract | dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan | Snittlistan/Controllers/AbstractController.cs | Snittlistan/Controllers/AbstractController.cs | using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Elmah;
using Raven.Client;
using Snittlistan.Models;
namespace Snittlistan.Controllers
{
public abstract class AbstractController : Controller
{
/// <summary>
/// Initializes a new instance of the AbstractController class.
/// </summary>
public AbstractController()
{ }
/// <summary>
/// Initializes a new instance of the AbstractController class.
/// </summary>
/// <param name="session">Document session.</param>
public AbstractController(IDocumentSession session)
{
Session = session;
}
/// <summary>
/// Gets the document session.
/// </summary>
public new IDocumentSession Session { get; private set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// make sure there's an admin user
if (Session.Load<User>("Admin") == null)
{
// first launch
Response.Redirect("/welcome");
Response.End();
}
}
}
} | using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Elmah;
using Raven.Client;
using Snittlistan.Models;
namespace Snittlistan.Controllers
{
public class AbstractController : Controller
{
/// <summary>
/// Initializes a new instance of the AbstractController class.
/// </summary>
public AbstractController()
{ }
/// <summary>
/// Initializes a new instance of the AbstractController class.
/// </summary>
/// <param name="session">Document session.</param>
public AbstractController(IDocumentSession session)
{
Session = session;
}
/// <summary>
/// Gets the document session.
/// </summary>
public new IDocumentSession Session { get; private set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// make sure there's an admin user
if (Session.Load<User>("Admin") == null)
{
// first launch
Response.Redirect("/welcome");
Response.End();
}
}
}
} | mit | C# |
746150f276cca81e06d067aa1db20be89af1ebb4 | implement LocalConfigurationFeature.ConfigurationFileIsNull | config-r/config-r | src/ConfigR.Roslyn.CSharp/Internal/StringExtensions.cs | src/ConfigR.Roslyn.CSharp/Internal/StringExtensions.cs | // <copyright file="StringExtensions.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. ([email protected])
// </copyright>
namespace ConfigR.Roslyn.CSharp.Internal
{
using System;
using System.IO;
using ConfigR.Sdk;
public static class StringExtensions
{
public static string ResolveScriptPath(this string scriptPath)
{
scriptPath = scriptPath ??
Path.ChangeExtension(AppDomain.CurrentDomain.SetupInformation.VSHostingAgnosticConfigurationFile(), "csx");
if (scriptPath == null)
{
throw new InvalidOperationException("AppDomain.CurrentDomain.SetupInformation.ConfigurationFile is null.");
}
return Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, scriptPath);
}
}
}
| // <copyright file="StringExtensions.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. ([email protected])
// </copyright>
namespace ConfigR.Roslyn.CSharp.Internal
{
using System;
using System.IO;
using ConfigR.Sdk;
public static class StringExtensions
{
public static string ResolveScriptPath(this string scriptPath)
{
scriptPath = scriptPath ??
Path.ChangeExtension(AppDomain.CurrentDomain.SetupInformation.VSHostingAgnosticConfigurationFile(), "csx");
return Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, scriptPath);
}
}
}
| mit | C# |
9fb471c5daf7d7213f2f5929a438997c6cf23f7a | add more tests | gaochundong/Redola | Tests/Redola.Rpc.TestHttpServer/TestModule.cs | Tests/Redola.Rpc.TestHttpServer/TestModule.cs | using System;
using Happer.Http;
namespace Redola.Rpc.TestHttpServer
{
public class TestModule : Module
{
private HelloClient _helloService;
public TestModule(HelloClient helloService)
{
_helloService = helloService;
Get["/empty"] = x =>
{
return string.Empty;
};
Get["/time"] = x =>
{
return DateTime.Now.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff");
};
Get["/hello"] = x =>
{
var response = _helloService.SayHello();
return response == null ? string.Empty : response.Message.Text;
};
}
}
}
| using Happer.Http;
namespace Redola.Rpc.TestHttpServer
{
public class TestModule : Module
{
private HelloClient _helloService;
public TestModule(HelloClient helloService)
{
_helloService = helloService;
Get["/hello"] = x =>
{
var response = _helloService.SayHello();
return response == null ? string.Empty : response.Message.Text;
};
}
}
}
| mit | C# |
23ea01b37326963b5ebf68bbcc1edd51c66a28d6 | Fix ctor, we must use initWithCoder when loading from a storyboard | a9upam/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,albertoms/monotouch-samples,robinlaide/monotouch-samples,kingyond/monotouch-samples,xamarin/monotouch-samples,a9upam/monotouch-samples,sakthivelnagarajan/monotouch-samples,sakthivelnagarajan/monotouch-samples,xamarin/monotouch-samples,nelzomal/monotouch-samples,labdogg1003/monotouch-samples,hongnguyenpro/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,peteryule/monotouch-samples,peteryule/monotouch-samples,nelzomal/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,robinlaide/monotouch-samples,kingyond/monotouch-samples,robinlaide/monotouch-samples,albertoms/monotouch-samples,a9upam/monotouch-samples,markradacz/monotouch-samples,hongnguyenpro/monotouch-samples,markradacz/monotouch-samples,nervevau2/monotouch-samples,nervevau2/monotouch-samples,haithemaraissia/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,iFreedive/monotouch-samples,W3SS/monotouch-samples,davidrynn/monotouch-samples,kingyond/monotouch-samples,davidrynn/monotouch-samples,labdogg1003/monotouch-samples,W3SS/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,hongnguyenpro/monotouch-samples,nervevau2/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,haithemaraissia/monotouch-samples,peteryule/monotouch-samples,iFreedive/monotouch-samples,robinlaide/monotouch-samples,iFreedive/monotouch-samples,andypaul/monotouch-samples,W3SS/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,albertoms/monotouch-samples,haithemaraissia/monotouch-samples,andypaul/monotouch-samples | TextKitDemo/TextKitDemo/CollectionViewCell.cs | TextKitDemo/TextKitDemo/CollectionViewCell.cs | using System;
using CoreGraphics;
using Foundation;
using UIKit;
namespace TextKitDemo
{
public partial class CollectionViewCell : UICollectionViewCell
{
public CollectionViewCell (IntPtr handle) : base (handle)
{
Initialize ();
}
[Export ("initWithCoder:")]
public CollectionViewCell (NSCoder coder) : base (coder)
{
Initialize ();
}
void Initialize ()
{
BackgroundColor = UIColor.DarkGray;
Layer.CornerRadius = 5;
UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate {
CalculateAndSetFonts ();
});
}
public void FormatCell (DemoModel demo)
{
containerView.Layer.CornerRadius = 2;
labelView.Text = demo.Title;
textView.AttributedText = demo.GetAttributedText ();
CalculateAndSetFonts ();
}
void CalculateAndSetFonts ()
{
const float cellTitleTextScaleFactor = 0.85f;
const float cellBodyTextScaleFactor = 0.7f;
UIFont cellTitleFont = Font.GetPreferredFont (labelView.Font.FontDescriptor.TextStyle, cellTitleTextScaleFactor);
UIFont cellBodyFont = Font.GetPreferredFont (textView.Font.FontDescriptor.TextStyle, cellBodyTextScaleFactor);
labelView.Font = cellTitleFont;
textView.Font = cellBodyFont;
}
}
}
| using System;
using CoreGraphics;
using Foundation;
using UIKit;
namespace TextKitDemo
{
public partial class CollectionViewCell : UICollectionViewCell
{
public CollectionViewCell (IntPtr handle) : base (handle)
{
BackgroundColor = UIColor.DarkGray;
Layer.CornerRadius = 5;
UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate {
CalculateAndSetFonts ();
});
}
public void FormatCell (DemoModel demo)
{
containerView.Layer.CornerRadius = 2;
labelView.Text = demo.Title;
textView.AttributedText = demo.GetAttributedText ();
CalculateAndSetFonts ();
}
void CalculateAndSetFonts ()
{
const float cellTitleTextScaleFactor = 0.85f;
const float cellBodyTextScaleFactor = 0.7f;
UIFont cellTitleFont = Font.GetPreferredFont (labelView.Font.FontDescriptor.TextStyle, cellTitleTextScaleFactor);
UIFont cellBodyFont = Font.GetPreferredFont (textView.Font.FontDescriptor.TextStyle, cellBodyTextScaleFactor);
labelView.Font = cellTitleFont;
textView.Font = cellBodyFont;
}
}
}
| mit | C# |
ad0cee99433b0451903a7445e0e9a6ba7462cf6e | add Host in TracingAnnotationNames | vostok/core | Vostok.Core/Tracing/TracingAnnotationNames.cs | Vostok.Core/Tracing/TracingAnnotationNames.cs | namespace Vostok.Tracing
{
public static class TracingAnnotationNames
{
public const string Operation = "operation";
public const string Service = "service";
public const string Component = "component";
public const string Kind = "kind";
public const string Host = "host";
public const string ClusterStrategy = "cluster.strategy";
public const string ClusterStatus = "cluster.status";
public const string HttpUrl = "http.url";
public const string HttpCode = "http.code";
public const string HttpMethod = "http.method";
public const string HttpRequestContentLength = "http.requestContentLength";
public const string HttpResponseContentLength = "http.responseContentLength";
}
} | namespace Vostok.Tracing
{
public static class TracingAnnotationNames
{
public const string Operation = "operation";
public const string Service = "service";
public const string Component = "component";
public const string Kind = "kind";
public const string ClusterStrategy = "cluster.strategy";
public const string ClusterStatus = "cluster.status";
public const string HttpUrl = "http.url";
public const string HttpCode = "http.code";
public const string HttpMethod = "http.method";
public const string HttpRequestContentLength = "http.requestContentLength";
public const string HttpResponseContentLength = "http.responseContentLength";
}
} | mit | C# |
2a2ac31e08213726703be7580ba462646a94e51f | Update "Shelf" | DRFP/Personal-Library | _Build/PersonalLibrary/Library/Model/Shelf.cs | _Build/PersonalLibrary/Library/Model/Shelf.cs | using SQLite;
namespace Library.Model {
[Table("Shelves")]
public class Shelf {
[PrimaryKey, AutoIncrement]
public int slfID { get; set; }
public string slfName { get; set; }
}
} | using SQLite;
namespace Library.Model {
[Table("Shelves")]
public class Shelf {
[PrimaryKey, AutoIncrement]
public int slfID { get; set; }
public string slfName { get; set; }
}
} | mit | C# |
855769f582524bc656cdf658dd2c4cc675e1e0c2 | fix FacadeMethod for overloaded method names | AlejandroCano/extensions,AlejandroCano/extensions,MehdyKarimpour/extensions,signumsoftware/extensions,signumsoftware/framework,MehdyKarimpour/extensions,signumsoftware/framework,signumsoftware/extensions | Signum.Entities.Extensions/Basics/FacadeMethodDN.cs | Signum.Entities.Extensions/Basics/FacadeMethodDN.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Utilities;
using System.Reflection;
using System.Linq.Expressions;
using System.ServiceModel;
namespace Signum.Entities.Basics
{
[Serializable]
public class FacadeMethodDN : IdentifiableEntity
{
private FacadeMethodDN() { }
public FacadeMethodDN(MethodInfo mi)
{
InterfaceName = mi.DeclaringType.Name;
var oca = mi.SingleAttribute<OperationContractAttribute>();
MethodName = oca.Name ?? mi.Name;
}
[NotNullable, SqlDbType(Size = 100)]
string interfaceName;
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100), AvoidLocalization]
public string InterfaceName
{
get { return interfaceName; }
set { Set(ref interfaceName, value, () => InterfaceName); }
}
[NotNullable, SqlDbType(Size = 100)]
string methodName;
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100), AvoidLocalization]
public string MethodName
{
get { return methodName; }
set { Set(ref methodName, value, () => MethodName); }
}
public override string ToString()
{
return "{0}.{1}".Formato(interfaceName, methodName);
}
static Expression<Func<FacadeMethodDN, MethodInfo, bool>> MatchExpression =
(fm, mi) => mi.DeclaringType.Name == fm.InterfaceName && mi.Name == fm.MethodName;
public bool Match(MethodInfo mi)
{
return MatchExpression.Evaluate(this, mi);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Utilities;
using System.Reflection;
using System.Linq.Expressions;
namespace Signum.Entities.Basics
{
[Serializable]
public class FacadeMethodDN : IdentifiableEntity
{
private FacadeMethodDN() { }
public FacadeMethodDN(MethodInfo mi)
{
InterfaceName = mi.DeclaringType.Name;
MethodName = mi.Name;
}
[NotNullable, SqlDbType(Size = 100)]
string interfaceName;
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100), AvoidLocalization]
public string InterfaceName
{
get { return interfaceName; }
set { Set(ref interfaceName, value, () => InterfaceName); }
}
[NotNullable, SqlDbType(Size = 100)]
string methodName;
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100), AvoidLocalization]
public string MethodName
{
get { return methodName; }
set { Set(ref methodName, value, () => MethodName); }
}
public override string ToString()
{
return "{0}.{1}".Formato(interfaceName, methodName);
}
static Expression<Func<FacadeMethodDN, MethodInfo, bool>> MatchExpression =
(fm, mi) => mi.DeclaringType.Name == fm.InterfaceName && mi.Name == fm.MethodName;
public bool Match(MethodInfo mi)
{
return MatchExpression.Evaluate(this, mi);
}
}
}
| mit | C# |
c2d4f488bdbbe4fa249d5be192d2eaa45ac88a99 | Change to call new API | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts/Commands/UnsubscribeProviderEmail/UnsubscribeProviderEmailQueryHandler.cs | src/SFA.DAS.EmployerAccounts/Commands/UnsubscribeProviderEmail/UnsubscribeProviderEmailQueryHandler.cs | using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail
{
public class UnsubscribeProviderEmailQueryHandler : AsyncRequestHandler<UnsubscribeProviderEmailQuery>
{
private readonly EmployerAccountsConfiguration _configuration;
private readonly IHttpService _httpService;
public UnsubscribeProviderEmailQueryHandler(
IHttpServiceFactory httpServiceFactory,
EmployerAccountsConfiguration configuration)
{
_configuration = configuration;
_httpService = httpServiceFactory.Create(
configuration.ProviderRegistrationsApi.ClientId,
configuration.ProviderRegistrationsApi.ClientSecret,
configuration.ProviderRegistrationsApi.IdentifierUri,
configuration.ProviderRegistrationsApi.Tenant
);
}
protected override async Task HandleCore(UnsubscribeProviderEmailQuery message)
{
var baseUrl = GetBaseUrl();
var url = $"{baseUrl}api/unsubscribe/{message.CorrelationId.ToString()}";
await _httpService.GetAsync(url, false);
}
private string GetBaseUrl()
{
var baseUrl = _configuration.ProviderRegistrationsApi.BaseUrl.EndsWith("/")
? _configuration.ProviderRegistrationsApi.BaseUrl
: _configuration.ProviderRegistrationsApi.BaseUrl + "/";
return baseUrl;
}
}
} | using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail
{
public class UnsubscribeProviderEmailQueryHandler : AsyncRequestHandler<UnsubscribeProviderEmailQuery>
{
private readonly EmployerAccountsConfiguration _configuration;
private readonly IHttpService _httpService;
public UnsubscribeProviderEmailQueryHandler(
IHttpServiceFactory httpServiceFactory,
EmployerAccountsConfiguration configuration)
{
_configuration = configuration;
_httpService = httpServiceFactory.Create(
configuration.ProviderRelationsApi.ClientId,
configuration.ProviderRelationsApi.ClientSecret,
configuration.ProviderRelationsApi.IdentifierUri,
configuration.ProviderRelationsApi.Tenant
);
}
protected override async Task HandleCore(UnsubscribeProviderEmailQuery message)
{
var baseUrl = GetBaseUrl();
var url = $"{baseUrl}unsubscribe/{message.CorrelationId.ToString()}";
await _httpService.GetAsync(url, false);
}
private string GetBaseUrl()
{
var baseUrl = _configuration.ProviderRelationsApi.BaseUrl.EndsWith("/")
? _configuration.ProviderRelationsApi.BaseUrl
: _configuration.ProviderRelationsApi.BaseUrl + "/";
return baseUrl;
}
}
} | mit | C# |
3bb77eaf2a29c5f69a752fb1805732ffc544d4ef | Add capacity construct to JsonArray and Add function to enable collection initializers | AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp | src/AngleSharp/Html/Forms/Submitters/Json/JsonArray.cs | src/AngleSharp/Html/Forms/Submitters/Json/JsonArray.cs | namespace AngleSharp.Html.Forms.Submitters.Json
{
using AngleSharp.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
sealed class JsonArray : JsonElement, IEnumerable<JsonElement>
{
private readonly List<JsonElement> _elements;
public Int32 Length => _elements.Count;
public JsonArray()
{
_elements = new List<JsonElement>();
}
public JsonArray(int capacity)
{
_elements = new List<JsonElement>(capacity);
}
public void Push(JsonElement element)
{
_elements.Add(element);
}
public void Add(JsonElement element)
{
_elements.Add(element);
}
public JsonElement this[Int32 key]
{
get => _elements.ElementAtOrDefault(key);
set
{
for (var i = _elements.Count; i <= key; i++)
{
_elements.Add(null!);
}
_elements[key] = value;
}
}
public override String ToString()
{
var sb = StringBuilderPool.Obtain().Append(Symbols.SquareBracketOpen);
var needsComma = false;
foreach (var element in _elements)
{
if (needsComma)
sb.Append(Symbols.Comma);
sb.Append(element?.ToString() ?? "null");
needsComma = true;
}
return sb.Append(Symbols.SquareBracketClose).ToPool();
}
public IEnumerator<JsonElement> GetEnumerator()
{
return _elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| namespace AngleSharp.Html.Forms.Submitters.Json
{
using AngleSharp.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
sealed class JsonArray : JsonElement, IEnumerable<JsonElement>
{
private readonly List<JsonElement> _elements = new List<JsonElement>();
public Int32 Length => _elements.Count;
public void Push(JsonElement element)
{
_elements.Add(element);
}
public JsonElement this[Int32 key]
{
get => _elements.ElementAtOrDefault(key);
set
{
for (var i = _elements.Count; i <= key; i++)
{
_elements.Add(null!);
}
_elements[key] = value;
}
}
public override String ToString()
{
var sb = StringBuilderPool.Obtain().Append(Symbols.SquareBracketOpen);
var needsComma = false;
foreach (var element in _elements)
{
if (needsComma)
sb.Append(Symbols.Comma);
sb.Append(element?.ToString() ?? "null");
needsComma = true;
}
return sb.Append(Symbols.SquareBracketClose).ToPool();
}
public IEnumerator<JsonElement> GetEnumerator()
{
return _elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| mit | C# |
30e0aebfa26bba9e3d4cf0f294a3b248524fa95e | Add author name | christianacca/Cache-Abstraction,christianacca/Cache-Abstraction | src/CcAcca.CacheAbstraction/Properties/AssemblyInfo.cs | src/CcAcca.CacheAbstraction/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CcAcca.CacheAbstration")]
[assembly: AssemblyDescription("Simple yet extensible cache abstraction for the .net framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Christian Crowhurst")]
[assembly: AssemblyProduct("CcAcca.CacheAbstration")]
[assembly: AssemblyCopyright("Copyright (c) 2014 Christian Crowhurst")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("adba66d0-ee3d-49fb-9476-bb5bfa9d0c36")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CcAcca.CacheAbstration")]
[assembly: AssemblyDescription("Simple yet extensible cache abstraction for the .net framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CcAcca")]
[assembly: AssemblyProduct("CcAcca.CacheAbstration")]
[assembly: AssemblyCopyright("Copyright (c) 2014 Christian Crowhurst")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("adba66d0-ee3d-49fb-9476-bb5bfa9d0c36")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
c0eea7b99387bb288a58e23172ce56e05365ac43 | Refactor WhenParsingTestResultFiles so that multiple result files are possible | dirkrombauts/pickles,dirkrombauts/pickles,blorgbeard/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,irfanah/pickles,irfanah/pickles,picklesdoc/pickles,magicmonty/pickles,ludwigjossieaux/pickles,blorgbeard/pickles,magicmonty/pickles,picklesdoc/pickles,blorgbeard/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,magicmonty/pickles,irfanah/pickles,irfanah/pickles,blorgbeard/pickles,dirkrombauts/pickles,dirkrombauts/pickles,magicmonty/pickles | src/Pickles/Pickles.Test/WhenParsingTestResultFiles.cs | src/Pickles/Pickles.Test/WhenParsingTestResultFiles.cs | using System;
using System.IO.Abstractions;
using System.IO.Abstractions.TestingHelpers;
using System.Linq;
using System.Reflection;
using Autofac;
using StreamReader = System.IO.StreamReader;
namespace PicklesDoc.Pickles.Test
{
public abstract class WhenParsingTestResultFiles<TResults> : BaseFixture
{
private readonly string[] resultsFileNames;
protected WhenParsingTestResultFiles(string resultsFileName)
{
this.resultsFileNames = resultsFileName.Split(';');
}
protected TResults ParseResultsFile()
{
this.AddTestResultsToConfiguration();
var results = Container.Resolve<TResults>();
return results;
}
protected void AddTestResultsToConfiguration()
{
foreach (var fileName in resultsFileNames)
{
// Write out the embedded test results file
using (var input = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PicklesDoc.Pickles.Test." + fileName)))
{
FileSystem.AddFile(fileName, new MockFileData(input.ReadToEnd()));
}
}
var configuration = Container.Resolve<Configuration>();
configuration.TestResultsFiles = resultsFileNames.Select(f => FileSystem.FileInfo.FromFileName(f)).ToArray();
}
}
} | using System;
using System.IO.Abstractions.TestingHelpers;
using System.Reflection;
using Autofac;
using StreamReader = System.IO.StreamReader;
namespace PicklesDoc.Pickles.Test
{
public abstract class WhenParsingTestResultFiles<TResults> : BaseFixture
{
private readonly string resultsFileName;
protected WhenParsingTestResultFiles(string resultsFileName)
{
this.resultsFileName = resultsFileName;
}
protected TResults ParseResultsFile()
{
this.AddTestResultsToConfiguration();
var results = Container.Resolve<TResults>();
return results;
}
private void AddTestResultsToConfiguration()
{
// Write out the embedded test results file
using (var input = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PicklesDoc.Pickles.Test." + resultsFileName)))
{
FileSystem.AddFile(resultsFileName, new MockFileData(input.ReadToEnd()));
}
var configuration = Container.Resolve<Configuration>();
configuration.TestResultsFiles = new[] { FileSystem.FileInfo.FromFileName(resultsFileName) };
}
}
} | apache-2.0 | C# |
b087bb08ba53c7877ed43c359c38bf03b98e0dd6 | fix authorization path | Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek | Tweek.ApiService.NetCore/Security/AuthorizationDecider.cs | Tweek.ApiService.NetCore/Security/AuthorizationDecider.cs | using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Engine;
using Engine.Core.Context;
using Engine.DataTypes;
using FSharpUtils.Newtonsoft;
using LanguageExt.Trans;
using LanguageExt.SomeHelp;
using LanguageExt.Trans.Linq;
using LanguageExt;
using static LanguageExt.Prelude;
namespace Tweek.ApiService.NetCore.Security
{
public delegate bool CheckReadConfigurationAccess(ClaimsPrincipal identity, string path, ICollection<Identity> tweekIdentities);
public static class Authorization
{
public static CheckReadConfigurationAccess CreateAccessChecker(ITweek tweek)
{
return (identity, path, tweekIdentities) =>
{
if (path == "@tweek/_" || path.StartsWith("@tweek/auth")) return false;
return tweekIdentities.Select(tweekIdentity =>
{
var identityType = tweekIdentity.Type;
var key = $"@tweek/auth/{identityType}/read_configuration";
var result = tweek.CalculateWithLocalContext(key, new HashSet<Identity>(),
type => type == "token" ? (GetContextValue)((string q) => Optional(identity.FindFirst(q)).Map(x=>x.Value).Map(JsonValue.NewString)) : (_) => None)
.SingleKey(key)
.Map(j => j.AsString())
.Match(x => match(x,
with("allow", (_) => true),
with("deny", (_) => false),
(claim) => Optional(identity.FindFirst(claim)).Match(c=> c.Value == tweekIdentity.Id, ()=>false)), () => true);
return result;
}).All(x => x);
};
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Engine;
using Engine.Core.Context;
using Engine.DataTypes;
using FSharpUtils.Newtonsoft;
using LanguageExt.Trans;
using LanguageExt.SomeHelp;
using LanguageExt.Trans.Linq;
using LanguageExt;
using static LanguageExt.Prelude;
namespace Tweek.ApiService.NetCore.Security
{
public delegate bool CheckReadConfigurationAccess(ClaimsPrincipal identity, string path, ICollection<Identity> tweekIdentities);
public static class Authorization
{
public static CheckReadConfigurationAccess CreateAccessChecker(ITweek tweek)
{
return (identity, path, tweekIdentities) =>
{
if (path.StartsWith("@tweek")) return false;
return tweekIdentities.Select(tweekIdentity =>
{
var identityType = tweekIdentity.Type;
var key = $"@tweek/auth/{identityType}/read_configuration";
var result = tweek.CalculateWithLocalContext(key, new HashSet<Identity>(),
type => type == "token" ? (GetContextValue)((string q) => Optional(identity.FindFirst(q)).Map(x=>x.Value).Map(JsonValue.NewString)) : (_) => None)
.SingleKey(key)
.Map(j => j.AsString())
.Match(x => match(x,
with("allow", (_) => true),
with("deny", (_) => false),
(claim) => Optional(identity.FindFirst(claim)).Match(c=> c.Value == tweekIdentity.Id, ()=>false)), () => true);
return result;
}).All(x => x);
};
}
}
}
| mit | C# |
5561f9dbc07c46d594bbb5d5d162664b3a8f8bf3 | Update IMetricTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/IMetricTelemeter.cs | TIKSN.Core/Analytics/Telemetry/IMetricTelemeter.cs | using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public interface IMetricTelemeter
{
Task TrackMetricAsync(string metricName, decimal metricValue);
}
}
| using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public interface IMetricTelemeter
{
Task TrackMetric(string metricName, decimal metricValue);
}
}
| mit | C# |
ca7585d90c5592df5dc1054007768f776c3fb2e5 | Use lower memorylimits value for appveyor build. | dlemstra/Magick.NET,dlemstra/Magick.NET | Tests/Magick.NET.Tests/Core/ResourceLimitsTests.cs | Tests/Magick.NET.Tests/Core/ResourceLimitsTests.cs | //=================================================================================================
// Copyright 2013-2017 Dirk Lemstra <https://magick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.Tests
{
[TestClass]
public class ResourceLimitsTests
{
[TestMethod]
public void Test_Values()
{
Assert.AreEqual(ulong.MaxValue, ResourceLimits.Disk);
if (ResourceLimits.Memory < 100000000U)
Assert.Fail("Invalid memory limit: {0}", ResourceLimits.Memory);
Assert.AreEqual(10000000U, ResourceLimits.Height);
Assert.AreEqual(0U, ResourceLimits.Throttle);
Assert.AreEqual(10000000U, ResourceLimits.Width);
ResourceLimits.Disk = 40000U;
Assert.AreEqual(40000U, ResourceLimits.Disk);
ResourceLimits.Disk = ulong.MaxValue;
ResourceLimits.Height = 100000U;
Assert.AreEqual(100000U, ResourceLimits.Height);
ResourceLimits.Height = 10000000U;
ResourceLimits.Memory = 10000000U;
Assert.AreEqual(10000000U, ResourceLimits.Memory);
ResourceLimits.Memory = 8585838592U;
ResourceLimits.Throttle = 1U;
Assert.AreEqual(1U, ResourceLimits.Throttle);
ResourceLimits.Throttle = 0U;
ResourceLimits.Width = 10000U;
Assert.AreEqual(10000U, ResourceLimits.Width);
ResourceLimits.Width = 10000000U;
}
}
}
| //=================================================================================================
// Copyright 2013-2017 Dirk Lemstra <https://magick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.Tests
{
[TestClass]
public class ResourceLimitsTests
{
[TestMethod]
public void Test_Values()
{
Assert.AreEqual(ulong.MaxValue, ResourceLimits.Disk);
if (ResourceLimits.Memory < 1000000000U)
Assert.Fail("Invalid memory limit: {0}", ResourceLimits.Memory);
Assert.AreEqual(10000000U, ResourceLimits.Height);
Assert.AreEqual(0U, ResourceLimits.Throttle);
Assert.AreEqual(10000000U, ResourceLimits.Width);
ResourceLimits.Disk = 40000U;
Assert.AreEqual(40000U, ResourceLimits.Disk);
ResourceLimits.Disk = ulong.MaxValue;
ResourceLimits.Height = 100000U;
Assert.AreEqual(100000U, ResourceLimits.Height);
ResourceLimits.Height = 10000000U;
ResourceLimits.Memory = 100000000U;
Assert.AreEqual(100000000U, ResourceLimits.Memory);
ResourceLimits.Memory = 8585838592U;
ResourceLimits.Throttle = 1U;
Assert.AreEqual(1U, ResourceLimits.Throttle);
ResourceLimits.Throttle = 0U;
ResourceLimits.Width = 10000U;
Assert.AreEqual(10000U, ResourceLimits.Width);
ResourceLimits.Width = 10000000U;
}
}
}
| apache-2.0 | C# |
ab32c1ba5f78115b18fa0e6c8c08b9f3aecad6a5 | Update NewAzureNetworkWatcherProtocolConfiguration.cs | ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell | src/ResourceManager/Network/Commands.Network/NetworkWatcher/NewAzureNetworkWatcherProtocolConfiguration.cs | src/ResourceManager/Network/Commands.Network/NetworkWatcher/NewAzureNetworkWatcherProtocolConfiguration.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Network.NetworkWatcher
{
[Cmdlet(VerbsCommon.New, "AzureRmNetworkWatcherProtocolConfiguration"),
OutputType(typeof(PSNetworkWatcherProtocolConfiguration))]
public class NewAzureNetworkWatcherProtocolConfiguration : NetworkBaseCmdlet
{
[Parameter(
Mandatory = true,
HelpMessage = "Procotol")]
[ValidateNotNullOrEmpty]
[PSArgumentCompleter("Tcp", "Http", "Https", "Icmp")]
public string Protocol { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Method")]
[ValidateNotNullOrEmpty]
public string Method { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Header")]
[ValidateNotNullOrEmpty]
public IDictionary Header { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "ValidStatusCode")]
[ValidateNotNullOrEmpty]
public int[] ValidStatusCode { get; set; }
public override void Execute()
{
base.Execute();
var protocolConfiguration = new PSNetworkWatcherProtocolConfiguration();
protocolConfiguration.Protocol = this.Protocol;
protocolConfiguration.Method = this.Method;
protocolConfiguration.Header = this.Header;
protocolConfiguration.ValidStatusCode = this.ValidStatusCode;
WriteObject(protocolConfiguration);
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Network.NetworkWatcher
{
[Cmdlet(VerbsCommon.New, "AzureRmNetworkWatcherProtocolConfiguration"),
OutputType(typeof(PSNetworkWatcherProtocolConfiguration))]
public class NewAzureNetworkWatcherProtocolConfiguration : NetworkBaseCmdlet
{
[Parameter(
Mandatory = true,
HelpMessage = "Procotol")]
[ValidateNotNullOrEmpty]
[PSArgumentCompleter("Tcp", "Http", "Https", "Icmp")]
public string Protocol { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Method")]
[ValidateNotNullOrEmpty]
public string Method { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Header")]
[ValidateNotNullOrEmpty]
public IDictionary Header { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "ValidStatusCode")]
[ValidateNotNullOrEmpty]
public int[] ValidStatusCode { get; set; }
public override void Execute()
{
base.Execute();
if (this.Protocol == null)
{
throw new ArgumentException("Protocol cannot be empty to create Protocol Configuration.");
}
var protocolConfiguration = new PSNetworkWatcherProtocolConfiguration();
protocolConfiguration.Protocol = this.Protocol;
protocolConfiguration.Method = this.Method;
protocolConfiguration.Header = this.Header;
protocolConfiguration.ValidStatusCode = this.ValidStatusCode;
WriteObject(protocolConfiguration);
}
}
}
| apache-2.0 | C# |
d263bcdd2d78c36e3bb4ac0e716140d954c5a0ee | Add ProcessorInfo.sustainedClockSpeedInGhz | carbon/Amazon | src/Amazon.Ec2/Models/Instances/ProcessorInfo.cs | src/Amazon.Ec2/Models/Instances/ProcessorInfo.cs | using System.Xml.Serialization;
namespace Amazon.Ec2
{
public sealed class ProcessorInfo
{
[XmlElement("sustainedClockSpeedInGhz")]
public double? SustainedClockSpeedInGhz { get; set; }
[XmlArray("supportedArchitectures")]
[XmlArrayItem("item")]
public string[]? SupportedArchitectures { get; set; }
}
} | #nullable disable
using System.Xml.Serialization;
namespace Amazon.Ec2
{
public sealed class ProcessorInfo
{
[XmlArray("supportedArchitectures")]
[XmlArrayItem("item")]
public string[] SupportedArchitectures { get; set; }
}
} | mit | C# |
2047baf8bc6470c7406dcafcce9f6ee773f9be7f | Allow the status to be any object instead of just a string. | lynxx131/dotnet.microservice | src/Dotnet.Microservice/Health/HealthResponse.cs | src/Dotnet.Microservice/Health/HealthResponse.cs | using System;
namespace Dotnet.Microservice.Health
{
/// <summary>
/// Represents a health check response
/// </summary>
public struct HealthResponse
{
public readonly bool IsHealthy;
public readonly object Response;
private HealthResponse(bool isHealthy, object statusObject)
{
IsHealthy = isHealthy;
Response = statusObject;
}
public static HealthResponse Healthy()
{
return Healthy("OK");
}
public static HealthResponse Healthy(object response)
{
return new HealthResponse(true, response);
}
public static HealthResponse Unhealthy()
{
return Unhealthy("FAILED");
}
public static HealthResponse Unhealthy(object response)
{
return new HealthResponse(false, response);
}
public static HealthResponse Unhealthy(Exception exception)
{
var message = $"EXCEPTION: {exception.GetType().Name}, {exception.Message}";
return new HealthResponse(false, message);
}
}
}
| using System;
namespace Dotnet.Microservice.Health
{
/// <summary>
/// Represents a health check response
/// </summary>
public struct HealthResponse
{
public readonly bool IsHealthy;
public readonly string Message;
private HealthResponse(bool isHealthy, string statusMessage)
{
IsHealthy = isHealthy;
Message = statusMessage;
}
public static HealthResponse Healthy()
{
return Healthy("OK");
}
public static HealthResponse Healthy(string message)
{
return new HealthResponse(true, message);
}
public static HealthResponse Unhealthy()
{
return Unhealthy("FAILED");
}
public static HealthResponse Unhealthy(string message)
{
return new HealthResponse(false, message);
}
public static HealthResponse Unhealthy(Exception exception)
{
var message = $"EXCEPTION: {exception.GetType().Name}, {exception.Message}";
return new HealthResponse(false, message);
}
}
}
| isc | C# |
bdbb86945886d932f249ca1e9bf6ab7af0016ac9 | add ct | AsynkronIT/protoactor-dotnet | src/Proto.Actor/Utils/ConcurrentKeyValueStore.cs | src/Proto.Actor/Utils/ConcurrentKeyValueStore.cs | // -----------------------------------------------------------------------
// <copyright file="ConcurrentKeyValueStore.cs" company="Asynkron AB">
// Copyright (C) 2015-2021 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Proto.Utils
{
namespace Proto.Utils
{
[PublicAPI]
public abstract class ConcurrentKeyValueStore<T>
{
private readonly AsyncSemaphore _semaphore;
protected ConcurrentKeyValueStore(AsyncSemaphore semaphore) => _semaphore = semaphore;
public Task<T?> GetStateAsync(string id, CancellationToken ct) => _semaphore.WaitAsync(() => InnerGetStateAsync(id, ct));
public Task SetStateAsync(string id, T state, CancellationToken ct) => _semaphore.WaitAsync(() => InnerSetStateAsync(id, state, ct));
public Task ClearStateAsync(string id, CancellationToken ct) => _semaphore.WaitAsync(() => InnerClearStateAsync(id, ct));
protected abstract Task<T?> InnerGetStateAsync(string id, CancellationToken ct);
protected abstract Task InnerSetStateAsync(string id, T state, CancellationToken ct);
protected abstract Task InnerClearStateAsync(string id, CancellationToken ct);
}
}
} | // -----------------------------------------------------------------------
// <copyright file="ConcurrentKeyValueStore.cs" company="Asynkron AB">
// Copyright (C) 2015-2021 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Proto.Utils
{
namespace Proto.Utils
{
[PublicAPI]
public abstract class ConcurrentKeyValueStore<T>
{
private readonly AsyncSemaphore _semaphore;
protected ConcurrentKeyValueStore(AsyncSemaphore semaphore) => _semaphore = semaphore;
public Task<T?> GetStateAsync(string id) => _semaphore.WaitAsync(() => InnerGetStateAsync(id));
public Task SetStateAsync(string id, T state) => _semaphore.WaitAsync(() => InnerSetStateAsync(id, state));
public Task ClearStateAsync(string id) => _semaphore.WaitAsync(() => InnerClearStateAsync(id));
protected abstract Task<T?> InnerGetStateAsync(string id);
protected abstract Task InnerSetStateAsync(string id, T state);
protected abstract Task InnerClearStateAsync(string id);
}
}
} | apache-2.0 | C# |
266646d353ba806d765f2dc86e882d7fa1a131ad | Fix issue #2 | WebApiContrib/WebApiContrib.IoC.Ninject,WebApiContrib/WebApiContrib.IoC.Ninject | src/WebApiContrib.IoC.Ninject/NinjectResolver.cs | src/WebApiContrib.IoC.Ninject/NinjectResolver.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Web.Http.Dependencies;
using Ninject;
using Ninject.Syntax;
namespace WebApiContrib.IoC.Ninject
{
/// <summary>
/// Updated from https://gist.github.com/2417226/040dd842d3dadb810065f1edad7f2594eaebe806
/// </summary>
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
resolver = null;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.GetAll(serviceType);
}
}
public class NinjectResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Web.Http.Dependencies;
using Ninject;
using Ninject.Syntax;
namespace WebApiContrib.IoC.Ninject
{
/// <summary>
/// Updated from https://gist.github.com/2417226/040dd842d3dadb810065f1edad7f2594eaebe806
/// </summary>
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.GetAll(serviceType);
}
}
public class NinjectResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
}
| mit | C# |
0b42533da9819954842f815897b38ad640ccd481 | Add NuGet restore to cake build | iivchenko/Wem-Studio | Build/build.cake | Build/build.cake | Task("NuGet")
.Does(() =>
{
NuGetRestore("../Src/WEMMS.sln");
});
Task("Default")
.IsDependentOn("NuGet")
.Does(() =>
{
MSBuild("../Src/WEMMS.sln");
});
RunTarget("Default"); | Task("Default")
.Does(() =>
{
MSBuild("..\\Src\\WEMMS.sln");
});
RunTarget("Default"); | mit | C# |
156933880ed8fda83a43716daa7f18561b19e95d | add entry point for CloudBuild. | sassembla/Miyamasu,sassembla/Miyamasu | Assets/MiyamasuTestRunner/Editor/MiyamasuTestIgniter.cs | Assets/MiyamasuTestRunner/Editor/MiyamasuTestIgniter.cs | using UnityEditor;
using UnityEngine;
namespace Miyamasu {
/*
Run tests when Initialize on load.
this thread is Unity Editor's MainThread, is ≒ Unity Player's MainThread.
*/
[InitializeOnLoad] public class MiyamasuTestIgniter {
static MiyamasuTestIgniter () {
#if CLOUDBUILD
{
Debug.Log("in cloudbuild.");
}
#else
{
var testRunner = new MiyamasuTestRunner();
testRunner.RunTestsOnEditorMainThread();
}
#endif
}
public static void CloudBuildTest () {
#if CLOUDBUILD
{
Debug.Log("in cloudbuild.");
}
#else
{
var testRunner = new MiyamasuTestRunner();
testRunner.RunTestsOnEditorMainThread();
}
#endif
}
}
} | using UnityEditor;
using UnityEngine;
namespace Miyamasu {
/*
Run tests when Initialize on load.
this thread is Unity Editor's MainThread, is ≒ Unity Player's MainThread.
*/
[InitializeOnLoad] public class MiyamasuTestIgniter {
static MiyamasuTestIgniter () {
#if CLOUDBUILD
{
Debug.Log("in cloudbuild.");
}
#else
{
var testRunner = new MiyamasuTestRunner();
testRunner.RunTestsOnEditorMainThread();
}
#endif
}
}
} | mit | C# |
77c0a1d8ba6c3e514a10d78a15c5438a9ffef6b1 | check more previous packets for sReturnToLobby | neowutran/OpcodeSearcher | DamageMeter.Core/Heuristic/S_PREPARE_RETURN_TO_LOBBY.cs | DamageMeter.Core/Heuristic/S_PREPARE_RETURN_TO_LOBBY.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tera;
using Tera.Game.Messages;
namespace DamageMeter.Heuristic
{
public class S_PREPARE_RETURN_TO_LOBBY : AbstractPacketHeuristic
{
public new void Process(ParsedMessage message)
{
base.Process(message);
if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; }
if (message.Payload.Count != 4) { return; }
var time = Reader.ReadInt32();
if(time == 0) return;
for (int i = 0; i < 5; i++)
{
var p = OpcodeFinder.Instance.GetMessage(OpcodeFinder.Instance.PacketCount - 1 - i);
if (p.Direction != MessageDirection.ClientToServer || p.Payload.Count != 0) { continue; }
//Return To lobby detection
OpcodeFinder.Instance.SetOpcode(p.OpCode, OpcodeEnum.C_RETURN_TO_LOBBY);
//S_PREPARE_RETURN_TO_LOBBY
OpcodeFinder.Instance.SetOpcode(message.OpCode, OPCODE);
S_CLEAR_ALL_HOLDED_ABNORMALITY.Wait();
return;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tera.Game.Messages;
namespace DamageMeter.Heuristic
{
public class S_PREPARE_RETURN_TO_LOBBY : AbstractPacketHeuristic
{
public new void Process(ParsedMessage message)
{
base.Process(message);
if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; }
if (message.Payload.Count != 4) { return; }
var previousPacket = OpcodeFinder.Instance.GetMessage(OpcodeFinder.Instance.PacketCount - 1);
if (previousPacket.Direction == Tera.MessageDirection.ClientToServer && previousPacket.Payload.Count == 0)
{
var time = Reader.ReadInt32();
if (time != 0 && OpcodeFinder.Instance.KnowledgeDatabase.ContainsKey(OpcodeFinder.KnowledgeDatabaseItem.CharacterSpawnedSuccesfully))
{
//Return To lobby detection
OpcodeFinder.Instance.SetOpcode(previousPacket.OpCode, OpcodeEnum.C_RETURN_TO_LOBBY);
//S_PREPARE_RETURN_TO_LOBBY
OpcodeFinder.Instance.SetOpcode(message.OpCode, OPCODE);
S_CLEAR_ALL_HOLDED_ABNORMALITY.Wait();
}
}
}
}
} | mit | C# |
9fae02a317ea3a5b0fb223c75ad75b18ff88a193 | Fix compilation of ApplicationTest | Forage/gstreamer-sharp,Forage/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,Forage/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,Forage/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp | tests/ApplicationTest.cs | tests/ApplicationTest.cs | //
// ApplicationTest.cs: NUnit Test Suite for gstreamer-sharp
//
// Authors:
// Aaron Bockover ([email protected])
//
// (C) 2006 Novell, Inc.
//
using System;
using NUnit.Framework;
[TestFixture]
public class ApplicationTest
{
[Test]
public void Init()
{
Gst.Application.Init();
Gst.Application.Deinit();
}
[Test]
public void InitArgs()
{
string [] args = { "arg_a", "arg_b" };
Gst.Application.Init("gstreamer-sharp-test", ref args);
Gst.Application.Deinit();
}
[Test]
public void InitArgsCheck()
{
string [] args = { "arg_a", "arg_b" };
Gst.Application.InitCheck("gstreamer-sharp-test", ref args);
Gst.Application.Deinit();
}
}
| //
// ApplicationTest.cs: NUnit Test Suite for gstreamer-sharp
//
// Authors:
// Aaron Bockover ([email protected])
//
// (C) 2006 Novell, Inc.
//
using System;
using NUnit.Framework;
[TestFixture]
public class ApplicationTest
{
[Test]
public void Init()
{
Gst.Application.Init();
Gst.Application.Deinit();
}
[Test]
public void InitArgs()
{
string [] args = { "arg_a", "arg_b" };
Gst.Application.Init("gstreamer-sharp-test", ref args);
Gst.Application.Deinit();
}
[Test]
public void InitArgsCheck()
{
string [] args = { "arg_a", "arg_b" };
Gst.Application.InitCheck("gstreamer-sharp-test", ref args);
Gst.Application.Deinit();
}
[Test]
public void TestVersion()
{
Assert.AreEqual(Gst.Application.Version.Minor, 10);
}
[Test]
public void TestVersionString()
{
Assert.IsNotNull(Gst.Application.Version.ToString());
}
[Test]
public void TestVersionDescription()
{
Assert.IsNotNull(Gst.Application.Version.Description);
}
}
| lgpl-2.1 | C# |
12a315799fb50404d1bed10923415d423813ed0f | order by name | bendetat/Listy-Azure,bendetat/Listy-Azure | src/Listy.Web/Controllers/Api/ListsController.cs | src/Listy.Web/Controllers/Api/ListsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Listy.Data.Entities;
using NHibernate;
namespace Listy.Web.Controllers.Api
{
public class ListsController : ApiController
{
private readonly ISessionFactory _sessionFactory;
public ListsController(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
}
public object Get()
{
using (var session = _sessionFactory.OpenSession())
{
using (session.BeginTransaction())
{
var lists = session
.QueryOver<ListyList>()
.OrderBy(l => l.Name).Asc
.List<ListyList>();
return lists.Select(l => new
{
Id = l.Id,
Name= l.Name,
});
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Listy.Data.Entities;
using NHibernate;
namespace Listy.Web.Controllers.Api
{
public class ListsController : ApiController
{
private readonly ISessionFactory _sessionFactory;
public ListsController(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
}
public object Get()
{
using (var session = _sessionFactory.OpenSession())
{
using (session.BeginTransaction())
{
var lists = session.CreateCriteria<ListyList>().List<ListyList>();
return lists.Select(l => new
{
Id = l.Id,
Name= l.Name,
});
}
}
}
}
}
| apache-2.0 | C# |
54a162e3843649a94be8a94f683107ca2c1623fb | 处理返回对应的异常消息。 :exclamation: | Zongsoft/Zongsoft.Web | src/Http/ExceptionFilter.cs | src/Http/ExceptionFilter.cs | /*
* Authors:
* 钟峰(Popeye Zhong) <[email protected]>
*
* Copyright (C) 2016 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.Web.
*
* Zongsoft.Web is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.Web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.Web; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
namespace Zongsoft.Web.Http
{
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if(actionExecutedContext.Exception == null)
return;
if(actionExecutedContext.Exception is Zongsoft.Security.Membership.AuthenticationException ||
actionExecutedContext.Exception is Zongsoft.Security.Membership.AuthorizationException)
{
actionExecutedContext.Response = this.GetExceptionResponse(actionExecutedContext.Exception, HttpStatusCode.Forbidden);
//退出,不用记录日志
return;
}
//生成返回的异常消息内容
actionExecutedContext.Response = this.GetExceptionResponse(actionExecutedContext.Exception);
//默认将异常信息写入日志文件
Zongsoft.Diagnostics.Logger.Error(actionExecutedContext.Exception);
}
private HttpResponseMessage GetExceptionResponse(Exception exception, HttpStatusCode status = HttpStatusCode.InternalServerError)
{
if(exception == null)
return null;
var message = exception.Message;
if(exception.InnerException != null)
message += Environment.NewLine + exception.InnerException.Message;
message = message?.Replace('"', '\'');
var response = new HttpResponseMessage(status)
{
Content = new StringContent($"{{\"type\":\"{exception.GetType().Name}\",\"message\":\"{message}\"}}", System.Text.Encoding.UTF8, "application/json")
};
return response;
}
}
}
| /*
* Authors:
* 钟峰(Popeye Zhong) <[email protected]>
*
* Copyright (C) 2016 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.Web.
*
* Zongsoft.Web is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.Web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.Web; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Web.Http.Filters;
namespace Zongsoft.Web.Http
{
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if(actionExecutedContext.Exception != null)
Zongsoft.Diagnostics.Logger.Error(actionExecutedContext.Exception);
}
}
}
| lgpl-2.1 | C# |
38d5e7085515159593bc16cdef7d6fb97fe607dc | Add Roles Index View link to Admin Index View.. | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Views/Admin/Index.cshtml | src/Open-School-Library/Views/Admin/Index.cshtml | @*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<div class="panel-body">
<h3>Administrator Links:</h3>
<br />
<ul style="list-style: none;">
<li>
<a asp-controller="Roles" asp-action="Index">Roles</a>
</li>
</ul>
</div> | @*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
| mit | C# |
164e88774ea4429525b593432d2fc253c4c59eea | update version | prodot/ReCommended-Extension | Sources/ReCommendedExtension/Properties/AssemblyInfo.cs | Sources/ReCommendedExtension/Properties/AssemblyInfo.cs | using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2019 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("3.6.4.0")]
[assembly: AssemblyFileVersion("3.6.4")] | using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2019 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("3.6.3.0")]
[assembly: AssemblyFileVersion("3.6.3")] | apache-2.0 | C# |
d0f8fdb79d41069e2af3898369e22e71d195c097 | Fix unit test failing in Debug11 configuration. | pratikkagda/nuget,jmezach/NuGet2,jmezach/NuGet2,jholovacs/NuGet,indsoft/NuGet2,chocolatey/nuget-chocolatey,indsoft/NuGet2,ctaggart/nuget,alluran/node.net,alluran/node.net,GearedToWar/NuGet2,mrward/NuGet.V2,atheken/nuget,dolkensp/node.net,OneGet/nuget,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,anurse/NuGet,mrward/nuget,xoofx/NuGet,jholovacs/NuGet,jmezach/NuGet2,GearedToWar/NuGet2,akrisiun/NuGet,antiufo/NuGet2,ctaggart/nuget,chocolatey/nuget-chocolatey,rikoe/nuget,alluran/node.net,pratikkagda/nuget,GearedToWar/NuGet2,mrward/NuGet.V2,rikoe/nuget,antiufo/NuGet2,xoofx/NuGet,jmezach/NuGet2,mono/nuget,RichiCoder1/nuget-chocolatey,OneGet/nuget,oliver-feng/nuget,pratikkagda/nuget,indsoft/NuGet2,antiufo/NuGet2,mrward/nuget,xoofx/NuGet,jmezach/NuGet2,jmezach/NuGet2,chester89/nugetApi,RichiCoder1/nuget-chocolatey,OneGet/nuget,xoofx/NuGet,anurse/NuGet,antiufo/NuGet2,mrward/nuget,jholovacs/NuGet,chocolatey/nuget-chocolatey,GearedToWar/NuGet2,akrisiun/NuGet,GearedToWar/NuGet2,mrward/nuget,oliver-feng/nuget,GearedToWar/NuGet2,mrward/nuget,zskullz/nuget,RichiCoder1/nuget-chocolatey,xoofx/NuGet,alluran/node.net,mono/nuget,themotleyfool/NuGet,jholovacs/NuGet,ctaggart/nuget,chocolatey/nuget-chocolatey,themotleyfool/NuGet,dolkensp/node.net,mrward/NuGet.V2,chocolatey/nuget-chocolatey,pratikkagda/nuget,oliver-feng/nuget,mono/nuget,xoofx/NuGet,oliver-feng/nuget,antiufo/NuGet2,mono/nuget,themotleyfool/NuGet,mrward/nuget,mrward/NuGet.V2,chocolatey/nuget-chocolatey,antiufo/NuGet2,jholovacs/NuGet,rikoe/nuget,mrward/NuGet.V2,indsoft/NuGet2,atheken/nuget,dolkensp/node.net,rikoe/nuget,zskullz/nuget,zskullz/nuget,pratikkagda/nuget,ctaggart/nuget,OneGet/nuget,kumavis/NuGet,indsoft/NuGet2,jholovacs/NuGet,kumavis/NuGet,chester89/nugetApi,mrward/NuGet.V2,oliver-feng/nuget,oliver-feng/nuget,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,dolkensp/node.net,zskullz/nuget,pratikkagda/nuget | src/Core/Utility/UriUtility.cs | src/Core/Utility/UriUtility.cs | using System;
using System.IO;
using System.IO.Packaging;
using System.Linq;
namespace NuGet
{
internal static class UriUtility
{
/// <summary>
/// Converts a uri to a path. Only used for local paths.
/// </summary>
internal static string GetPath(Uri uri)
{
string path = uri.OriginalString;
if (path.StartsWith("/", StringComparison.Ordinal))
{
path = path.Substring(1);
}
// Bug 483: We need the unescaped uri string to ensure that all characters are valid for a path.
// Change the direction of the slashes to match the filesystem.
return Uri.UnescapeDataString(path.Replace('/', Path.DirectorySeparatorChar));
}
internal static Uri CreatePartUri(string path)
{
// Only the segments between the path separators should be escaped
var segments = path.Split( new[] { '/', Path.DirectorySeparatorChar }, StringSplitOptions.None)
.Select(Uri.EscapeDataString);
var escapedPath = String.Join("/", segments);
return PackUriHelper.CreatePartUri(new Uri(escapedPath, UriKind.Relative));
}
/// <summary>
/// Determines if the scheme, server and path of two Uris are identical.
/// </summary>
public static bool UriEquals(Uri uri1, Uri uri2)
{
uri1 = new Uri(uri1.OriginalString.TrimEnd('/'));
uri2 = new Uri(uri2.OriginalString.TrimEnd('/'));
return Uri.Compare(uri1, uri2, UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase) == 0;
}
}
}
| using System;
using System.IO;
using System.IO.Packaging;
using System.Linq;
namespace NuGet
{
internal static class UriUtility
{
/// <summary>
/// Converts a uri to a path. Only used for local paths.
/// </summary>
internal static string GetPath(Uri uri)
{
string path = uri.OriginalString;
if (path.StartsWith("/", StringComparison.Ordinal))
{
path = path.Substring(1);
}
// Bug 483: We need the unescaped uri string to ensure that all characters are valid for a path.
// Change the direction of the slashes to match the filesystem.
return Uri.UnescapeDataString(path.Replace('/', Path.DirectorySeparatorChar));
}
internal static Uri CreatePartUri(string path)
{
// Only the segments between the path separators should be escaped
var segments = path.Split(new[] { "/" }, StringSplitOptions.None)
.Select(Uri.EscapeDataString);
var escapedPath = String.Join("/", segments);
return PackUriHelper.CreatePartUri(new Uri(escapedPath, UriKind.Relative));
}
/// <summary>
/// Determines if the scheme, server and path of two Uris are identical.
/// </summary>
public static bool UriEquals(Uri uri1, Uri uri2)
{
uri1 = new Uri(uri1.OriginalString.TrimEnd('/'));
uri2 = new Uri(uri2.OriginalString.TrimEnd('/'));
return Uri.Compare(uri1, uri2, UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase) == 0;
}
}
}
| apache-2.0 | C# |
00efed2c39d67d0d5f4c5b0d21509ebea2fef205 | Add colours for tick judgements | ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu | osu.Game/Screens/Play/HUD/HitErrorMeters/HitErrorMeter.cs | osu.Game/Screens/Play/HUD/HitErrorMeters/HitErrorMeter.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.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Skinning;
using osuTK.Graphics;
namespace osu.Game.Screens.Play.HUD.HitErrorMeters
{
public abstract class HitErrorMeter : CompositeDrawable, ISkinnableDrawable
{
protected HitWindows HitWindows { get; private set; }
[Resolved]
private ScoreProcessor processor { get; set; }
[Resolved]
private OsuColour colours { get; set; }
[BackgroundDependencyLoader(true)]
private void load(DrawableRuleset drawableRuleset)
{
HitWindows = drawableRuleset?.FirstAvailableHitWindows ?? HitWindows.Empty;
}
protected override void LoadComplete()
{
base.LoadComplete();
processor.NewJudgement += OnNewJudgement;
}
protected abstract void OnNewJudgement(JudgementResult judgement);
protected Color4 GetColourForHitResult(HitResult result)
{
switch (result)
{
case HitResult.SmallTickMiss:
case HitResult.LargeTickMiss:
case HitResult.Miss:
return colours.Red;
case HitResult.Meh:
return colours.Yellow;
case HitResult.Ok:
return colours.Green;
case HitResult.Good:
return colours.GreenLight;
case HitResult.SmallTickHit:
case HitResult.LargeTickHit:
case HitResult.Great:
return colours.Blue;
default:
return colours.BlueLight;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (processor != null)
processor.NewJudgement -= OnNewJudgement;
}
}
}
| // 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.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Skinning;
using osuTK.Graphics;
namespace osu.Game.Screens.Play.HUD.HitErrorMeters
{
public abstract class HitErrorMeter : CompositeDrawable, ISkinnableDrawable
{
protected HitWindows HitWindows { get; private set; }
[Resolved]
private ScoreProcessor processor { get; set; }
[Resolved]
private OsuColour colours { get; set; }
[BackgroundDependencyLoader(true)]
private void load(DrawableRuleset drawableRuleset)
{
HitWindows = drawableRuleset?.FirstAvailableHitWindows ?? HitWindows.Empty;
}
protected override void LoadComplete()
{
base.LoadComplete();
processor.NewJudgement += OnNewJudgement;
}
protected abstract void OnNewJudgement(JudgementResult judgement);
protected Color4 GetColourForHitResult(HitResult result)
{
switch (result)
{
case HitResult.Miss:
return colours.Red;
case HitResult.Meh:
return colours.Yellow;
case HitResult.Ok:
return colours.Green;
case HitResult.Good:
return colours.GreenLight;
case HitResult.Great:
return colours.Blue;
default:
return colours.BlueLight;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (processor != null)
processor.NewJudgement -= OnNewJudgement;
}
}
}
| mit | C# |
34cd75945bb872a47c560d3724b936ab8a9d524e | return SetDeviceToken | growthbeat/growthbeat-unity,growthbeat/growthbeat-unity,SIROK/growthbeat-unity,SIROK/growthbeat-unity | source/Assets/Plugins/Growthbeat/GrowthPush.cs | source/Assets/Plugins/Growthbeat/GrowthPush.cs | //
// GrowthPush.cs
// Growthbeat-unity
//
// Created by Baekwoo Chung on 2015/06/15.
// Copyright (c) 2015年 SIROK, Inc. All rights reserved.
//
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class GrowthPush {
private static GrowthPush instance = new GrowthPush ();
public enum Environment {
Unknown = 0,
Development = 1,
Production = 2
}
#if UNITY_IPHONE
[DllImport("__Internal")] private static extern void requestDeviceToken(int environment);
[DllImport("__Internal")] private static extern void setDeviceToken(string deviceToken);
[DllImport("__Internal")] private static extern void cearBadge();
[DllImport("__Internal")] private static extern void setTag(string name, string value);
[DllImport("__Internal")] private static extern void trackEvent(string name, string value);
[DllImport("__Internal")] private static extern void setDeviceTags();
#endif
public static GrowthPush GetInstance ()
{
return GrowthPush.instance;
}
public void RequestDeviceToken (string senderId, Environment environment)
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().RequestRegistrationId(senderId, environment);
#elif UNITY_IPHONE && !UNITY_EDITOR
requestDeviceToken((int)environment);
#endif
}
public void RequestDeviceToken (Environment environment)
{
#if UNITY_ANDROID
#elif UNITY_IPHONE && !UNITY_EDITOR
RequestDeviceToken((null, environment);
#endif
}
public void SetDeviceToken (string deviceToken)
{
#if UNITY_ANDROID
#elif UNITY_IPHONE && !UNITY_EDITOR
setDeviceToken((deviceToken);
#endif
}
public void ClearBadge ()
{
#if UNITY_IPHONE && !UNITY_EDITOR
growthPushClearBadge();
#endif
}
public void SetTag (string name)
{
SetTag (name, null);
}
public void SetTag (string name, string value)
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().SetTag(name, value);
#elif UNITY_IPHONE && !UNITY_EDITOR
setTag(name, value);
#endif
}
public void TrackEvent(string name)
{
TrackEvent (name, null);
}
public void TrackEvent (string name, string value)
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().TrackEvent(name, value);
#elif UNITY_IPHONE && !UNITY_EDITOR
trackEvent(name, value);
#endif
}
public void SetDeviceTags ()
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().SetDeviceTags();
#elif UNITY_IPHONE && !UNITY_EDITOR
setDeviceTags();
#endif
}
}
| //
// GrowthPush.cs
// Growthbeat-unity
//
// Created by Baekwoo Chung on 2015/06/15.
// Copyright (c) 2015年 SIROK, Inc. All rights reserved.
//
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class GrowthPush {
private static GrowthPush instance = new GrowthPush ();
public enum Environment {
Unknown = 0,
Development = 1,
Production = 2
}
#if UNITY_IPHONE
[DllImport("__Internal")] private static extern void requestDeviceToken(int environment);
[DllImport("__Internal")] private static extern void setDeviceToken(string deviceToken);
[DllImport("__Internal")] private static extern void cearBadge();
[DllImport("__Internal")] private static extern void setTag(string name, string value);
[DllImport("__Internal")] private static extern void trackEvent(string name, string value);
[DllImport("__Internal")] private static extern void setDeviceTags();
#endif
public static GrowthPush GetInstance ()
{
return GrowthPush.instance;
}
public void RequestDeviceToken (string senderId, Environment environment)
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().RequestRegistrationId(senderId, environment);
#elif UNITY_IPHONE && !UNITY_EDITOR
requestDeviceToken((int)environment);
#endif
}
public void RequestDeviceToken (Environment environment)
{
#if UNITY_ANDROID
#elif UNITY_IPHONE && !UNITY_EDITOR
RequestDeviceToken((null, environment);
#endif
}
public void ClearBadge ()
{
#if UNITY_IPHONE && !UNITY_EDITOR
growthPushClearBadge();
#endif
}
public void SetTag (string name)
{
SetTag (name, null);
}
public void SetTag (string name, string value)
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().SetTag(name, value);
#elif UNITY_IPHONE && !UNITY_EDITOR
setTag(name, value);
#endif
}
public void TrackEvent(string name)
{
TrackEvent (name, null);
}
public void TrackEvent (string name, string value)
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().TrackEvent(name, value);
#elif UNITY_IPHONE && !UNITY_EDITOR
trackEvent(name, value);
#endif
}
public void SetDeviceTags ()
{
#if UNITY_ANDROID
GrowthPushAndroid.GetInstance().SetDeviceTags();
#elif UNITY_IPHONE && !UNITY_EDITOR
setDeviceTags();
#endif
}
}
| apache-2.0 | C# |
c6086669512365de27a51c45d16f94f8af636f8e | Fix refunder authorization | ucdavis/CRP,ucdavis/CRP,ucdavis/CRP | CRP.Mvc/Controllers/Helpers/Filter/RolesFilter.cs | CRP.Mvc/Controllers/Helpers/Filter/RolesFilter.cs | using System;
using System.Web.Mvc;
using CRP.Controllers.Helpers;
namespace CRP.Controllers.Filter
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AdminOnlyAttribute : AuthorizeAttribute
{
public AdminOnlyAttribute()
{
Roles = RoleNames.Admin; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class UserOnlyAttribute : AuthorizeAttribute
{
public UserOnlyAttribute()
{
Roles = RoleNames.User; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AnyoneWithRoleAttribute : AuthorizeAttribute
{
public AnyoneWithRoleAttribute()
{
Roles = RoleNames.Admin + "," + RoleNames.User; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class UserAdminOnlyAttribute : AuthorizeAttribute
{
public UserAdminOnlyAttribute()
{
Roles = RoleNames.ManageAll + "," + RoleNames.SchoolAdmin; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RefunderOnlyAttribute : AuthorizeAttribute
{
public RefunderOnlyAttribute()
{
Roles = RoleNames.Admin + "," + RoleNames.Refunder; //Set the roles prop to a comma delimited string of allowed roles
}
}
}
| using System;
using System.Web.Mvc;
using CRP.Controllers.Helpers;
namespace CRP.Controllers.Filter
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AdminOnlyAttribute : AuthorizeAttribute
{
public AdminOnlyAttribute()
{
Roles = RoleNames.Admin; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class UserOnlyAttribute : AuthorizeAttribute
{
public UserOnlyAttribute()
{
Roles = RoleNames.User; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AnyoneWithRoleAttribute : AuthorizeAttribute
{
public AnyoneWithRoleAttribute()
{
Roles = RoleNames.Admin + "," + RoleNames.User; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class UserAdminOnlyAttribute : AuthorizeAttribute
{
public UserAdminOnlyAttribute()
{
Roles = RoleNames.ManageAll + "," + RoleNames.SchoolAdmin; //Set the roles prop to a comma delimited string of allowed roles
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RefunderOnlyAttribute : AuthorizeAttribute
{
public RefunderOnlyAttribute()
{
Roles = RoleNames.Refunder; //Set the roles prop to a comma delimited string of allowed roles
}
}
}
| mit | C# |
58af2c918136d6935845032bbd5fc5dd31c64ff5 | Fix puzzle | martincostello/project-euler | src/ProjectEuler/Puzzles/Puzzle092.cs | src/ProjectEuler/Puzzles/Puzzle092.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=92</c>. This class cannot be inherited.
/// </summary>
public sealed class Puzzle092 : Puzzle
{
/// <inheritdoc />
public override string Question => "How many starting numbers below ten million will arrive at 89 from square digit addition?";
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
const int Limit = 10_000_000;
const int Target = 89;
int count = 0;
for (int i = 1; i < Limit; i++)
{
int value = i;
while (value != 1 && value != Target)
{
value = Maths.Digits(value).Sum((p) => p * p);
}
if (value == Target)
{
count++;
}
}
Answer = count;
return 0;
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=92</c>. This class cannot be inherited.
/// </summary>
public sealed class Puzzle092 : Puzzle
{
/// <inheritdoc />
public override string Question => "How many starting numbers below ten million will arrive at 89 from square digit addition?";
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
const int Limit = 10_000_000;
const int Target = 89;
int count = 0;
for (int i = 1; i < Limit; i++)
{
int value = i;
while (value != 1 && value != Target)
{
value = Maths.Digits(value).Aggregate((x, y) => (x * x) + y);
}
if (value == Target)
{
count++;
}
}
Answer = count;
return 0;
}
}
| apache-2.0 | C# |
a7fd882d7aeeae8c03256fa7e34e0c02e40ade8a | Fix path to SPARQL test suite files | BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB | src/core/BrightstarDB.InternalTests/TestPaths.cs | src/core/BrightstarDB.InternalTests/TestPaths.cs | using System.IO;
using NUnit.Framework;
namespace BrightstarDB.InternalTests
{
internal static class TestPaths
{
public static string DataPath => Path.Combine(TestContext.CurrentContext.TestDirectory, "..\\..\\..\\..\\BrightstarDB.Tests\\Data\\");
}
}
| using System.IO;
using NUnit.Framework;
namespace BrightstarDB.InternalTests
{
internal static class TestPaths
{
public static string DataPath => Path.Combine(TestContext.CurrentContext.TestDirectory, "..\\..\\..\\BrightstarDB.Tests\\Data\\");
}
}
| mit | C# |
8f3fa7cd2661a282a31fbd9eb514d86bce2f872e | Move initialization logic to ctor | mstrother/BmpListener | BmpListener/Bmp/BmpHeader.cs | BmpListener/Bmp/BmpHeader.cs | using System;
using Newtonsoft.Json;
using System.Linq;
using BmpListener;
namespace BmpListener.Bmp
{
public class BmpHeader
{
public BmpHeader(byte[] data)
{
Version = data.First();
//if (Version != 3)
//{
// throw new Exception("invalid BMP version");
//}
Length = data.ToUInt32(1);
Type = (MessageType)data.ElementAt(5);
}
public byte Version { get; private set; }
[JsonIgnore]
public uint Length { get; private set; }
public MessageType Type { get; private set; }
}
} | using System;
using Newtonsoft.Json;
namespace BmpListener.Bmp
{
public class BmpHeader
{
public BmpHeader(byte[] data)
{
ParseBytes(data);
}
public byte Version { get; private set; }
[JsonIgnore]
public uint Length { get; private set; }
public MessageType Type { get; private set; }
public void ParseBytes(byte[] data)
{
Version = data[0];
//if (Version != 3)
//{
// throw new Exception("invalid BMP version");
//}
Length = data.ToUInt32(1);
Type = (MessageType) data[5];
}
}
} | mit | C# |
da750a74fc91d26ba39205201a33ac1d6b5b49fb | Add xmldoc mention of valid `OnlineID` values | smoogipoo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu,peppy/osu-new,smoogipoo/osu | osu.Game/Database/IHasOnlineID.cs | osu.Game/Database/IHasOnlineID.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.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. Any value 0 or less denotes a missing ID.
/// </summary>
/// <remarks>
/// Generally we use -1 when specifying "missing" in code, but values of 0 are also considered missing as the online source
/// is generally a MySQL autoincrement value, which can never be 0.
/// </remarks>
int OnlineID { get; }
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. -1 denotes a missing ID.
/// </summary>
int OnlineID { get; }
}
}
| mit | C# |
15fbca6b767bc629203c752607332cb6ecc738c5 | Tweak display of BloomMetadataEditorDialog (BL-7381) | BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop | src/BloomExe/Edit/BloomMetadataEditorDialog.cs | src/BloomExe/Edit/BloomMetadataEditorDialog.cs | using System;
using System.Windows.Forms;
using SIL.Windows.Forms.ClearShare;
using SIL.Windows.Forms.ClearShare.WinFormsUI;
using L10NSharp;
namespace Bloom.Edit
{
public class BloomMetadataEditorDialog : MetadataEditorDialog
{
public CheckBox _replaceCopyrightCheckbox;
public BloomMetadataEditorDialog(Metadata metadata, bool isDerivedBook) : base(metadata)
{
ShowCreator = false;
if (isDerivedBook)
{
this.SuspendLayout();
_replaceCopyrightCheckbox = new CheckBox();
_replaceCopyrightCheckbox.Text = LocalizationManager.GetString("EditTab.CopyrightThisDerivedVersion", "Copyright and license this translated version");
_replaceCopyrightCheckbox.Checked = true;
_replaceCopyrightCheckbox.CheckedChanged += ReplaceCopyrightCheckboxChanged;
_replaceCopyrightCheckbox.Location = new System.Drawing.Point(20,10);
_replaceCopyrightCheckbox.AutoSize = true;
var topPanel = new Panel();
topPanel.SuspendLayout();
topPanel.Dock = System.Windows.Forms.DockStyle.Top;
topPanel.AutoSize = true;
topPanel.Controls.Add(_replaceCopyrightCheckbox);
this.Controls.Add(topPanel);
this.Size = new System.Drawing.Size(this.Width, this.Height + topPanel.Height);
MetadataControl.BringToFront();
topPanel.ResumeLayout(false);
topPanel.PerformLayout();
this.ResumeLayout(false);
}
}
private void ReplaceCopyrightCheckboxChanged(Object sender, EventArgs e)
{
MetadataControl.Enabled = _replaceCopyrightCheckbox.Checked;
}
protected override void _minimallyCompleteCheckTimer_Tick(object sender, EventArgs e)
{
if (_replaceCopyrightCheckbox == null || _replaceCopyrightCheckbox.Checked)
base._minimallyCompleteCheckTimer_Tick(sender, e);
else
OkButton.Enabled = true;
}
public bool ReplaceOriginalCopyright
{
get { return (_replaceCopyrightCheckbox != null) ? _replaceCopyrightCheckbox.Checked : true; }
set
{
if (_replaceCopyrightCheckbox != null)
{
_replaceCopyrightCheckbox.Checked = value;
MetadataControl.Enabled = value;
}
}
}
}
}
| using System;
using System.Windows.Forms;
using SIL.Windows.Forms.ClearShare;
using SIL.Windows.Forms.ClearShare.WinFormsUI;
using L10NSharp;
namespace Bloom.Edit
{
public class BloomMetadataEditorDialog : MetadataEditorDialog
{
public CheckBox _replaceCopyrightCheckbox;
public BloomMetadataEditorDialog(Metadata metadata, bool isDerivedBook) : base(metadata)
{
ShowCreator = false;
if (isDerivedBook)
{
this.SuspendLayout();
_replaceCopyrightCheckbox = new CheckBox();
_replaceCopyrightCheckbox.Text = LocalizationManager.GetString("EditTab.CopyrightThisDerivedVersion", "Copyright and license this translated version");
_replaceCopyrightCheckbox.Checked = true;
_replaceCopyrightCheckbox.CheckedChanged += ReplaceCopyrightCheckboxChanged;
_replaceCopyrightCheckbox.Location = new System.Drawing.Point(20,10);
_replaceCopyrightCheckbox.AutoSize = true;
var topPanel = new Panel();
topPanel.SuspendLayout();
topPanel.Dock = System.Windows.Forms.DockStyle.Top;
topPanel.ClientSize = new System.Drawing.Size(347, 40);
topPanel.Controls.Add(_replaceCopyrightCheckbox);
this.Controls.Add(topPanel);
this.Size = new System.Drawing.Size(this.Width, this.Height + topPanel.Height);
MetadataControl.BringToFront();
topPanel.ResumeLayout(false);
topPanel.PerformLayout();
this.ResumeLayout(false);
}
}
private void ReplaceCopyrightCheckboxChanged(Object sender, EventArgs e)
{
MetadataControl.Enabled = _replaceCopyrightCheckbox.Checked;
}
protected override void _minimallyCompleteCheckTimer_Tick(object sender, EventArgs e)
{
if (_replaceCopyrightCheckbox == null || _replaceCopyrightCheckbox.Checked)
base._minimallyCompleteCheckTimer_Tick(sender, e);
else
OkButton.Enabled = true;
}
public bool ReplaceOriginalCopyright
{
get { return (_replaceCopyrightCheckbox != null) ? _replaceCopyrightCheckbox.Checked : true; }
set
{
if (_replaceCopyrightCheckbox != null)
{
_replaceCopyrightCheckbox.Checked = value;
MetadataControl.Enabled = value;
}
}
}
}
}
| mit | C# |
0925a8413bb672b9aac5d98bf0e19ccd6913c114 | fix get author by id | QubizSolutions/mvc5-ng2-material2,QubizSolutions/mvc5-ng2-material2,QubizSolutions/mvc5-ng2-material2,QubizSolutions/mvc5-ng2-material2 | src/DA/Repositories/Author/AuthorRepository.cs | src/DA/Repositories/Author/AuthorRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tesseract.DA.Author;
using Tesseract.DA.Author.Contract;
namespace Tesseract.DA.Repositories
{
public class AuthorRepository : BaseRepository<Author.Entity.Author>, IAuthorRepository
{
public AuthorRepository(AuthorsDBContext context, UnitOfWork unitOfWork)
: base(context, unitOfWork)
{ }
public void Create(AuthorContract author)
{
dbSet.Add(author.ToEntity());
}
public void Update(AuthorContract author)
{
Author.Entity.Author authorEntity = dbSet.FirstOrDefault(x => x.Id == author.Id);
dbSet.Attach(authorEntity);
authorEntity.FirstName = author.FirstName;
authorEntity.LastName = author.LastName;
authorEntity.BirthDate = author.BirthDate;
authorEntity.Country = author.Country;
dbContext.Entry(authorEntity).State = System.Data.Entity.EntityState.Modified;
}
public AuthorContract GetById(Guid id)
{
return dbSet.FirstOrDefault(x => x.Id == id).ToContract(true);
}
public AuthorContract[] ListAuthors()
{
Author.Entity.Author[] authors = dbSet.ToArray();
return authors.Select(x => x.ToContract(false)).ToArray();
}
public AuthorContract[] ListByIds(Guid[] ids)
{
return dbSet.Where(x => ids.Contains(x.Id)).Select(x => x.ToContract(false)).ToArray();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tesseract.DA.Author;
using Tesseract.DA.Author.Contract;
namespace Tesseract.DA.Repositories
{
public class AuthorRepository : BaseRepository<Author.Entity.Author>, IAuthorRepository
{
public AuthorRepository(AuthorsDBContext context, UnitOfWork unitOfWork)
: base(context, unitOfWork)
{ }
public void Create(AuthorContract author)
{
dbSet.Add(author.ToEntity());
}
public void Update(AuthorContract author)
{
Author.Entity.Author authorEntity = dbSet.FirstOrDefault(x => x.Id == author.Id);
dbSet.Attach(authorEntity);
authorEntity.FirstName = author.FirstName;
authorEntity.LastName = author.LastName;
authorEntity.BirthDate = author.BirthDate;
authorEntity.Country = author.Country;
dbContext.Entry(authorEntity).State = System.Data.Entity.EntityState.Modified;
}
public AuthorContract GetById(Guid id)
{
return dbSet.FirstOrDefault().ToContract(true);
}
public AuthorContract[] ListAuthors()
{
Author.Entity.Author[] authors = dbSet.ToArray();
return authors.Select(x => x.ToContract(false)).ToArray();
}
public AuthorContract[] ListByIds(Guid[] ids)
{
return dbSet.Where(x => ids.Contains(x.Id)).Select(x => x.ToContract(false)).ToArray();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.