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 |
|---|---|---|---|---|---|---|---|---|
65a2913dc5851222b4d17e0e0da23651d512a2a5 | Implement IDisposable | nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner | MultiMiner.Xgminer/Miner.cs | MultiMiner.Xgminer/Miner.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer
{
public class Miner : IDisposable
{
private Process minerProcess;
private readonly MinerConfig minerConfig;
public Miner(MinerConfig minerConfig)
{
this.minerConfig = minerConfig;
}
public List<Device> GetDevices()
{
List<Device> result = new List<Device>();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = minerConfig.ExecutablePath;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.Arguments = MinerParameter.EnumerateDevices;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
minerProcess = Process.Start(startInfo);
List<string> output = new List<string>();
while (!minerProcess.StandardOutput.EndOfStream)
{
string line = minerProcess.StandardOutput.ReadLine();
output.Add(line);
}
DeviceParser.ParseOutputForDevices(output, result);
return result;
}
public void Dispose()
{
if (minerProcess != null)
{
minerProcess.Dispose();
minerProcess = null;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace MultiMiner.Xgminer
{
public class Miner
{
private Process minerProcess;
private readonly MinerConfig minerConfig;
public Miner(MinerConfig minerConfig)
{
this.minerConfig = minerConfig;
}
public List<Device> GetDevices()
{
List<Device> result = new List<Device>();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = minerConfig.ExecutablePath;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.Arguments = MinerParameter.EnumerateDevices;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
minerProcess = Process.Start(startInfo);
List<string> output = new List<string>();
while (!minerProcess.StandardOutput.EndOfStream)
{
string line = minerProcess.StandardOutput.ReadLine();
output.Add(line);
}
DeviceParser.ParseOutputForDevices(output, result);
return result;
}
}
}
| mit | C# |
669395e404d4c639b08993c7d1b4bbc5cab64e55 | Add missing ReCaptcha TagHelper registration (#6886) | stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2 | src/OrchardCore/OrchardCore.ReCaptcha.Core/ServiceCollectionExtensions.cs | src/OrchardCore/OrchardCore.ReCaptcha.Core/ServiceCollectionExtensions.cs | using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OrchardCore.ReCaptcha.ActionFilters.Detection;
using OrchardCore.ReCaptcha.Configuration;
using OrchardCore.ReCaptcha.Services;
using OrchardCore.ReCaptcha.TagHelpers;
using Polly;
namespace OrchardCore.ReCaptcha.Core
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddReCaptcha(this IServiceCollection services, Action<ReCaptchaSettings> configure = null)
{
services.AddHttpClient<ReCaptchaClient>()
.AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(0.5 * attempt)));
services.AddTransient<IDetectRobots, IpAddressRobotDetector>();
services.AddTransient<IConfigureOptions<ReCaptchaSettings>, ReCaptchaSettingsConfiguration>();
services.AddTransient<ReCaptchaService>();
services.AddTagHelpers<ReCaptchaTagHelper>();
if (configure != null)
{
services.Configure(configure);
}
return services;
}
}
}
| using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OrchardCore.ReCaptcha.ActionFilters.Detection;
using OrchardCore.ReCaptcha.Configuration;
using OrchardCore.ReCaptcha.Services;
using Polly;
namespace OrchardCore.ReCaptcha.Core
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddReCaptcha(this IServiceCollection services, Action<ReCaptchaSettings> configure = null)
{
services.AddHttpClient<ReCaptchaClient>()
.AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(0.5 * attempt)));
services.AddTransient<IDetectRobots, IpAddressRobotDetector>();
services.AddTransient<IConfigureOptions<ReCaptchaSettings>, ReCaptchaSettingsConfiguration>();
services.AddTransient<ReCaptchaService>();
if (configure != null)
{
services.Configure(configure);
}
return services;
}
}
}
| bsd-3-clause | C# |
9ca0e06e9f752673074fbbddd0a9f43746d91e7c | Use GetAwaiter().GetResult() | stratisproject/NStratis | NBitcoin.Tests/WebClient.cs | NBitcoin.Tests/WebClient.cs | #if NOWEBCLIENT
using System;
using System.IO;
using System.Net.Http;
namespace NBitcoin.Tests
{
public class WebClient
{
public void DownloadFile(string url, string file)
{
HttpClient client = new HttpClient();
// The default value is 100,000 milliseconds (100 seconds) and
// that's not long enough to download Bitcoin on slower connections.
client.Timeout = TimeSpan.FromMinutes(5);
var bytes = client.GetByteArrayAsync(url).GetAwaiter().GetResult();
File.WriteAllBytes(file, bytes);
}
}
}
#endif | #if NOWEBCLIENT
using System;
using System.IO;
using System.Net.Http;
namespace NBitcoin.Tests
{
public class WebClient
{
public void DownloadFile(string url, string file)
{
HttpClient client = new HttpClient();
// The default value is 100,000 milliseconds (100 seconds).
// That's long enough to download Bitcoin.
client.Timeout = TimeSpan.FromMinutes(5);
// Changed .GetAwaiter().GetResult() to .Result
// https://stackoverflow.com/questions/17284517/is-task-result-the-same-as-getawaiter-getresult
var bytes = client.GetByteArrayAsync(url).Result;
File.WriteAllBytes(file, bytes);
}
}
}
#endif | mit | C# |
eef72b18f69e1c4eac444935621c1c75f0261698 | Bump version to v2.3.0 | rickyah/ini-parser,rickyah/ini-parser | src/IniFileParser/Properties/AssemblyInfo.cs | src/IniFileParser/Properties/AssemblyInfo.cs | using System.Reflection;
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("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.3.0")]
[assembly: AssemblyFileVersion("2.3.0")] | using System.Reflection;
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("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.2.4")]
[assembly: AssemblyFileVersion("2.2.4")] | mit | C# |
5121ff02263f88c72dcbe643c74f13485c074608 | Fix MapperBenchmarks interation count discrepancy | KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin | src/Kirkin.Tests/Mapping/MapperBenchmarks.cs | src/Kirkin.Tests/Mapping/MapperBenchmarks.cs | using AutoMapper;
using Kirkin.Mapping;
using Kirkin.Reflection;
using Xunit;
namespace Kirkin.Tests.Mapping
{
public class MapperBenchmarks
{
[Fact]
public void AutomapperClone()
{
MapperConfiguration config = new MapperConfiguration(c => c.CreateMap<Dummy, Dummy>());
IMapper mapper = config.CreateMapper();
Dummy source = new Dummy { ID = 1, Value = "Blah" };
for (int i = 0; i < 100000; i++) {
Dummy target = mapper.Map<Dummy>(source);
}
}
[Fact]
public void KirkinMapperStaticClone()
{
Dummy source = new Dummy { ID = 1, Value = "Blah" };
for (int i = 0; i < 100000; i++)
{
Dummy target = Kirkin.Mapping.Mapper.Clone(source);
}
}
[Fact]
public void KirkinMapperConfiguredAutomapClone()
{
Dummy source = new Dummy { ID = 1, Value = "Blah" };
IMapper<Dummy, Dummy> mapper = Kirkin.Mapping.Mapper.CreateMapper<Dummy, Dummy>();
for (int i = 0; i < 100000; i++) {
Dummy target = mapper.Map(source);
}
}
[Fact]
public void KirkinMapperConfiguredPropertyListClone()
{
Dummy source = new Dummy { ID = 1, Value = "Blah" };
Mapper<Dummy, Dummy> mapper = MapperBuilder
.FromPropertyList(PropertyList<Dummy>.Default)
.BuildMapper();
for (int i = 0; i < 100000; i++) {
Dummy target = mapper.Map(source);
}
}
sealed class Dummy
{
public int ID { get; set; }
public string Value { get; set; }
}
}
} | using AutoMapper;
using Kirkin.Mapping;
using Kirkin.Reflection;
using Xunit;
namespace Kirkin.Tests.Mapping
{
public class MapperBenchmarks
{
[Fact]
public void AutomapperClone()
{
MapperConfiguration config = new MapperConfiguration(c => c.CreateMap<Dummy, Dummy>());
IMapper mapper = config.CreateMapper();
Dummy source = new Dummy { ID = 1, Value = "Blah" };
for (int i = 0; i < 100000; i++) {
Dummy target = mapper.Map<Dummy>(source);
}
}
[Fact]
public void KirkinMapperStaticClone()
{
Dummy source = new Dummy { ID = 1, Value = "Blah" };
for (int i = 0; i < 1000000; i++)
{
Dummy target = Kirkin.Mapping.Mapper.Clone(source);
}
}
[Fact]
public void KirkinMapperConfiguredAutomapClone()
{
Dummy source = new Dummy { ID = 1, Value = "Blah" };
IMapper<Dummy, Dummy> mapper = Kirkin.Mapping.Mapper.CreateMapper<Dummy, Dummy>();
for (int i = 0; i < 100000; i++) {
Dummy target = mapper.Map(source);
}
}
[Fact]
public void KirkinMapperConfiguredPropertyListClone()
{
Dummy source = new Dummy { ID = 1, Value = "Blah" };
Mapper<Dummy, Dummy> mapper = MapperBuilder
.FromPropertyList(PropertyList<Dummy>.Default)
.BuildMapper();
for (int i = 0; i < 100000; i++) {
Dummy target = mapper.Map(source);
}
}
sealed class Dummy
{
public int ID { get; set; }
public string Value { get; set; }
}
}
} | mit | C# |
03f976c72b9aca11a6a305c674804eaa26132adc | Update EntityUnitOfWork.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityUnitOfWork.cs | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityUnitOfWork.cs | using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityUnitOfWork : UnitOfWorkBase
{
private readonly DbContext[] _dbContexts;
public EntityUnitOfWork(DbContext[] dbContexts) => this._dbContexts = dbContexts;
public override async Task CompleteAsync(CancellationToken cancellationToken)
{
var tasks = this._dbContexts.Select(dbContext => dbContext.SaveChangesAsync(cancellationToken)).ToArray();
_ = await Task.WhenAll(tasks).ConfigureAwait(false);
}
public override Task DiscardAsync(CancellationToken cancellationToken)
{
_ = this._dbContexts.Do(dbContext => dbContext.ChangeTracker.Clear());
return Task.CompletedTask;
}
protected override bool IsDirty() => this._dbContexts.Any(dbContext => dbContext.ChangeTracker.HasChanges());
}
}
| using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityUnitOfWork : UnitOfWorkBase
{
private readonly DbContext[] _dbContexts;
public EntityUnitOfWork(DbContext[] dbContexts) => this._dbContexts = dbContexts;
public override async Task CompleteAsync(CancellationToken cancellationToken)
{
var tasks = this._dbContexts.Select(dbContext => dbContext.SaveChangesAsync(cancellationToken)).ToArray();
await Task.WhenAll(tasks);
}
public override Task DiscardAsync(CancellationToken cancellationToken)
{
this._dbContexts.Do(dbContext => dbContext.ChangeTracker.Clear());
return Task.CompletedTask;
}
protected override bool IsDirty() => this._dbContexts.Any(dbContext => dbContext.ChangeTracker.HasChanges());
}
}
| mit | C# |
71cdeee501d87726c1aeee0eeff0cc93779c7706 | Clear IsBusy on Wallet load error | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs | WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs | using AvalonStudio.Extensibility;
using ReactiveUI;
using Splat;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class ClosedWalletViewModel : WalletViewModelBase
{
public ClosedWalletViewModel(Wallet wallet) : base(wallet)
{
OpenWalletCommand = ReactiveCommand.CreateFromTask(async () =>
{
IsBusy = true;
try
{
var global = Locator.Current.GetService<Global>();
if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None))
{
return;
}
await global.WalletManager.StartWalletAsync(Wallet);
}
catch (Exception e)
{
NotificationHelpers.Error($"Error loading Wallet: {Title}");
Logger.LogError(e.Message);
}
finally
{
IsBusy = false;
}
}, this.WhenAnyValue(x => x.IsBusy).Select(x => !x));
}
public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; }
}
}
| using AvalonStudio.Extensibility;
using ReactiveUI;
using Splat;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class ClosedWalletViewModel : WalletViewModelBase
{
public ClosedWalletViewModel(Wallet wallet) : base(wallet)
{
OpenWalletCommand = ReactiveCommand.CreateFromTask(async () =>
{
IsBusy = true;
try
{
var global = Locator.Current.GetService<Global>();
if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None))
{
return;
}
await global.WalletManager.StartWalletAsync(Wallet);
}
catch (Exception e)
{
NotificationHelpers.Error($"Error loading Wallet: {Title}");
Logger.LogError(e.Message);
}
}, this.WhenAnyValue(x => x.IsBusy).Select(x => !x));
}
public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; }
}
}
| mit | C# |
e2090024f64425ca2318212398feea05761ab99d | Make the new InvalidPatternException constructor internal, and give it some documentation. | zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,malcolmr/nodatime,zaccharles/nodatime,malcolmr/nodatime,nodatime/nodatime,jskeet/nodatime,zaccharles/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,jskeet/nodatime,nodatime/nodatime,zaccharles/nodatime,malcolmr/nodatime | src/NodaTime/Text/InvalidPatternException.cs | src/NodaTime/Text/InvalidPatternException.cs | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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.
#endregion
using System;
using System.Globalization;
#if !PCL
using System.Runtime.Serialization;
#endif
namespace NodaTime.Text
{
/// <summary>
/// Exception thrown to indicate that the format pattern provided for either formatting or parsing is invalid.
/// </summary>
/// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
/// See the thread safety section of the user guide for more information.
/// </threadsafety>
#if !PCL
[Serializable]
#endif
public sealed class InvalidPatternException : FormatException
{
/// <summary>
/// Creates a new InvalidPatternException with no message.
/// </summary>
public InvalidPatternException()
{
}
/// <summary>
/// Creates a new InvalidPatternException with the given message.
/// </summary>
/// <param name="message">A message describing the nature of the failure</param>
public InvalidPatternException(string message)
: base(message)
{
}
/// <summary>
/// Creates a new InvalidPatternException by formatting the given format string with
/// the specified parameters, in the current culture.
/// </summary>
/// <param name="formatString">Format string to use in order to create the final message</param>
/// <param name="parameters">Format string parameters</param>
internal InvalidPatternException(string formatString, params object[] parameters)
: this(string.Format(CultureInfo.CurrentCulture, formatString, parameters))
{
}
#if !PCL
/// <summary>
/// Creates a new InvalidPatternException from the given serialization information.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
private InvalidPatternException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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.
#endregion
using System;
using System.Globalization;
#if !PCL
using System.Runtime.Serialization;
#endif
namespace NodaTime.Text
{
/// <summary>
/// Exception thrown to indicate that the format pattern provided for either formatting or parsing is invalid.
/// </summary>
/// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
/// See the thread safety section of the user guide for more information.
/// </threadsafety>
#if !PCL
[Serializable]
#endif
public sealed class InvalidPatternException : FormatException
{
/// <summary>
/// Creates a new InvalidPatternException with no message.
/// </summary>
public InvalidPatternException()
{
}
/// <summary>
/// Creates a new InvalidPatternException with the given message.
/// </summary>
/// <param name="message">A message describing the nature of the failure</param>
public InvalidPatternException(string message)
: base(message)
{
}
public InvalidPatternException(string formatString, params object[] parameters)
: this(string.Format(CultureInfo.CurrentCulture, formatString, parameters))
{
}
#if !PCL
/// <summary>
/// Creates a new InvalidPatternException from the given serialization information.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
private InvalidPatternException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| apache-2.0 | C# |
df14fc6fb14aff5b0b516c3629ea6d2b4f650864 | Add AssemblyInformationVersion for nuget. | chariothy/MultiTargetFrameworkDemo,chariothy/MultiTargetFrameworkDemo | MultiTarget/Properties/AssemblyInfo.cs | MultiTarget/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("MultiTarget")]
[assembly: AssemblyDescription("Demonstration of how to build multi-targeting project.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Chariothy")]
[assembly: AssemblyProduct("MultiTarget")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("e2f59451-687b-4033-bf44-5cf65689601d")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.2")] | 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("MultiTarget")]
[assembly: AssemblyDescription("Demonstration of how to build multi-targeting project.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Chariothy")]
[assembly: AssemblyProduct("MultiTarget")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("e2f59451-687b-4033-bf44-5cf65689601d")]
// 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.1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
f04abecf2f27c5ee84f57ff44d41b14aea8556d4 | use GetComponentInParent() instead | yasokada/unity-150912-findParentCanvasOfPanel | Assets/FindParentCanvas.cs | Assets/FindParentCanvas.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.2 2015/09/15
* - brush up getMyParentCanvasName() by using GetComponentInParent()
* v0.1 2015/09/12
* - getMyParentCanvasName() worked as expected
*/
public class FindParentCanvas : MonoBehaviour {
string getMyParentCanvasName(GameObject panel) {
return panel.GetComponentInParent<Canvas>().name;
}
void Test_each(string name) {
GameObject myPanel = GameObject.Find (name);
string canvasName = getMyParentCanvasName (myPanel);
Debug.Log (canvasName + " - " + myPanel.name);
}
void Test_main() {
Test_each ("Panel_1");
Test_each ("Panel_1_1");
Test_each ("Panel_1_2_1");
Test_each ("Panel_2");
Test_each ("Panel_2_1");
Test_each ("Panel_2_2_1");
}
void Start () {
Test_main ();
}
}
| using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.1 2015/09/12
* - getMyParentCanvasName() worked as expected
*/
public class FindParentCanvas : MonoBehaviour {
string getMyParentCanvasName(GameObject panel) {
GameObject parentGO;
GameObject targetGO = panel;
for (int loop=0; loop<3; loop++) { // search upper three levels
parentGO = targetGO.transform.parent.gameObject;
if (parentGO.GetComponent<Canvas> () != null) {
return parentGO.name;
}
targetGO = parentGO;
}
return "";
}
void Test_each(string name) {
GameObject myPanel = GameObject.Find (name);
string canvasName = getMyParentCanvasName (myPanel);
Debug.Log (canvasName + " - " + myPanel.name);
}
void Test_main() {
Test_each ("Panel_1");
Test_each ("Panel_1_1");
Test_each ("Panel_1_2_1");
Test_each ("Panel_2");
Test_each ("Panel_2_1");
Test_each ("Panel_2_2_1");
}
void Start () {
Test_main ();
}
}
| mit | C# |
4306e89e1567a640d16c7c29943c16e618457d72 | fix issue where rrp is not zero and price is zero, we only care about price being zero to indicate a free item | danbadge/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,actionshrimp/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Schema/Pricing/Price.cs | src/SevenDigital.Api.Schema/Pricing/Price.cs | using System;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Pricing
{
[XmlRoot("price")]
[Serializable]
public class Price
{
[XmlElement("currency")]
public Currency Currency { get; set; }
[XmlElement("value")]
public string Value { get; set; }
[XmlElement("formattedPrice")]
public string FormattedPrice { get; set; }
[XmlElement("rrp")]
public string Rrp { get; set; }
[XmlElement("formattedRrp")]
public string FormattedRrp { get; set; }
[XmlElement("onSale")]
public bool IsOnSale { get; set; }
public PriceStatus Status
{
get
{
if (PriceIsZero())
return PriceStatus.Free;
if(string.IsNullOrEmpty(Value) && FormattedPrice == "N/A")
return PriceStatus.UnAvailable;
return PriceStatus.Available;
}
}
private bool PriceIsZero()
{
decimal value;
if (decimal.TryParse(Value, out value))
return value == 0;
return false;
}
}
} | using System;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Pricing
{
[XmlRoot("price")]
[Serializable]
public class Price
{
[XmlElement("currency")]
public Currency Currency { get; set; }
[XmlElement("value")]
public string Value { get; set; }
[XmlElement("formattedPrice")]
public string FormattedPrice { get; set; }
[XmlElement("rrp")]
public string Rrp { get; set; }
[XmlElement("formattedRrp")]
public string FormattedRrp { get; set; }
[XmlElement("onSale")]
public bool IsOnSale { get; set; }
public PriceStatus Status
{
get
{
if (Value == "0" && Rrp == "0")
return PriceStatus.Free;
if(string.IsNullOrEmpty(Value) && FormattedPrice == "N/A")
return PriceStatus.UnAvailable;
return PriceStatus.Available;
}
}
}
} | mit | C# |
e742615ab7dc90a7d6cc4a0f7d772a39e97c878d | Improve test | David-Desmaisons/EasyActor | Concurrent.Test/Dispatchers/RateLimiterDispatcherTests.cs | Concurrent.Test/Dispatchers/RateLimiterDispatcherTests.cs | using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Concurrent.Dispatchers;
using FluentAssertions;
using RateLimiter;
using Xunit;
using Xunit.Abstractions;
namespace Concurrent.Test.Dispatchers
{
public class RateLimiterDispatcherTests
{
private readonly RateLimiterDispatcher _RateLimiterDispatcher;
private readonly ITestOutputHelper _TestOutput;
private const int Interval = 200;
public RateLimiterDispatcherTests(ITestOutputHelper testOutput)
{
_TestOutput = testOutput;
var limiter = new CountByIntervalAwaitableConstraint(1, TimeSpan.FromMilliseconds(Interval));
_RateLimiterDispatcher = new RateLimiterDispatcher(limiter);
}
[Fact]
public async Task Dispatcher_Limit_Number_Of_Call()
{
var count = 0;
var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(700));
var stopWatch = Stopwatch.StartNew();
_TestOutput.WriteLine($"Start: {DateTime.Now:O}");
while (!cancellationTokenSource.IsCancellationRequested)
{
await _RateLimiterDispatcher.SwitchToContext();
if (cancellationTokenSource.IsCancellationRequested)
break;
count++;
_TestOutput.WriteLine($"Doing: {DateTime.Now:O}");
}
stopWatch.Stop();
var numberOfCall = (int) (Math.Truncate((decimal)stopWatch.ElapsedMilliseconds / Interval));
_TestOutput.WriteLine($"Ended: {DateTime.Now:O}");
_TestOutput.WriteLine($"Count:{count}, Time spend: {stopWatch.Elapsed}");
count.Should().Be(numberOfCall);
}
}
}
| using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Concurrent.Dispatchers;
using FluentAssertions;
using RateLimiter;
using Xunit;
using Xunit.Abstractions;
namespace Concurrent.Test.Dispatchers
{
public class RateLimiterDispatcherTests
{
private readonly RateLimiterDispatcher _RateLimiterDispatcher;
private readonly ITestOutputHelper _TestOutput;
public RateLimiterDispatcherTests(ITestOutputHelper testOutput)
{
_TestOutput = testOutput;
var limiter = new CountByIntervalAwaitableConstraint(1, TimeSpan.FromMilliseconds(200));
_RateLimiterDispatcher = new RateLimiterDispatcher(limiter);
}
[Fact]
public async Task Dispatcher_Limit_Number_Of_Call()
{
var count = 0;
var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(700));
var stopWatch = Stopwatch.StartNew();
_TestOutput.WriteLine($"Start: {DateTime.Now:O}");
while (!cancellationTokenSource.IsCancellationRequested)
{
await _RateLimiterDispatcher.SwitchToContext();
if (cancellationTokenSource.IsCancellationRequested)
break;
count++;
_TestOutput.WriteLine($"Doing: {DateTime.Now:O}");
}
stopWatch.Stop();
_TestOutput.WriteLine($"Ended: {DateTime.Now:O}");
_TestOutput.WriteLine($"Count:{count}, Time spend: {stopWatch.Elapsed}");
count.Should().Be(4);
}
}
}
| mit | C# |
768d9a57e48ba2a6a32c908b9381383b9793c015 | Update OpeningFilesThroughPath.cs | aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Files/Handling/OpeningFilesThroughPath.cs | Examples/CSharp/Files/Handling/OpeningFilesThroughPath.cs | using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningFilesThroughPath
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening through Path
//Creating a Workbook object and opening an Excel file using its file path
Workbook workbook1 = new Workbook(dataDir + "Book1.xls");
Console.WriteLine("Workbook opened using path successfully!");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningFilesThroughPath
{
public static void Main(string[] args)
{
//Exstart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening through Path
//Creating a Workbook object and opening an Excel file using its file path
Workbook workbook1 = new Workbook(dataDir + "Book1.xls");
Console.WriteLine("Workbook opened using path successfully!");
//ExEnd:1
}
}
}
| mit | C# |
fdc05abd9feeb0cdeb4a380bf919fa62a98a6342 | Check account call. | bchavez/Coinbase | Source/Coinbase.Tests/Integration/IntegrationTests.cs | Source/Coinbase.Tests/Integration/IntegrationTests.cs | using System.IO;
using System.Net;
using System.Threading.Tasks;
using Flurl.Http;
using NUnit.Framework;
using Z.ExtensionMethods;
namespace Coinbase.Tests.Integration
{
[Explicit]
public class IntegrationTests
{
protected CoinbaseApi client;
public IntegrationTests()
{
Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(IntegrationTests).Assembly.Location));
var lines = File.ReadAllLines("../../.secrets.txt");
var apiKey = lines[0].GetAfter(":");
var apiSecret = lines[1].GetAfter(":");
var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);
FlurlHttp.Configure(settings =>
{
settings.HttpClientFactory = new ProxyFactory(webProxy);
});
client = new CoinbaseApi(new ApiKeyConfig{ ApiKey = apiKey, ApiSecret = apiSecret});
}
}
[Explicit]
public class UserTests : IntegrationTests
{
[Test]
public async Task can_get_auths()
{
var r = await client.Users.GetAuthInfoAsync();
r.Dump();
}
[Test]
public async Task check_account_list()
{
var r = await client.Accounts.ListAccountsAsync();
r.Dump();
}
}
} | using System.IO;
using System.Net;
using System.Threading.Tasks;
using Flurl.Http;
using NUnit.Framework;
using Z.ExtensionMethods;
namespace Coinbase.Tests.Integration
{
[Explicit]
public class IntegrationTests
{
protected CoinbaseApi client;
public IntegrationTests()
{
Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(IntegrationTests).Assembly.Location));
var lines = File.ReadAllLines("../../.secrets.txt");
var apiKey = lines[0].GetAfter(":");
var apiSecret = lines[1].GetAfter(":");
var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);
FlurlHttp.Configure(settings =>
{
settings.HttpClientFactory = new ProxyFactory(webProxy);
});
client = new CoinbaseApi(new ApiKeyConfig{ ApiKey = apiKey, ApiSecret = apiSecret});
}
}
[Explicit]
public class UserTests : IntegrationTests
{
[Test]
public async Task can_get_auths()
{
var r = await client.Users.GetAuthInfoAsync();
r.Dump();
}
}
} | mit | C# |
f6cdb389f81e435d2767199636a5108395a2003e | Set correct output type for RemoveRoleDefinition | juvchan/azure-powershell,hallihan/azure-powershell,TaraMeyer/azure-powershell,PashaPash/azure-powershell,yadavbdev/azure-powershell,jianghaolu/azure-powershell,tonytang-microsoft-com/azure-powershell,PashaPash/azure-powershell,zaevans/azure-powershell,hallihan/azure-powershell,arcadiahlyy/azure-powershell,ClogenyTechnologies/azure-powershell,atpham256/azure-powershell,yoavrubin/azure-powershell,oaastest/azure-powershell,SarahRogers/azure-powershell,seanbamsft/azure-powershell,nickheppleston/azure-powershell,alfantp/azure-powershell,akurmi/azure-powershell,kagamsft/azure-powershell,enavro/azure-powershell,jianghaolu/azure-powershell,akurmi/azure-powershell,juvchan/azure-powershell,CamSoper/azure-powershell,pomortaz/azure-powershell,praveennet/azure-powershell,jianghaolu/azure-powershell,SarahRogers/azure-powershell,hovsepm/azure-powershell,seanbamsft/azure-powershell,bgold09/azure-powershell,atpham256/azure-powershell,enavro/azure-powershell,jtlibing/azure-powershell,seanbamsft/azure-powershell,zhencui/azure-powershell,yantang-msft/azure-powershell,pelagos/azure-powershell,oaastest/azure-powershell,hallihan/azure-powershell,kagamsft/azure-powershell,nickheppleston/azure-powershell,nickheppleston/azure-powershell,TaraMeyer/azure-powershell,Matt-Westphal/azure-powershell,jasper-schneider/azure-powershell,chef-partners/azure-powershell,zaevans/azure-powershell,rohmano/azure-powershell,hallihan/azure-powershell,ClogenyTechnologies/azure-powershell,dominiqa/azure-powershell,ClogenyTechnologies/azure-powershell,DeepakRajendranMsft/azure-powershell,dulems/azure-powershell,jasper-schneider/azure-powershell,stankovski/azure-powershell,akurmi/azure-powershell,mayurid/azure-powershell,yoavrubin/azure-powershell,Matt-Westphal/azure-powershell,stankovski/azure-powershell,pelagos/azure-powershell,enavro/azure-powershell,krkhan/azure-powershell,AzureRT/azure-powershell,ClogenyTechnologies/azure-powershell,seanbamsft/azure-powershell,tonytang-microsoft-com/azure-powershell,dulems/azure-powershell,chef-partners/azure-powershell,mayurid/azure-powershell,krkhan/azure-powershell,devigned/azure-powershell,krkhan/azure-powershell,jtlibing/azure-powershell,praveennet/azure-powershell,stankovski/azure-powershell,hallihan/azure-powershell,jtlibing/azure-powershell,ankurchoubeymsft/azure-powershell,pelagos/azure-powershell,rohmano/azure-powershell,tonytang-microsoft-com/azure-powershell,ClogenyTechnologies/azure-powershell,ankurchoubeymsft/azure-powershell,dulems/azure-powershell,jtlibing/azure-powershell,dulems/azure-powershell,atpham256/azure-powershell,haocs/azure-powershell,oaastest/azure-powershell,haocs/azure-powershell,TaraMeyer/azure-powershell,PashaPash/azure-powershell,jasper-schneider/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,jasper-schneider/azure-powershell,enavro/azure-powershell,pankajsn/azure-powershell,DeepakRajendranMsft/azure-powershell,kagamsft/azure-powershell,bgold09/azure-powershell,pankajsn/azure-powershell,chef-partners/azure-powershell,juvchan/azure-powershell,SarahRogers/azure-powershell,rohmano/azure-powershell,tonytang-microsoft-com/azure-powershell,hovsepm/azure-powershell,chef-partners/azure-powershell,zaevans/azure-powershell,arcadiahlyy/azure-powershell,rhencke/azure-powershell,pelagos/azure-powershell,PashaPash/azure-powershell,chef-partners/azure-powershell,dominiqa/azure-powershell,ankurchoubeymsft/azure-powershell,arcadiahlyy/azure-powershell,kagamsft/azure-powershell,zhencui/azure-powershell,ailn/azure-powershell,jianghaolu/azure-powershell,AzureRT/azure-powershell,haocs/azure-powershell,akurmi/azure-powershell,Matt-Westphal/azure-powershell,pomortaz/azure-powershell,arcadiahlyy/azure-powershell,praveennet/azure-powershell,ailn/azure-powershell,alfantp/azure-powershell,hungmai-msft/azure-powershell,rhencke/azure-powershell,oaastest/azure-powershell,devigned/azure-powershell,yantang-msft/azure-powershell,zaevans/azure-powershell,praveennet/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,alfantp/azure-powershell,zaevans/azure-powershell,enavro/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,yantang-msft/azure-powershell,hovsepm/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,krkhan/azure-powershell,dulems/azure-powershell,shuagarw/azure-powershell,yantang-msft/azure-powershell,mayurid/azure-powershell,shuagarw/azure-powershell,naveedaz/azure-powershell,SarahRogers/azure-powershell,dominiqa/azure-powershell,oaastest/azure-powershell,pankajsn/azure-powershell,ailn/azure-powershell,rhencke/azure-powershell,atpham256/azure-powershell,bgold09/azure-powershell,pelagos/azure-powershell,haocs/azure-powershell,jtlibing/azure-powershell,haocs/azure-powershell,hovsepm/azure-powershell,atpham256/azure-powershell,DeepakRajendranMsft/azure-powershell,pankajsn/azure-powershell,rhencke/azure-powershell,zhencui/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,yantang-msft/azure-powershell,devigned/azure-powershell,seanbamsft/azure-powershell,nickheppleston/azure-powershell,bgold09/azure-powershell,jasper-schneider/azure-powershell,zhencui/azure-powershell,arcadiahlyy/azure-powershell,yadavbdev/azure-powershell,naveedaz/azure-powershell,SarahRogers/azure-powershell,TaraMeyer/azure-powershell,zhencui/azure-powershell,nemanja88/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,CamSoper/azure-powershell,kagamsft/azure-powershell,rohmano/azure-powershell,CamSoper/azure-powershell,dominiqa/azure-powershell,CamSoper/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,CamSoper/azure-powershell,pomortaz/azure-powershell,DeepakRajendranMsft/azure-powershell,ankurchoubeymsft/azure-powershell,tonytang-microsoft-com/azure-powershell,hungmai-msft/azure-powershell,pomortaz/azure-powershell,AzureRT/azure-powershell,stankovski/azure-powershell,yadavbdev/azure-powershell,dominiqa/azure-powershell,shuagarw/azure-powershell,rhencke/azure-powershell,yadavbdev/azure-powershell,ankurchoubeymsft/azure-powershell,alfantp/azure-powershell,hovsepm/azure-powershell,zhencui/azure-powershell,juvchan/azure-powershell,yoavrubin/azure-powershell,Matt-Westphal/azure-powershell,alfantp/azure-powershell,nemanja88/azure-powershell,AzureRT/azure-powershell,nemanja88/azure-powershell,nemanja88/azure-powershell,juvchan/azure-powershell,AzureAutomationTeam/azure-powershell,yoavrubin/azure-powershell,akurmi/azure-powershell,praveennet/azure-powershell,yantang-msft/azure-powershell,ailn/azure-powershell,shuagarw/azure-powershell,AzureAutomationTeam/azure-powershell,nemanja88/azure-powershell,seanbamsft/azure-powershell,Matt-Westphal/azure-powershell,mayurid/azure-powershell,ailn/azure-powershell,DeepakRajendranMsft/azure-powershell,pomortaz/azure-powershell,yadavbdev/azure-powershell,jianghaolu/azure-powershell,bgold09/azure-powershell,AzureRT/azure-powershell,TaraMeyer/azure-powershell,hungmai-msft/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,atpham256/azure-powershell,AzureAutomationTeam/azure-powershell,stankovski/azure-powershell,mayurid/azure-powershell,PashaPash/azure-powershell,hungmai-msft/azure-powershell,AzureRT/azure-powershell,AzureAutomationTeam/azure-powershell,nickheppleston/azure-powershell,shuagarw/azure-powershell,yoavrubin/azure-powershell | src/ResourceManager/Resources/Commands.Resources/RoleDefinitions/RemoveAzureRoleDefinitionCommand.cs | src/ResourceManager/Resources/Commands.Resources/RoleDefinitions/RemoveAzureRoleDefinitionCommand.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 System.Management.Automation;
using Microsoft.Azure.Commands.Resources.Models;
using Microsoft.Azure.Commands.Resources.Models.Authorization;
using ProjectResources = Microsoft.Azure.Commands.Resources.Properties.Resources;
namespace Microsoft.Azure.Commands.Resources
{
/// <summary>
/// Deletes a given role definition.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "AzureRoleDefinition"), OutputType(typeof(PSRoleDefinition))]
public class RemoveAzureRoleDefinitionCommand : ResourcesBaseCmdlet
{
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Role definition id.")]
public string Id { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter Force { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter PassThru { get; set; }
public override void ExecuteCmdlet()
{
PSRoleDefinition roleDefinition = null;
ConfirmAction(
Force.IsPresent,
string.Format(ProjectResources.RemoveRoleDefinition, Id),
ProjectResources.RemoveRoleDefinition,
Id,
() => roleDefinition = PoliciesClient.RemoveRoleDefinition(Id));
if (PassThru)
{
WriteObject(roleDefinition);
}
}
}
}
| // ----------------------------------------------------------------------------------
//
// 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 System.Management.Automation;
using Microsoft.Azure.Commands.Resources.Models;
using Microsoft.Azure.Commands.Resources.Models.Authorization;
using ProjectResources = Microsoft.Azure.Commands.Resources.Properties.Resources;
namespace Microsoft.Azure.Commands.Resources
{
/// <summary>
/// Deletes a given role definition.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "AzureRoleDefinition"), OutputType(typeof(bool))]
public class RemoveAzureRoleDefinitionCommand : ResourcesBaseCmdlet
{
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Role definition id.")]
public string Id { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter Force { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter PassThru { get; set; }
public override void ExecuteCmdlet()
{
PSRoleDefinition roleDefinition = null;
ConfirmAction(
Force.IsPresent,
string.Format(ProjectResources.RemoveRoleDefinition, Id),
ProjectResources.RemoveRoleDefinition,
Id,
() => roleDefinition = PoliciesClient.RemoveRoleDefinition(Id));
if (PassThru)
{
WriteObject(roleDefinition);
}
}
}
}
| apache-2.0 | C# |
c75d2eae7d5c7093595af8b6346612d6c14d195d | fix Entourage test | HearthSim/HearthDb | HearthDb.Tests/UnitTest1.cs | HearthDb.Tests/UnitTest1.cs | #region
using HearthDb.Enums;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endregion
namespace HearthDb.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void BasicTest()
{
Assert.AreEqual("Flame Lance", Cards.All["AT_001"].Name);
Assert.AreEqual("Flammenlanze", Cards.All["AT_001"].GetLocName(Locale.deDE));
Assert.AreEqual("Nutthapon Petchthai", Cards.All["AT_001"].ArtistName);
Assert.AreEqual(CardSet.TGT, Cards.All["AT_001"].Set);
Assert.AreEqual(true, Cards.All["AT_001"].Collectible);
Assert.AreEqual(Rarity.COMMON, Cards.All["AT_001"].Rarity);
Assert.AreEqual(CardClass.MAGE, Cards.All["AT_001"].Class);
Assert.AreEqual(5, Cards.All["AT_001"].Cost);
Assert.AreEqual(0, Cards.All["AT_001"].Attack);
}
[TestMethod]
public void EntourageCardTest()
{
var animalCompanion = Cards.Collectible[CardIds.Collectible.Hunter.AnimalCompanion];
Assert.AreEqual(3, animalCompanion.EntourageCardIds.Length);
Assert.AreEqual(CardIds.NonCollectible.Hunter.Misha, animalCompanion.EntourageCardIds[0]);
Assert.AreEqual(CardIds.NonCollectible.Hunter.Leokk, animalCompanion.EntourageCardIds[1]);
}
[TestMethod]
public void EntourageCardTest_AnimalCompanion()
{
var animalCompanion = Cards.Collectible[CardIds.Collectible.Hunter.AnimalCompanion];
Assert.AreEqual(3, animalCompanion.EntourageCardIds.Length);
}
[TestMethod]
public void IgnoreCaseTest()
{
var c1 = Cards.GetFromName("Flame Lance", Locale.enUS);
var c2 = Cards.GetFromName("FLAME LANCE", Locale.enUS);
var c3 = Cards.GetFromName("flame lance", Locale.enUS);
var c4 = Cards.GetFromName("FlAmE lAnCe", Locale.enUS);
Assert.AreEqual(c1, c2);
Assert.AreEqual(c2, c3);
Assert.AreEqual(c3, c4);
}
}
} | #region
using HearthDb.Enums;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endregion
namespace HearthDb.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void BasicTest()
{
Assert.AreEqual("Flame Lance", Cards.All["AT_001"].Name);
Assert.AreEqual("Flammenlanze", Cards.All["AT_001"].GetLocName(Locale.deDE));
Assert.AreEqual("Nutthapon Petchthai", Cards.All["AT_001"].ArtistName);
Assert.AreEqual(CardSet.TGT, Cards.All["AT_001"].Set);
Assert.AreEqual(true, Cards.All["AT_001"].Collectible);
Assert.AreEqual(Rarity.COMMON, Cards.All["AT_001"].Rarity);
Assert.AreEqual(CardClass.MAGE, Cards.All["AT_001"].Class);
Assert.AreEqual(5, Cards.All["AT_001"].Cost);
Assert.AreEqual(0, Cards.All["AT_001"].Attack);
}
[TestMethod]
public void EntourageCardTest()
{
var animalCompanion = Cards.Collectible[CardIds.Collectible.Hunter.AnimalCompanion];
Assert.AreEqual(3, animalCompanion.EntourageCardIds.Length);
Assert.AreEqual(CardIds.NonCollectible.Hunter.Misha, animalCompanion.EntourageCardIds[0]);
Assert.AreEqual(CardIds.NonCollectible.Hunter.Leokk, animalCompanion.EntourageCardIds[1]);
}
[TestMethod]
public void EntourageCardTest_BaneOfDoom()
{
var baneOfDoom = Cards.Collectible[CardIds.Collectible.Warlock.BaneOfDoom];
Assert.AreEqual(6, baneOfDoom.EntourageCardIds.Length);
}
[TestMethod]
public void IgnoreCaseTest()
{
var c1 = Cards.GetFromName("Flame Lance", Locale.enUS);
var c2 = Cards.GetFromName("FLAME LANCE", Locale.enUS);
var c3 = Cards.GetFromName("flame lance", Locale.enUS);
var c4 = Cards.GetFromName("FlAmE lAnCe", Locale.enUS);
Assert.AreEqual(c1, c2);
Assert.AreEqual(c2, c3);
Assert.AreEqual(c3, c4);
}
}
} | mit | C# |
817f02089fcb826d4fa8994333ed27731dd83df8 | fix S_DUNGEON_COOL_TIME_LIST again | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Parsing/Messages/S_DUNGEON_COOL_TIME_LIST.cs | TCC.Core/Parsing/Messages/S_DUNGEON_COOL_TIME_LIST.cs | using System;
using System.Collections.Generic;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class S_DUNGEON_COOL_TIME_LIST : ParsedMessage
{
public readonly Dictionary<uint, short> DungeonCooldowns;
public S_DUNGEON_COOL_TIME_LIST(TeraMessageReader reader) : base(reader)
{
DungeonCooldowns = new Dictionary<uint, short>();
try
{
reader.RepositionAt(4);
var count = reader.ReadUInt16();
reader.Skip(2); //var offset = reader.ReadUInt16();
reader.Skip(4);
for (var i = 0; i < count; i++)
{
var curr = reader.ReadUInt16();
var next = reader.ReadUInt16();
var id = reader.ReadUInt32();
reader.Skip(8);
var daily = reader.ReadInt16();
var weekly = reader.ReadInt16();
var entries = (short) (daily == -1 ? weekly == -1 ? -1 : weekly : daily);
if(entries != -1) DungeonCooldowns[id] = entries;
if (next == 0) return;
reader.RepositionAt(next);
}
}
catch (System.Exception)
{
Log.F($"[S_DUNGEON_COOL_TIME_LIST] Failed to parse packet");
}
}
}
}
| using System.Collections.Generic;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class S_DUNGEON_COOL_TIME_LIST : ParsedMessage
{
public readonly Dictionary<uint, short> DungeonCooldowns;
public S_DUNGEON_COOL_TIME_LIST(TeraMessageReader reader) : base(reader)
{
DungeonCooldowns = new Dictionary<uint, short>();
try
{
var count = reader.ReadUInt16();
reader.Skip(2); //var offset = reader.ReadUInt16();
reader.Skip(4);
for (var i = 0; i < count; i++)
{
reader.Skip(2);
var next = reader.ReadUInt16();
var id = reader.ReadUInt32();
reader.Skip(10);
var entries = reader.ReadInt16();
DungeonCooldowns.Add(id, entries);
if (next == 0) return;
reader.RepositionAt(next);
}
}
catch (System.Exception)
{
Log.F($"[S_DUNGEON_COOL_TIME_LIST] Failed to parse packet");
}
}
}
}
| mit | C# |
427cf8cf771901ee56d9f92e7977e5c03b0b99a3 | Fix error? | Vytek/HazelTestUDPClientUnity | Assets/Scripts/NetworkCube.cs | Assets/Scripts/NetworkCube.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NetworkCube : MonoBehaviour {
//The ID of the client that owns this player (so we can check if it's us updating)
public ushort objectID;
public bool DEBUG = true;
Vector3 lastPosition = Vector3.zero;
Vector3 nextPosition = Vector3.zero;
Quaternion lastRotation = Quaternion.identity;
Quaternion nextRotation = Quaternion.identity;
Vector3 lastScale;
// Use this for initialization
void Start () {
NetworkManager.OnReceiveMessageFromGameObjectUpdate += NetworkManager_OnReceiveMessageFromGameObjectUpdate;
//Initialize
lastPosition = transform.position;
lastRotation = transform.rotation;
}
public IEnumerator ThisWillBeExecutedOnTheMainThread()
{
Debug.Log("This is executed from the main thread");
//transform.position = new Vector3(newMessage.GameObjectPos.x, newMessage.GameObjectPos.y, newMessage.GameObjectPos.z);
lastPosition = nextPosition;
transform.position = nextPosition;
lastRotation = nextRotation;
transform.rotation = nextRotation;
//Add rotation
yield return null;
}
void NetworkManager_OnReceiveMessageFromGameObjectUpdate (NetworkManager.ReceiveMessageFromGameObject newMessage)
{
Debug.Log ("Raise event in GameObject");
Debug.Log (newMessage.MessageType);
Debug.Log (newMessage.GameObjectID);
Debug.Log (newMessage.GameObjectPos);
Debug.Log (newMessage.GameObjectRot);
//Update pos and rot
if (newMessage.GameObjectID == objectID)
{
nextPosition = new Vector3(newMessage.GameObjectPos.x, newMessage.GameObjectPos.y, newMessage.GameObjectPos.z);
nextRotation = new Quaternion(newMessage.GameObjectRot.x, newMessage.GameObjectRot.y, newMessage.GameObjectRot.z, newMessage.GameObjectRot.w);
UnityMainThreadDispatcher.Instance().Enqueue(ThisWillBeExecutedOnTheMainThread());
}
}
// Update is called once per frame
void Update () {
if ((Vector3.Distance(transform.position, lastPosition) > 0.05) || (Quaternion.Angle(transform.rotation, lastRotation) > 0.3))
{
NetworkManager.instance.SendMessage(NetworkManager.SendType.SENDTOOTHER, NetworkManager.PacketId.OBJECT_MOVE, this.objectID, transform.position, transform.rotation);
//Update stuff
lastPosition = transform.position;
lastRotation = transform.rotation;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NetworkCube : MonoBehaviour {
//The ID of the client that owns this player (so we can check if it's us updating)
public ushort objectID;
public bool DEBUG = true;
Vector3 lastPosition = Vector3.zero;
Vector3 nextPosition = Vector3.zero;
Quaternion lastRotation = Quaternion.identity;
Quaternion nextRotation = Quaternion.identity;
Vector3 lastScale;
// Use this for initialization
void Start () {
NetworkManager.OnReceiveMessageFromGameObjectUpdate += NetworkManager_OnReceiveMessageFromGameObjectUpdate;
//Initialize
lastPosition = transform.position;
lastRotation = transform.rotation;
}
public IEnumerator ThisWillBeExecutedOnTheMainThread()
{
Debug.Log("This is executed from the main thread");
//transform.position = new Vector3(newMessage.GameObjectPos.x, newMessage.GameObjectPos.y, newMessage.GameObjectPos.z);
lastPosition = nextPosition;
transform.position = nextPosition;
lastRotation = nextRotation;
transform.rotation = nextRotation;
//Add rotation
yield return null;
}
void NetworkManager_OnReceiveMessageFromGameObjectUpdate (NetworkManager.ReceiveMessageFromGameObject newMessage)
{
Debug.Log ("Raise event in GameObject");
Debug.Log (newMessage.MessageType);
Debug.Log (newMessage.GameObjectID);
Debug.Log (newMessage.GameObjectPos);
Debug.Log (newMessage.GameObjectRot);
//Update pos and rot
if (newMessage.GameObjectID == objectID)
{
nextPosition = new Vector3(newMessage.GameObjectPos.x, newMessage.GameObjectPos.y, newMessage.GameObjectPos.z);
nextRotation = new Quaternion(newMessage.GameObjectRot.x, newMessage.GameObjectPos.y, newMessage.GameObjectRot.z, newMessage.GameObjectRot.w);
UnityMainThreadDispatcher.Instance().Enqueue(ThisWillBeExecutedOnTheMainThread());
}
}
// Update is called once per frame
void Update () {
if ((Vector3.Distance(transform.position, lastPosition) > 0.05) || (Quaternion.Angle(transform.rotation, lastRotation) > 0.3))
{
NetworkManager.instance.SendMessage(NetworkManager.SendType.SENDTOOTHER, NetworkManager.PacketId.OBJECT_MOVE, this.objectID, transform.position, transform.rotation);
//Update stuff
lastPosition = transform.position;
lastRotation = transform.rotation;
}
}
}
| mit | C# |
e9bce922f06f64884a7a3da8304c8884f11166ee | Support piping a WebAssembly file to wasm-dump | jonathanvdc/cs-wasm,jonathanvdc/cs-wasm | wasm-dump/Program.cs | wasm-dump/Program.cs | using System;
using System.IO;
using Wasm.Binary;
namespace Wasm.Dump
{
public static class Program
{
private static MemoryStream ReadStdinToEnd()
{
// Based on Marc Gravell's answer to this StackOverflow question:
// https://stackoverflow.com/questions/1562417/read-binary-data-from-console-in
var memStream = new MemoryStream();
using (var stdin = Console.OpenStandardInput())
{
byte[] buffer = new byte[2048];
int bytes;
while ((bytes = stdin.Read(buffer, 0, buffer.Length)) > 0)
{
memStream.Write(buffer, 0, bytes);
}
}
memStream.Seek(0, SeekOrigin.Begin);
return memStream;
}
public static int Main(string[] args)
{
if (args.Length > 1)
{
Console.Error.WriteLine("usage: wasm-dump [file.wasm]");
return 1;
}
var memStream = new MemoryStream();
WasmFile file;
if (args.Length == 0)
{
using (var input = ReadStdinToEnd())
{
file = WasmFile.ReadBinary(input);
}
}
else
{
file = WasmFile.ReadBinary(args[0]);
}
file.Dump(Console.Out);
Console.WriteLine();
return 0;
}
}
}
| using System;
using System.IO;
using Wasm.Binary;
namespace Wasm.Dump
{
public static class Program
{
public static int Main(string[] args)
{
if (args.Length != 1)
{
Console.Error.WriteLine("usage: wasm-dump file.wasm");
return 1;
}
var file = WasmFile.ReadBinary(args[0]);
file.Dump(Console.Out);
Console.WriteLine();
return 0;
}
}
}
| mit | C# |
faad90ccd836645ca9489e0c14efc6b0314eaa5e | change EmptyPosition to class | acple/ParsecSharp | ParsecSharp/Data/Internal/EmptyPosition.cs | ParsecSharp/Data/Internal/EmptyPosition.cs | namespace ParsecSharp.Internal
{
public class EmptyPosition : IPosition
{
public static IPosition Initial { get; } = new EmptyPosition();
public int Line => 0;
public int Column => -1;
private EmptyPosition()
{ }
public int CompareTo(IPosition other)
=> (this.Equals(other)) ? 0 : -1;
public bool Equals(IPosition other)
=> ReferenceEquals(this, other);
public override bool Equals(object? obj)
=> ReferenceEquals(this, obj);
public override int GetHashCode()
=> 0;
public override string ToString()
=> "Position: none";
}
}
| namespace ParsecSharp.Internal
{
public readonly struct EmptyPosition : IPosition
{
public static EmptyPosition Initial => default;
public int Line => 0;
public int Column => -1;
public int CompareTo(IPosition other)
=> (other is EmptyPosition) ? 0 : -1;
public bool Equals(IPosition other)
=> other is EmptyPosition;
public override bool Equals(object? obj)
=> obj is EmptyPosition;
public override int GetHashCode()
=> 0;
public override string ToString()
=> "Position: none";
}
}
| mit | C# |
57cd90a7db9653640a41103321864e1c565cdf44 | Update console to show parsing duration | CSGO-Analysis/CSGO-Analyzer | DemoParser-Console/Program.cs | DemoParser-Console/Program.cs | using DemoParser_Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoParser_Console
{
class Program
{
static void Main(string[] args)
{
DateTime begin;
DateTime end;
Stream inputStream = new FileStream(args[0], FileMode.Open);
Console.WriteLine("Parsing...");
begin = DateTime.Now;
DemoParser parser = new DemoParser(inputStream);
parser.ParseDemo(true);
end = DateTime.Now;
Console.WriteLine(String.Format("Started: {0}", begin.ToString("HH:mm:ss.ffffff")));
Console.WriteLine(String.Format("Finished: {0}", end.ToString("HH:mm:ss.ffffff")));
Console.WriteLine(String.Format("\nTotal: {0}", (end - begin)));
Console.ReadKey();
}
}
}
| using DemoParser_Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoParser_Console
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
Stream inputStream = new FileStream(args[0], FileMode.Open);
DemoParser parser = new DemoParser(inputStream);
parser.ParseDemo(true);
Console.WriteLine(DateTime.Now);
Console.ReadKey();
}
}
}
| mit | C# |
16c47e721b2ff43708e60cd15ef0d5025eb82d73 | Fix Grafeas smoke test to use client builder | jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet | apis/Grafeas.V1/Grafeas.V1.SmokeTests/GrafeasSmokeTest.cs | apis/Grafeas.V1/Grafeas.V1.SmokeTests/GrafeasSmokeTest.cs | // Copyright 2019 Google LLC
//
// 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
//
// https://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.
namespace Grafeas.V1.SmokeTests
{
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using Grpc.Auth;
using Grpc.Core;
using System;
public class GrafeasSmokeTest
{
public static int Main(string[] args)
{
// Read projectId from args
if (args.Length != 1)
{
Console.WriteLine("Usage: Project ID must be passed as first argument.");
Console.WriteLine();
return 1;
}
string projectId = args[0];
// Smoke test against the Google Container Analysis implementation, using
// a known endpoint.
// Create client
var channelCredential = GoogleCredential.GetApplicationDefault().ToChannelCredentials();
GrafeasClient client = new GrafeasClientBuilder
{
Endpoint = "containeranalysis.googleapis.com",
ChannelCredentials = channelCredential
}.Build();
// Call API method
ProjectName projectName = ProjectName.FromProject(projectId);
PagedEnumerable<ListNotesResponse, Note> notes = client.ListNotes(projectName, "");
// Show the result
foreach (Note note in notes)
{
Console.WriteLine(note);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
| // Copyright 2019 Google LLC
//
// 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
//
// https://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.
namespace Grafeas.V1.SmokeTests
{
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using Grpc.Auth;
using Grpc.Core;
using System;
public class GrafeasSmokeTest
{
public static int Main(string[] args)
{
// Read projectId from args
if (args.Length != 1)
{
Console.WriteLine("Usage: Project ID must be passed as first argument.");
Console.WriteLine();
return 1;
}
string projectId = args[0];
// Smoke test against the Google Container Analysis implementation, using
// a known endpoint.
// Create client
var channelCredential = GoogleCredential.GetApplicationDefault().ToChannelCredentials();
var channel = new Channel("containeranalysis.googleapis.com", channelCredential);
GrafeasClient client = GrafeasClient.Create(channel);
// Call API method
ProjectName projectName = ProjectName.FromProject(projectId);
PagedEnumerable<ListNotesResponse, Note> notes = client.ListNotes(projectName, "");
// Show the result
foreach (Note note in notes)
{
Console.WriteLine(note);
}
// Success
Console.WriteLine("Smoke test passed OK");
return 0;
}
}
}
| apache-2.0 | C# |
33c0fd7e459d9ae2060e5c392db4c274cd8701c1 | Add GitCommandException taking a message | appharbor/appharbor-cli | src/AppHarbor/GitCommandException.cs | src/AppHarbor/GitCommandException.cs | using System;
namespace AppHarbor
{
public class GitCommandException : Exception
{
public GitCommandException(string message)
: base(message)
{
}
}
}
| using System;
namespace AppHarbor
{
public class GitCommandException : Exception
{
}
}
| mit | C# |
186208213a2eaede992b17f7b4ab38cd5d8a10ec | Order Fonts Alphabetically | tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS | Portal.CMS.Services/Generic/FontService.cs | Portal.CMS.Services/Generic/FontService.cs | using Portal.CMS.Entities;
using Portal.CMS.Entities.Entities.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Portal.CMS.Services.Generic
{
public interface IFontService
{
Font Get(int fontId);
List<Font> Get();
int Create(string fontName, string fontType, string fontFilePath);
void Delete(int fontId);
}
public class FontService : IFontService
{
#region Dependencies
private readonly PortalEntityModel _context;
public FontService(PortalEntityModel context)
{
_context = context;
}
#endregion Dependencies
public Font Get(int fontId)
{
var results = _context.Fonts.SingleOrDefault(x => x.FontId == fontId);
return results;
}
public List<Font> Get()
{
var results = _context.Fonts.OrderBy(x => x.FontName).ToList();
return results;
}
public int Create(string fontName, string fontType, string fontFilePath)
{
var newFont = new Font
{
FontName = fontName,
FontType = fontType,
FontPath = fontFilePath,
DateAdded = DateTime.Now,
DateUpdated = DateTime.Now
};
_context.Fonts.Add(newFont);
_context.SaveChanges();
return newFont.FontId;
}
public void Delete(int fontId)
{
var font = _context.Fonts.FirstOrDefault(x => x.FontId == fontId);
if (font == null)
return;
_context.Fonts.Remove(font);
_context.SaveChanges();
}
}
} | using Portal.CMS.Entities;
using Portal.CMS.Entities.Entities.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Portal.CMS.Services.Generic
{
public interface IFontService
{
Font Get(int fontId);
List<Font> Get();
int Create(string fontName, string fontType, string fontFilePath);
void Delete(int fontId);
}
public class FontService : IFontService
{
#region Dependencies
private readonly PortalEntityModel _context;
public FontService(PortalEntityModel context)
{
_context = context;
}
#endregion Dependencies
public Font Get(int fontId)
{
var results = _context.Fonts.SingleOrDefault(x => x.FontId == fontId);
return results;
}
public List<Font> Get()
{
var results = _context.Fonts.OrderByDescending(x => x.FontId).ToList();
return results;
}
public int Create(string fontName, string fontType, string fontFilePath)
{
var newFont = new Font
{
FontName = fontName,
FontType = fontType,
FontPath = fontFilePath,
DateAdded = DateTime.Now,
DateUpdated = DateTime.Now
};
_context.Fonts.Add(newFont);
_context.SaveChanges();
return newFont.FontId;
}
public void Delete(int fontId)
{
var font = _context.Fonts.FirstOrDefault(x => x.FontId == fontId);
if (font == null)
return;
_context.Fonts.Remove(font);
_context.SaveChanges();
}
}
} | mit | C# |
ac5b6bfe77c94d81a271aa1b4a4e813541761e92 | Update PlayerMovement.cs | afroraydude/First_Unity_Game,afroraydude/First_Unity_Game,afroraydude/First_Unity_Game | Real_Game/Assets/Scripts/PlayerMovement.cs | Real_Game/Assets/Scripts/PlayerMovement.cs | using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public GameManager manager;
public float moveSpeed;
private float maxSpeed = 5f;
public int deathCount;
public GameObject deathParticals;
private Vector3 input;
private Vector3 spawn;
// Use this for initialization
void Start ()
{
spawn = transform.position;
manager = manager.GetComponent<GameManager>();
}
// Update is called once per frame
void FixedUpdate ()
{
input = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if(rigidbody.velocity.magnitude < maxSpeed)
{
rigidbody.AddForce(input * moveSpeed);
}
if (transform.position.y < -2)
{
Die ();
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Goal")
{
manager.CompleteLevel();
}
}
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Enemy")
{
deathCount +=1;
Die ();
}
}
void Die()
{
Instantiate(deathParticals, transform.position, Quaternion.identity);
transform.position = spawn;
}
}
| using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public GameManager manager;
public float moveSpeed;
private float maxSpeed = 5f;
public GameObject deathParticals;
private Vector3 input;
private Vector3 spawn;
// Use this for initialization
void Start ()
{
spawn = transform.position;
manager = manager.GetComponent<GameManager>();
}
// Update is called once per frame
void FixedUpdate ()
{
input = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
if(rigidbody.velocity.magnitude < maxSpeed)
{
rigidbody.AddForce(input * moveSpeed);
}
if (transform.position.y < -2)
{
Die ();
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Goal")
{
manager.CompleteLevel();
}
}
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Enemy")
{
Die ();
}
}
void Die()
{
Instantiate(deathParticals, transform.position, Quaternion.identity);
transform.position = spawn;
}
} | mit | C# |
2bbc771769cb37b5f92f32ec635d73dde6c98b6d | Update GetListOfSubscriptions.cs | devkale/sample-code-csharp,AuthorizeNet/sample-code-csharp,akankaria/sample-code-csharp,rmorrin/sample-code-csharp | RecurringBilling/GetListOfSubscriptions.cs | RecurringBilling/GetListOfSubscriptions.cs | using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers.Bases;
namespace net.authorize.sample
{
class GetListOfSubscriptions
{
public static void Run(String ApiLoginID, String ApiTransactionKey)
{
Console.WriteLine("Get A List of Subscriptions Sample");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ApiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = ApiTransactionKey,
};
var request = new ARBGetSubscriptionListRequest {searchType = ARBGetSubscriptionListSearchTypeEnum.subscriptionActive }; // only gets active subscriptions
var controller = new ARBGetSubscriptionListController(request); // instantiate the contoller that will call the service
controller.Execute();
ARBGetSubscriptionListResponse response = controller.GetApiResponse(); // get the response from the service (errors contained if any)
//validate
if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
{
if (response != null && response.messages.message != null && response.subscriptionDetails != null)
{
Console.WriteLine("Success, " + response.totalNumInResultSet + " Results Returned ");
}
}
else
{
Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text);
}
}
}
}
| using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers.Bases;
namespace net.authorize.sample
{
class GetListSubscriptions
{
public static void Run(String ApiLoginID, String ApiTransactionKey)
{
Console.WriteLine("Get A List of Subscriptions Sample");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ApiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = ApiTransactionKey,
};
var request = new ARBGetSubscriptionListRequest {searchType = ARBGetSubscriptionListSearchTypeEnum.subscriptionActive }; // only gets active subscriptions
var controller = new ARBGetSubscriptionListController(request); // instantiate the contoller that will call the service
controller.Execute();
ARBGetSubscriptionListResponse response = controller.GetApiResponse(); // get the response from the service (errors contained if any)
//validate
if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
{
if (response != null && response.messages.message != null && response.subscriptionDetails != null)
{
Console.WriteLine("Success, " + response.totalNumInResultSet + " Results Returned ");
}
}
else
{
Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text);
}
}
}
}
| mit | C# |
0fdce021a5b4293c06edc84ad815dc1b6439a58b | Optimize Success. | Faithlife/Parsing | src/Faithlife.Parsing/Parser-Then.cs | src/Faithlife.Parsing/Parser-Then.cs | namespace Faithlife.Parsing;
public static partial class Parser
{
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<TAfter> Then<TBefore, TAfter>(this IParser<TBefore> parser, Func<TBefore, IParser<TAfter>> convertValueToNextParser)
=> Create(position => parser.TryParse(position).MapSuccess(result => convertValueToNextParser(result.Value).TryParse(result.NextPosition)));
/// <summary>
/// Converts any successfully parsed value.
/// </summary>
public static IParser<TAfter> Select<TBefore, TAfter>(this IParser<TBefore> parser, Func<TBefore, TAfter> convertValue)
=> parser.Then(value => Success(convertValue(value)));
/// <summary>
/// Succeeds with the specified value if the parser is successful.
/// </summary>
public static IParser<TAfter> Success<TBefore, TAfter>(this IParser<TBefore> parser, TAfter value)
=> Create(position => parser.TryParse(position).MapSuccess(result => ParseResult.Success(value, result.NextPosition)));
/// <summary>
/// Concatenates the two successfully parsed collections.
/// </summary>
public static IParser<IReadOnlyList<T>> Concat<T>(this IParser<IEnumerable<T>> firstParser, IParser<IEnumerable<T>> secondParser)
=> firstParser.Then(firstValue => secondParser.Select(x => firstValue.Concat(x).ToList()));
/// <summary>
/// Appends a successfully parsed value to the end of a successfully parsed collection.
/// </summary>
public static IParser<IReadOnlyList<T>> Append<T>(this IParser<IEnumerable<T>> firstParser, IParser<T> secondParser)
=> firstParser.Concat(secondParser.Once());
/// <summary>
/// Used to support LINQ query syntax.
/// </summary>
public static IParser<TAfter> SelectMany<TBefore, TDuring, TAfter>(this IParser<TBefore> parser, Func<TBefore, IParser<TDuring>> selector, Func<TBefore, TDuring, TAfter> projector)
=> parser.Then(t => selector(t).Select(u => projector(t, u)));
}
| namespace Faithlife.Parsing;
public static partial class Parser
{
/// <summary>
/// Executes one parser after another.
/// </summary>
public static IParser<TAfter> Then<TBefore, TAfter>(this IParser<TBefore> parser, Func<TBefore, IParser<TAfter>> convertValueToNextParser)
=> Create(position => parser.TryParse(position).MapSuccess(result => convertValueToNextParser(result.Value).TryParse(result.NextPosition)));
/// <summary>
/// Converts any successfully parsed value.
/// </summary>
public static IParser<TAfter> Select<TBefore, TAfter>(this IParser<TBefore> parser, Func<TBefore, TAfter> convertValue)
=> parser.Then(value => Success(convertValue(value)));
/// <summary>
/// Succeeds with the specified value if the parser is successful.
/// </summary>
public static IParser<TAfter> Success<TBefore, TAfter>(this IParser<TBefore> parser, TAfter value) => parser.Select(_ => value);
/// <summary>
/// Concatenates the two successfully parsed collections.
/// </summary>
public static IParser<IReadOnlyList<T>> Concat<T>(this IParser<IEnumerable<T>> firstParser, IParser<IEnumerable<T>> secondParser)
=> firstParser.Then(firstValue => secondParser.Select(x => firstValue.Concat(x).ToList()));
/// <summary>
/// Appends a successfully parsed value to the end of a successfully parsed collection.
/// </summary>
public static IParser<IReadOnlyList<T>> Append<T>(this IParser<IEnumerable<T>> firstParser, IParser<T> secondParser)
=> firstParser.Concat(secondParser.Once());
/// <summary>
/// Used to support LINQ query syntax.
/// </summary>
public static IParser<TAfter> SelectMany<TBefore, TDuring, TAfter>(this IParser<TBefore> parser, Func<TBefore, IParser<TDuring>> selector, Func<TBefore, TDuring, TAfter> projector)
=> parser.Then(t => selector(t).Select(u => projector(t, u)));
}
| mit | C# |
088cf24a6b6e43194d68ae18ace9e9fce8020b60 | Revert "Base directory for Avalonia" | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Program.cs | WalletWasabi.Gui/Program.cs | using Avalonia;
using AvalonStudio.Shell;
using AvalonStudio.Shell.Extensibility.Platforms;
using NBitcoin;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui
{
internal class Program
{
#pragma warning disable IDE1006 // Naming Styles
private static async Task Main(string[] args)
#pragma warning restore IDE1006 // Naming Styles
{
StatusBarViewModel statusBar = null;
try
{
BuildAvaloniaApp().BeforeStarting(async builder =>
{
try
{
MainWindowViewModel.Instance = new MainWindowViewModel();
Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt"));
var configFilePath = Path.Combine(Global.DataDir, "Config.json");
var config = new Config(configFilePath);
await config.LoadOrCreateDefaultFileAsync();
Logger.LogInfo<Config>("Config is successfully initialized.");
Global.InitializeConfig(config);
if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it.
{
var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath));
if (File.Exists(cachedIndexFilePath))
{
File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false);
}
}
Global.InitializeNoWallet();
statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker);
MainWindowViewModel.Instance.StatusBar = statusBar;
if (Global.IndexDownloader.Network != Network.Main)
{
MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}";
}
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
}).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance);
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
finally
{
statusBar?.Dispose();
await Global.DisposeAsync();
}
}
private static AppBuilder BuildAvaloniaApp()
{
return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI();
}
}
}
| using Avalonia;
using AvalonStudio.Shell;
using AvalonStudio.Shell.Extensibility.Platforms;
using NBitcoin;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui
{
internal class Program
{
#pragma warning disable IDE1006 // Naming Styles
private static async Task Main(string[] args)
#pragma warning restore IDE1006 // Naming Styles
{
StatusBarViewModel statusBar = null;
try
{
Platform.BaseDirectory = Path.Combine(Global.DataDir, "Gui");
BuildAvaloniaApp().BeforeStarting(async builder =>
{
try
{
MainWindowViewModel.Instance = new MainWindowViewModel();
Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt"));
var configFilePath = Path.Combine(Global.DataDir, "Config.json");
var config = new Config(configFilePath);
await config.LoadOrCreateDefaultFileAsync();
Logger.LogInfo<Config>("Config is successfully initialized.");
Global.InitializeConfig(config);
if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it.
{
var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath));
if (File.Exists(cachedIndexFilePath))
{
File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false);
}
}
Global.InitializeNoWallet();
statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker);
MainWindowViewModel.Instance.StatusBar = statusBar;
if (Global.IndexDownloader.Network != Network.Main)
{
MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}";
}
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
}).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance);
}
catch (Exception ex)
{
Logger.LogCritical<Program>(ex);
}
finally
{
statusBar?.Dispose();
await Global.DisposeAsync();
}
}
private static AppBuilder BuildAvaloniaApp()
{
return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI();
}
}
}
| mit | C# |
2ae2957e436e244a7a960daab3c7c967798a71cb | Implement IRCMessage | Luke-Wolf/wolfybot | WolfyBot.Core/IRCMessage.cs | WolfyBot.Core/IRCMessage.cs | //
// Copyright 2014 luke
//
// 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;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
namespace WolfyBot.Core
{
public class IRCMessage
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WolfyBot.Core.IRCMessage"/> class.
/// </summary>
/// <param name="ircMessage">A Message formatted in the IRC Protocol</param>
public IRCMessage (String ircMessage)
{
TimeStamp = DateTime.Now;
//If an IRC Message starts with a colon the first string before
//the space is the prefix
int prefixEnd = -1;
if (ircMessage.StartsWith (":", StringComparison.Ordinal)) {
prefixEnd = ircMessage.IndexOf (" ", StringComparison.Ordinal);
Prefix = ircMessage.Substring (1, prefixEnd - 1);
}
//Get the Trailing Parameters if they exist as a string literal
//Trailing Parameters are demarkated by a space and a colon at the
//end of the normal parameter set
int trailingStart = ircMessage.IndexOf (" :", StringComparison.Ordinal);
if (trailingStart >= 0) {
TrailingParameters = ircMessage.Substring (trailingStart + 2);
} else {
trailingStart = ircMessage.Length;
}
//pull the command and parameters out of the IRC Message by pulling everything
//between the prefix and the trailing parameters, The Command is the first item,
//and everything else if it exists is the parameter to that command
String[] commandAndParameters = ircMessage.Substring (prefixEnd + 1, trailingStart - prefixEnd - 1).Split (' ');
Command = commandAndParameters [0];
if (commandAndParameters.Length > 1) {
Parameters = commandAndParameters.Skip (1).ToList ();
//If Parameters contains a channel pull it out
foreach (var item in Parameters) {
if (item.Contains ("#")) {
Channel = item;
break;
}
}
}
}
//Copy Constructor
public IRCMessage (IRCMessage other)
{
TimeStamp = other.TimeStamp;
Prefix = String.Copy (other.Prefix);
Command = String.Copy (other.Command);
Parameters = new List<String> (other.Parameters);
Channel = String.Copy (other.Channel);
}
#endregion
#region Methods
public String ToIRCString ()
{
return String.Format (":{0} {1} {2} :{3}", Prefix,
Command, Parameters.ToString ().Replace (",", " "), TrailingParameters);
}
public String ToLogString ()
{
return String.Format ("{0} {1} {2} {3} {4}", TimeStamp, Prefix,
Command, Parameters.ToString ().Replace (",", " "), TrailingParameters);
}
public String ToString ()
{
return String.Format ("TimeStamp: {0}, IRC Message: ':{1} {2} {3} :{4}'",
TimeStamp, Prefix, Command, Parameters.ToString ().Replace (",", " "), TrailingParameters);
}
#endregion
#region Properties
public String Prefix {
get;
set;
}
public String Command {
get;
set;
}
public List<String> Parameters {
get;
set;
}
public String TrailingParameters {
get;
set;
}
public DateTime TimeStamp {
get;
set;
}
public String Channel {
get;
set;
}
#endregion
}
}
| //
// Copyright 2014 luke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace WolfyBot.Core
{
public class IRCMessage
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WolfyBot.Core.IRCMessage"/> class.
/// </summary>
/// <param name="ircMessage">A Message formatted in the IRC Protocol</param>
public IRCMessage (String ircMessage)
{
TimeStamp = DateTime.Now;
//TODO: write IRC Parser
}
//Copy Constructor
public IRCMessage (IRCMessage other)
{
TimeStamp = other.TimeStamp;
Prefix = other.Prefix;
Command = other.Command;
Parameters = other.Parameters;
TrailingParameters = other.TrailingParameters;
}
#endregion
#region Methods
public String ToIRCString ()
{
//TODO: Implement Serialization to IRC Protocol
return "";
}
public String ToLogString ()
{
//TODO: Implement Serialization to logging format
return "";
}
#endregion
#region Properties
public String Prefix {
get;
set;
}
public String Command {
get;
set;
}
public String Parameters {
get;
set;
}
public String TrailingParameters {
get;
set;
}
public DateTime TimeStamp {
get;
set;
}
#endregion
}
}
| apache-2.0 | C# |
f8fb972cd57afbd82461333533a26a934ff7ac1d | 修正 HtmlText 属性默认行为 | yonglehou/Jumony,zpzgone/Jumony,wukaixian/Jumony,yonglehou/Jumony,wukaixian/Jumony,zpzgone/Jumony | Ivony.Html.Parser/DomTextNode.cs | Ivony.Html.Parser/DomTextNode.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Ivony.Html.Parser
{
/// <summary>
/// IHtmlTextNode 的一个实现
/// </summary>
public class DomTextNode : DomNode, IHtmlTextNode
{
private readonly string raw;
/// <summary>
/// 创建 DomTextNode 对象
/// </summary>
/// <param name="rawHtml"></param>
public DomTextNode( string rawHtml )
{
raw = rawHtml;
}
/// <summary>
/// 获取一个名称,用于识别节点类型,此属性总是返回 "TextNode"
/// </summary>
protected override string ObjectName
{
get { return "TextNode"; }
}
/// <summary>
/// 获取文本节点所代表的 HTML 文本
/// </summary>
public string HtmlText
{
get
{
var element = this.Parent();
if ( element != null && Document.HtmlSpecification.IsCDataElement( element.Name ) )
return raw;
return HtmlEncoding.HtmlEncode( HtmlEncoding.HtmlDecode( raw ) );
}
}
/// <summary>
/// 获取原始的 HTML 文本
/// </summary>
public override string RawHtml
{
get
{
return raw;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Ivony.Html.Parser
{
/// <summary>
/// IHtmlTextNode 的一个实现
/// </summary>
public class DomTextNode : DomNode, IHtmlTextNode
{
private readonly string raw;
/// <summary>
/// 创建 DomTextNode 对象
/// </summary>
/// <param name="rawHtml"></param>
public DomTextNode( string rawHtml )
{
raw = rawHtml;
}
/// <summary>
/// 获取一个名称,用于识别节点类型,此属性总是返回 "TextNode"
/// </summary>
protected override string ObjectName
{
get { return "TextNode"; }
}
/// <summary>
/// 获取文本节点所代表的 HTML 文本
/// </summary>
public string HtmlText
{
get
{
var element = this.Parent();
if ( element != null )
{
if ( Document.HtmlSpecification.IsCDataElement( element.Name ) )
return raw;
else
return HtmlEncoding.HtmlEncode( HtmlEncoding.HtmlDecode( raw ) );
}
return raw;
}
}
/// <summary>
/// 获取原始的 HTML 文本
/// </summary>
public override string RawHtml
{
get
{
return raw;
}
}
}
}
| apache-2.0 | C# |
1fa95571bcbad2402ab0bedb8d300cd878fffa6b | Update AnimatedBar.cs | sant0ro/Yupi,sant0ro/Yupi,sant0ro/Yupi,TheDoct0r11/Yupi,TheDoct0r11/Yupi,TheDoct0r11/Yupi,sant0ro/Yupi,sant0ro/Yupi,TheDoct0r11/Yupi | Yupi/Core/Io/AnimatedBar.cs | Yupi/Core/Io/AnimatedBar.cs | /**
Because i love chocolat...
88 88
"" 88
88
8b d8 88 88 8b,dPPYba, 88 88
`8b d8' 88 88 88P' "8a 88 88
`8b d8' 88 88 88 d8 88 ""
`8b,d8' "8a, ,a88 88b, ,a8" 88 aa
Y88' `"YbbdP'Y8 88`YbbdP"' 88 88
d8' 88
d8' 88
Private Habbo Hotel Emulating System
@author Claudio A. Santoro W.
@author Kessiler R.
@version dev-beta
@license MIT
@copyright Sulake Corporation Oy
@observation All Rights of Habbo, Habbo Hotel, and all Habbo contents and it's names, is copyright from Sulake
Corporation Oy. Yupi! has nothing linked with Sulake.
This Emulator is Only for DEVELOPMENT uses. If you're selling this you're violating Sulakes Copyright.
*/
using System.Collections.Generic;
using Yupi.Core.Io.Interfaces;
namespace Yupi.Core.Io
{
public class AnimatedBar : AbstractBar
{
private readonly List<string> _animation;
private int _counter;
public AnimatedBar()
{
_animation = new List<string> { "/", "-", @"\", "|" };
_counter = 0;
}
/// <summary>
/// prints the character found in the animation according to the current index
/// </summary>
public override void Step()
{
System.Console.Write("{0}\b", _animation[_counter % _animation.Count]);
_counter++;
}
}
}
| /**
Because i love chocolat...
88 88
"" 88
88
8b d8 88 88 8b,dPPYba, 88 88
`8b d8' 88 88 88P' "8a 88 88
`8b d8' 88 88 88 d8 88 ""
`8b,d8' "8a, ,a88 88b, ,a8" 88 aa
Y88' `"YbbdP'Y8 88`YbbdP"' 88 88
d8' 88
d8' 88
Private Habbo Hotel Emulating System
@author Claudio A. Santoro W.
@author Kessiler R.
@version dev-beta
@license MIT
@copyright Sulake Corporation Oy
@observation All Rights of Habbo, Habbo Hotel, and all Habbo contents and it's names, is copyright from Sulake
Corporation Oy. Yupi! has nothing linked with Sulake.
This Emulator is Only for DEVELOPMENT uses. If you're selling this you're violating Sulakes Copyright.
*/
using System.Collections.Generic;
using Yupi.Core.Io.Interfaces;
namespace Yupi.Core.Io
{
public class AnimatedBar : AbstractBar
{
private readonly List<string> _animation;
private int _counter;
public AnimatedBar()
{
_animation = new List<string> { "/", "-", @"\", "|" };
_counter = 0;
}
/// <summary>
/// prints the character found in the animation according to the current index
/// </summary>
public override void Step()
{
System.Console.Write("{0}\b", _animation[_counter]);
_counter++;
if (_counter == _animation.Count)
_counter = 0;
}
}
} | mit | C# |
c66699b7c76377b6809601313a0e12c56f52c1bb | Add unit test for all action method on CropController | erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner | Oogstplanner.Tests/Controllers/CropControllerTest.cs | Oogstplanner.Tests/Controllers/CropControllerTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NUnit.Framework;
using Oogstplanner.Services;
using Oogstplanner.Controllers;
using Oogstplanner.Models;
using Oogstplanner.Repositories;
namespace Oogstplanner.Tests
{
[TestFixture]
public class CropControllerTest
{
private CropController controller;
[TestFixtureSetUp]
public void Setup()
{
// Initialize a fake database with one crop.
var db = new FakeOogstplannerContext
{
Crops =
{
new Crop
{
Id = 1,
Name = "Broccoli",
SowingMonths = Month.May ^ Month.June ^ Month.October ^ Month.November
}
}
};
this.controller = new CropController(new CropProvider(new CropRepository(db)));
}
[Test]
public void Controllers_Crop_Index_AllCrops()
{
// Arrange
const string expectedResult = "Broccoli";
// Act
var viewResult = controller.Index();
var actualResult = ((IEnumerable<Crop>)viewResult.ViewData.Model).Single().Name;
// Assert
Assert.AreEqual(expectedResult, actualResult,
"Since there is only a broccoli in the database the index method should return it.");
}
[Test]
public void Controllers_Crop_All()
{
// Arrange
const string expectedResult = "Broccoli";
// Act
var viewResult = controller.All();
var actualResult = ((ContentResult)viewResult).Content;
// Assert
Assert.IsTrue(actualResult.Contains(expectedResult),
"Since there is a broccoli in the database the JSON string returned by the all " +
"method should contain it.");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NUnit.Framework;
using Oogstplanner.Services;
using Oogstplanner.Controllers;
using Oogstplanner.Models;
using Oogstplanner.Repositories;
namespace Oogstplanner.Tests
{
[TestFixture]
public class CropControllerTest
{
private CropController controller;
[TestFixtureSetUp]
public void Setup()
{
// Initialize a fake database with one crop.
var db = new FakeOogstplannerContext
{
Crops =
{
new Crop
{
Id = 1,
Name = "Broccoli",
SowingMonths = Month.May ^ Month.June ^ Month.October ^ Month.November
}
}
};
this.controller = new CropController(new CropProvider(new CropRepository(db)));
}
[Test]
public void Controllers_Crop_Index_AllCrops()
{
// Arrange
var expectedResult = "Broccoli";
// Act
var viewResult = controller.Index();
var actualResult = ((IEnumerable<Crop>)viewResult.ViewData.Model).Single().Name;
// Assert
Assert.AreEqual(expectedResult, actualResult,
"Since there is only a broccoli in the database the index method should return it.");
}
}
} | mit | C# |
f1426e287b74dce56b5b5dd53d1cb7c33ba9d30d | Hide redact button in sample when gateway is already redacted | philjones88/SpreedlyCoreSharp | SpreedlyCoreSharp.WebSample/Views/Gateways/Gateways.cshtml | SpreedlyCoreSharp.WebSample/Views/Gateways/Gateways.cshtml | @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<System.Collections.Generic.List<SpreedlyCoreSharp.Domain.Gateway>>
@{
ViewBag.Active = "Gateway";
Layout = "_Layout.cshtml";
}
<div class="span12">
<a href="/gateways/add-test-gateway" class="btn" onclick="return confirm('Are you sure you want to add a test gateway?')">Add Test Gateway</a>
<br />
<table class="table table-striped">
<thead>
<tr>
<th>Token</th>
<th>Type</th>
<th>Redacted?</th>
<th>3D Auth?</th>
<th>3D Purchase?</th>
<th>Created</th>
<th>Updated</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var gateway in Model)
{
<tr>
<td>@gateway.Token</td>
<td>@gateway.GatewayType</td>
<td>@gateway.Redacted</td>
<td>@gateway.GatewayCharacteristics.Supports3DSecureAuthorize</td>
<td>@gateway.GatewayCharacteristics.Supports3DSecurePurchase</td>
<td>@gateway.CreatedAt</td>
<td>@gateway.UpdatedAt</td>
<td>
@if (!gateway.Redacted)
{
<a href="/gateways/redact/@gateway.Token" class="btn btn-danger" onclick="return confirm('Are you sure, redacting a gateway is permenant.')">Redact</a>
}
</td>
</tr>
}
</tbody>
</table>
</div>
| @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<System.Collections.Generic.List<SpreedlyCoreSharp.Domain.Gateway>>
@{
ViewBag.Active = "Gateway";
Layout = "_Layout.cshtml";
}
<div class="span12">
<a href="/gateways/add-test-gateway" class="btn" onclick="return confirm('Are you sure you want to add a test gateway?')">Add Test Gateway</a>
<br />
<table class="table table-striped">
<thead>
<tr>
<th>Token</th>
<th>Type</th>
<th>Redacted?</th>
<th>3D Auth?</th>
<th>3D Purchase?</th>
<th>Created</th>
<th>Updated</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var gateway in Model)
{
<tr>
<td>@gateway.Token</td>
<td>@gateway.GatewayType</td>
<td>@gateway.Redacted</td>
<td>@gateway.GatewayCharacteristics.Supports3DSecureAuthorize</td>
<td>@gateway.GatewayCharacteristics.Supports3DSecurePurchase</td>
<td>@gateway.CreatedAt</td>
<td>@gateway.UpdatedAt</td>
<td>
<a href="/gateways/redact/@gateway.Token" class="btn btn-danger" onclick="return confirm('Are you sure, redacting a gateway is permenant.')">Redact</a>
</td>
</tr>
}
</tbody>
</table>
</div>
| mit | C# |
fdca5e92a12fd77a407ae15c2f08bb1de5132d0a | Fix 'set description' link | rijkshuisstijl/Rijkshuisstijl.VersionManager | Views/VersionManager/SetDescription.cshtml | Views/VersionManager/SetDescription.cshtml | @model Rijkshuisstijl.VersionManager.ViewModels.Admin.SetDescriptionViewModel
@{
Layout.Title = T("Edit the description");
}
<div id="version-description">
<div class="errormessages">
@Html.ValidationSummary()
</div>
@using (Html.BeginFormAntiForgeryPost())
{
@Html.HiddenFor(m => m.ContentItemId)
@Html.HiddenFor(m => m.ContentItemVersionId)
@Html.Label(T("Edit the description").Text, new {@class = "editor-label"})
@Html.TextBoxFor(m => m.Description, new {@class = "textMedium"})
<fieldset>
<legend></legend>
<button class="primaryAction" type="submit">@T("Save")</button>
</fieldset>
}
</div>
@using (Script.Foot())
{
<script type="text/javascript">
document.getElementById("VersionManagerRecord_Description").focus();
</script>
}
| @model Rijkshuisstijl.VersionManager.ViewModels.Admin.SetDescriptionViewModel
@{
Layout.Title = T("Edit the description");
}
<div id="version-description">
<div class="errormessages">
@Html.ValidationSummary()
</div>
@using (Html.BeginFormAntiForgeryPost("SetDescription"))
{
@Html.HiddenFor(m => m.ContentItemId)
@Html.HiddenFor(m => m.ContentItemVersionId)
@Html.Label(T("Edit the description").Text, new {@class = "editor-label"})
@Html.TextBoxFor(m => m.Description, new {@class = "textMedium"})
<fieldset>
<legend></legend>
<button class="primaryAction" type="submit">@T("Save")</button>
</fieldset>
}
</div>
@using (Script.Foot())
{
<script type="text/javascript">
document.getElementById("VersionManagerRecord_Description").focus();
</script>
} | bsd-2-clause | C# |
395d5f2eee14f9c6d7b5fc7dbb762146740237f2 | Fix NRE | jlucansky/refit,jlucansky/refit,onovotny/refit,paulcbetts/refit,paulcbetts/refit,PKRoma/refit,onovotny/refit | Refit/HttpUtility.NetStandard.cs | Refit/HttpUtility.NetStandard.cs | using Microsoft.AspNetCore.WebUtilities;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
namespace System.Web
{
class HttpUtility
{
internal static NameValueCollection ParseQueryString(string v)
{
var parsed = QueryHelpers.ParseQuery(v);
var all = from kvp in parsed
from val in kvp.Value
select new { kvp.Key, Value = val };
var nvc = new NameValueCollection();
foreach(var item in all) {
nvc.Add(item.Key, item.Value);
}
return nvc;
}
internal static string UrlEncode(string x) => UrlEncoder.Default.Encode(x);
}
}
| using Microsoft.AspNetCore.WebUtilities;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
namespace System.Web
{
class HttpUtility
{
internal static NameValueCollection ParseQueryString(string v)
{
var parsed = QueryHelpers.ParseNullableQuery(v);
var all = from kvp in parsed
from val in kvp.Value
select new { kvp.Key, Value = val };
var nvc = new NameValueCollection();
foreach(var item in all) {
nvc.Add(item.Key, item.Value);
}
return nvc;
}
internal static string UrlEncode(string x) => UrlEncoder.Default.Encode(x);
}
}
| mit | C# |
237d87bc143fc4b8593b465d8b50b2aa2ab610ce | Add MessageCountPart to Recipient object | messagebird/csharp-rest-api | MessageBird/Objects/Recipient.cs | MessageBird/Objects/Recipient.cs | using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace MessageBird.Objects
{
public class Recipient
{
public enum RecipientStatus
{
// Message status
[EnumMember(Value = "scheduled")]
Scheduled,
[EnumMember(Value = "sent")]
Sent,
[EnumMember(Value = "buffered")]
Buffered,
[EnumMember(Value = "delivered")]
Delivered,
[EnumMember(Value = "delivery_failed")]
DeliveryFailed,
[EnumMember(Value = "expired")]
Expired,
// Voice message status
[EnumMember(Value = "calling")]
Calling,
[EnumMember(Value = "answered")]
Answered,
[EnumMember(Value = "failed")]
Failed,
// reserved for future use
[EnumMember(Value = "busy")]
Busy,
[EnumMember(Value = "machine")]
Machine
};
[JsonProperty("recipient")]
public long Msisdn { get; set; }
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public RecipientStatus? Status { get; set; }
[JsonProperty("statusDatetime")]
public DateTime? StatusDatetime { get; set; }
[JsonProperty("messagePartCount")]
public int MessagePartCount { get; set; }
public Recipient(long msisdn)
{
Msisdn = msisdn;
}
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace MessageBird.Objects
{
public class Recipient
{
public enum RecipientStatus
{
// Message status
[EnumMember(Value = "scheduled")]
Scheduled,
[EnumMember(Value = "sent")]
Sent,
[EnumMember(Value = "buffered")]
Buffered,
[EnumMember(Value = "delivered")]
Delivered,
[EnumMember(Value = "delivery_failed")]
DeliveryFailed,
[EnumMember(Value = "expired")]
Expired,
// Voice message status
[EnumMember(Value = "calling")]
Calling,
[EnumMember(Value = "answered")]
Answered,
[EnumMember(Value = "failed")]
Failed,
// reserved for future use
[EnumMember(Value = "busy")]
Busy,
[EnumMember(Value = "machine")]
Machine
};
[JsonProperty("recipient")]
public long Msisdn { get; set; }
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public RecipientStatus? Status { get; set; }
[JsonProperty("statusDatetime")]
public DateTime? StatusDatetime { get; set; }
public Recipient(long msisdn)
{
Msisdn = msisdn;
}
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| isc | C# |
f8b523942216ceb05d389c44c751edfd6a948ff8 | Update Assorted.cs | mcintyre321/OneOf | OneOf/Types/Assorted.cs | OneOf/Types/Assorted.cs |
namespace OneOf.Types
{
public struct Yes { }
public struct No { }
public struct Maybe { }
public struct Unknown { }
public struct True { }
public struct False { }
public struct All { }
public struct Some { }
public struct None
{
public static OneOf<T, None> Of<T>(T t) => new None();
}
public struct NotFound { }
public struct Success { }
public struct Success<T>
{
public Success(T value)
{
Value = value;
}
public T Value { get; }
}
public struct Result<T>
{
public Result(T value)
{
Value = value;
}
public T Value { get; }
}
public struct Error { }
public struct Error<T>
{
public Error(T value)
{
Value = value;
}
public T Value { get; }
}
}
|
namespace OneOf.Types
{
public struct Yes { }
public struct No { }
public struct Maybe { }
public struct Unknown { }
public struct True { }
public struct False { }
public struct All { }
public struct Some { }
public struct None { }
public struct NotFound { }
public struct Success { }
public struct Success<T>
{
public Success(T value)
{
Value = value;
}
public T Value { get; }
}
public struct Result<T>
{
public Result(T value)
{
Value = value;
}
public T Value { get; }
}
public struct Error { }
public struct Error<T>
{
public Error(T value)
{
Value = value;
}
public T Value { get; }
}
}
| mit | C# |
70caa51a8ab52503cc33d4db4a67b60c9399e127 | add assembly properties | andrewyakonyuk/NBass | NBass/Properties/AssemblyInfo.cs | NBass/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Resources;
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("NBass")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NBass")]
[assembly: AssemblyCopyright("")]
[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("6b63b779-32b9-42ed-9a27-2148b6d9bf70")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
| 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("NBass")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NBass")]
[assembly: AssemblyCopyright("")]
[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("6b63b779-32b9-42ed-9a27-2148b6d9bf70")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| mit | C# |
79af77ac511c14e01cb5d43ccdccbfa2bc04213f | 修改 xml | toolgood/ToolGood.ReadyGo,toolgood/ToolGood.ReadyGo | ToolGood.ReadyGo3/Gadget/Events/SqlErrorEventArgs.cs | ToolGood.ReadyGo3/Gadget/Events/SqlErrorEventArgs.cs | using System;
namespace ToolGood.ReadyGo3.Gadget.Events
{
/// <summary>
/// sql错误事件事件参数
/// </summary>
public class SqlErrorEventArgs : System.EventArgs
{
/// <summary>
/// sql错误事件事件参数
/// </summary>
/// <param name="sql"></param>
/// <param name="args"></param>
/// <param name="sqlWithArgs"></param>
/// <param name="exception"></param>
public SqlErrorEventArgs(string sql, object[] args, string sqlWithArgs, Exception exception)
{
SqlWithArgs = sqlWithArgs;
Exception = exception;
ErrorMsg = exception.Message;
Sql = sql;
Args = args;
Handle = false;
}
/// <summary>
///
/// </summary>
public Exception Exception;
/// <summary>
/// Sql语句
/// </summary>
public string Sql;
/// <summary>
/// 参数
/// </summary>
public object[] Args;
/// <summary>
/// Sql语句+参数
/// </summary>
public string SqlWithArgs;
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMsg;
/// <summary>
/// 是否处理
/// </summary>
public bool Handle;
}
/// <summary>
/// sql错误事件事件处理
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public delegate void SqlErrorEventHandler(object sender, SqlErrorEventArgs args);
} | using System;
namespace ToolGood.ReadyGo3.Gadget.Events
{
/// <summary>
/// sql错误事件事件参数
/// </summary>
public class SqlErrorEventArgs : System.EventArgs
{
/// <summary>
/// sql错误事件事件参数
/// </summary>
/// <param name="sql"></param>
/// <param name="args"></param>
/// <param name="sqlWithArgs"></param>
/// <param name="errorMsg"></param>
public SqlErrorEventArgs(string sql, object[] args, string sqlWithArgs, Exception exception)
{
SqlWithArgs = sqlWithArgs;
Exception = exception;
ErrorMsg = exception.Message;
Sql = sql;
Args = args;
Handle = false;
}
/// <summary>
///
/// </summary>
public Exception Exception;
/// <summary>
/// Sql语句
/// </summary>
public string Sql;
/// <summary>
/// 参数
/// </summary>
public object[] Args;
/// <summary>
/// Sql语句+参数
/// </summary>
public string SqlWithArgs;
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMsg;
/// <summary>
/// 是否处理
/// </summary>
public bool Handle;
}
/// <summary>
/// sql错误事件事件处理
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public delegate void SqlErrorEventHandler(object sender, SqlErrorEventArgs args);
} | apache-2.0 | C# |
7ee0c26c855d472e63be063d64bd6866e10aacc5 | Add WriteAttributeStringAsync | AMDL/amdl2maml | amdl2maml/Converter/Writers/BlockWriter.cs | amdl2maml/Converter/Writers/BlockWriter.cs | using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Xml;
namespace Amdl.Maml.Converter.Writers
{
class BlockWriter
{
private readonly XmlWriter writer;
public BlockWriter(XmlWriter writer)
{
this.writer = writer;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteStartElementAsync(string localName)
{
return writer.WriteStartElementAsync(null, localName, null);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteEndElementAsync()
{
return writer.WriteEndElementAsync();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteAttributeStringAsync(string localName, string value)
{
return writer.WriteAttributeStringAsync(null, localName, null, value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value)
{
return writer.WriteAttributeStringAsync(prefix, localName, ns, value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteStringAsync(string text)
{
return writer.WriteStringAsync(text);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteRawAsync(string text)
{
return writer.WriteRawAsync(text);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteCommentAsync(string text)
{
return writer.WriteCommentAsync(text);
}
}
}
| using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Xml;
namespace Amdl.Maml.Converter.Writers
{
class BlockWriter
{
private readonly XmlWriter writer;
public BlockWriter(XmlWriter writer)
{
this.writer = writer;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteStartElementAsync(string localName)
{
return writer.WriteStartElementAsync(null, localName, null);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteEndElementAsync()
{
return writer.WriteEndElementAsync();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteStringAsync(string text)
{
return writer.WriteStringAsync(text);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteRawAsync(string text)
{
return writer.WriteRawAsync(text);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Task WriteCommentAsync(string text)
{
return writer.WriteCommentAsync(text);
}
}
}
| apache-2.0 | C# |
c0f39514b9aba1295ba168ad29b541ba92d4b1a7 | Fix legacy droplet scale | NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu | osu.Game.Rulesets.Catch/Skinning/LegacyDropletPiece.cs | osu.Game.Rulesets.Catch/Skinning/LegacyDropletPiece.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Textures;
using osuTK;
namespace osu.Game.Rulesets.Catch.Skinning
{
public class LegacyDropletPiece : LegacyCatchHitObjectPiece
{
public LegacyDropletPiece()
{
Scale = new Vector2(0.8f);
}
protected override void LoadComplete()
{
base.LoadComplete();
Texture texture = Skin.GetTexture("fruit-drop");
Texture overlayTexture = Skin.GetTexture("fruit-drop-overlay");
SetTexture(texture, overlayTexture);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Textures;
namespace osu.Game.Rulesets.Catch.Skinning
{
public class LegacyDropletPiece : LegacyCatchHitObjectPiece
{
protected override void LoadComplete()
{
base.LoadComplete();
Texture texture = Skin.GetTexture("fruit-drop");
Texture overlayTexture = Skin.GetTexture("fruit-drop-overlay");
SetTexture(texture, overlayTexture);
}
}
}
| mit | C# |
4e85478f1e1bd8caf508f1b42012deffa53c9ec2 | Fix login link on register page | erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner | Zk/Views/Account/Register.cshtml | Zk/Views/Account/Register.cshtml | @{
ViewBag.Title = "Registreer je vandaag bij de Oogstplanner";
}
<div class="flowtype-area">
<!-- START RESPONSIVE RECTANGLE LAYOUT -->
<!-- Top bar -->
<div id="top">
</div>
<!-- Fixed main screen -->
<div id="login" class="bg imglogin">
<div class="row">
<div class="mainbox col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Registreer je vandaag bij de Oogstplanner</div>
<div class="panel-side-link">
@Html.ActionLink("Inloggen", "Login")
</div>
</div>
<div class="panel-body">
@{ Html.RenderPartial("_RegisterForm"); }
</div><!-- End panel body -->
</div><!-- End panel -->
</div><!-- End signup box -->
</div><!-- End row -->
</div><!-- End main login div -->
<!-- END RESPONSIVE RECTANGLES LAYOUT -->
</div><!-- End flowtype-area --> | @{
ViewBag.Title = "Registreer je vandaag bij de Oogstplanner";
}
<div class="flowtype-area">
<!-- START RESPONSIVE RECTANGLE LAYOUT -->
<!-- Top bar -->
<div id="top">
</div>
<!-- Fixed main screen -->
<div id="login" class="bg imglogin">
<div class="row">
<div class="mainbox col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Registreer je vandaag bij de Oogstplanner</div>
<div class="panel-side-link">
<a id="signin-link" href="#">Inloggen</a>
</div>
</div>
<div class="panel-body">
@{ Html.RenderPartial("_RegisterForm"); }
</div><!-- End panel body -->
</div><!-- End panel -->
</div><!-- End signup box -->
</div><!-- End row -->
</div><!-- End main login div -->
<!-- END RESPONSIVE RECTANGLES LAYOUT -->
</div><!-- End flowtype-area --> | mit | C# |
665da09ed76c5a74bd688ddf2a41c5dd325b3ba7 | disable HD for taiko | johnneijzen/osu,2yangk23/osu,smoogipooo/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,ZLima12/osu,2yangk23/osu,smoogipoo/osu,ZLima12/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu-new,UselessToucan/osu,johnneijzen/osu,ppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,ppy/osu | osu.Game.Rulesets.Taiko/Mods/TaikoModHidden.cs | osu.Game.Rulesets.Taiko/Mods/TaikoModHidden.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModHidden : ModHidden
{
public override string Description => @"Beats fade out before you hit them!";
public override double ScoreMultiplier => 1.06;
public override bool HasImplementation => false;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Mods
{
public class TaikoModHidden : ModHidden
{
public override string Description => @"Beats fade out before you hit them!";
public override double ScoreMultiplier => 1.06;
}
}
| mit | C# |
24d51748be139edfa10947f1bbea931144f015dc | Remove unused field | whampson/cascara,whampson/bft-spec | Src/WHampson.Bft/TemplateFile.cs | Src/WHampson.Bft/TemplateFile.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace WHampson.Bft
{
public sealed class TemplateFile
{
private static XDocument OpenXmlFile(string path)
{
try
{
return XDocument.Load(path, LoadOptions.SetLineInfo);
}
catch (XmlException e)
{
throw new TemplateException(e.Message, e);
}
}
private XDocument doc;
public TemplateFile(string path)
{
doc = OpenXmlFile(path);
}
public T Process<T>(string filePath)
{
TemplateProcessor processor = new TemplateProcessor(doc);
return processor.Process<T>(filePath);
}
public string this[string key]
{
// Get template metadata (Root element attribute values)
get
{
XAttribute attr = doc.Root.Attribute(key);
return (attr != null) ? attr.Value : null;
}
}
}
} | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace WHampson.Bft
{
public sealed class TemplateFile
{
private static XDocument OpenXmlFile(string path)
{
try
{
return XDocument.Load(path, LoadOptions.SetLineInfo);
}
catch (XmlException e)
{
throw new TemplateException(e.Message, e);
}
}
private XDocument doc;
private TemplateProcessor processor;
public TemplateFile(string path)
{
doc = OpenXmlFile(path);
}
public T Process<T>(string filePath)
{
TemplateProcessor processor = new TemplateProcessor(doc);
return processor.Process<T>(filePath);
}
public string this[string key]
{
// Get template metadata (Root element attribute values)
get
{
XAttribute attr = doc.Root.Attribute(key);
return (attr != null) ? attr.Value : null;
}
}
}
} | mit | C# |
30af76cadb35983bf23a343fc5bf00c1a8e14963 | Add language option to Find | LordMike/TMDbLib | TMDbLib/Client/TMDbClientFind.cs | TMDbLib/Client/TMDbClientFind.cs | using System.Net;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Find;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// FindAsync movies, people and tv shows by an external id.
/// The following types can be found based on the specified external id's
/// - Movies: Imdb
/// - People: Imdb, FreeBaseMid, FreeBaseId, TvRage
/// - TV Series: Imdb, FreeBaseMid, FreeBaseId, TvRage, TvDb
/// </summary>
/// <param name="source">The source the specified id belongs to</param>
/// <param name="id">The id of the object you wish to located</param>
/// <returns>A list of all objects in TMDb that matched your id</returns>
/// <param name="cancellationToken">A cancellation token</param>
public Task<FindContainer> FindAsync(FindExternalSource source, string id, CancellationToken cancellationToken = default(CancellationToken))
{
return FindAsync(source, id, null, cancellationToken);
}
/// <summary>
/// FindAsync movies, people and tv shows by an external id.
/// The following types can be found based on the specified external id's
/// - Movies: Imdb
/// - People: Imdb, FreeBaseMid, FreeBaseId, TvRage
/// - TV Series: Imdb, FreeBaseMid, FreeBaseId, TvRage, TvDb
/// </summary>
/// <param name="source">The source the specified id belongs to</param>
/// <param name="id">The id of the object you wish to located</param>
/// <returns>A list of all objects in TMDb that matched your id</returns>
/// <param name="language">If specified the api will attempt to return a localized result. ex: en,it,es.</param>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<FindContainer> FindAsync(FindExternalSource source, string id, string language, CancellationToken cancellationToken = default(CancellationToken))
{
RestRequest req = _client.Create("find/{id}");
req.AddUrlSegment("id", WebUtility.UrlEncode(id));
req.AddParameter("external_source", source.GetDescription());
language = language ?? DefaultLanguage;
if (!string.IsNullOrEmpty(language))
req.AddParameter("language", language);
RestResponse<FindContainer> resp = await req.ExecuteGet<FindContainer>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
} | using System.Net;
using System.Threading;
using System.Threading.Tasks;
using TMDbLib.Objects.Find;
using TMDbLib.Rest;
using TMDbLib.Utilities;
namespace TMDbLib.Client
{
public partial class TMDbClient
{
/// <summary>
/// FindAsync movies, people and tv shows by an external id.
/// The following trypes can be found based on the specified external id's
/// - Movies: Imdb
/// - People: Imdb, FreeBaseMid, FreeBaseId, TvRage
/// - TV Series: Imdb, FreeBaseMid, FreeBaseId, TvRage, TvDb
/// </summary>
/// <param name="source">The source the specified id belongs to</param>
/// <param name="id">The id of the object you wish to located</param>
/// <returns>A list of all objects in TMDb that matched your id</returns>
/// <param name="cancellationToken">A cancellation token</param>
public async Task<FindContainer> FindAsync(FindExternalSource source, string id, CancellationToken cancellationToken = default(CancellationToken))
{
RestRequest req = _client.Create("find/{id}");
req.AddUrlSegment("id", WebUtility.UrlEncode(id));
req.AddParameter("external_source", source.GetDescription());
RestResponse<FindContainer> resp = await req.ExecuteGet<FindContainer>(cancellationToken).ConfigureAwait(false);
return resp;
}
}
} | mit | C# |
1812b654a5156ea5365789175d81779022c441f7 | add null checks for Text and Html. | l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto | Source/Eto/Forms/Clipboard.cs | Source/Eto/Forms/Clipboard.cs | using System;
using Eto;
using Eto.Drawing;
using System.IO;
namespace Eto.Forms
{
public interface IClipboard : IInstanceWidget
{
string[] Types { get; }
void SetString (string value, string type);
void SetData (byte[] value, string type);
string GetString (string type);
byte[] GetData (string type);
string Text { get; set; }
string Html { get; set; }
Image Image { get; set; }
void Clear ();
}
public class Clipboard : InstanceWidget
{
IClipboard handler;
public Clipboard ()
: this(Generator.Current)
{
}
public Clipboard (Generator generator)
: base(generator, typeof(IClipboard))
{
handler = (IClipboard)Handler;
}
public string[] Types {
get { return handler.Types; }
}
public void SetDataStream (Stream stream, string type)
{
byte[] buffer = new byte[stream.Length];
if (stream.CanSeek && stream.Position != 0)
stream.Seek (0, SeekOrigin.Begin);
stream.Read (buffer, 0, buffer.Length);
SetData (buffer, type);
}
public void SetData (byte[] value, string type)
{
handler.SetData (value, type);
}
public byte[] GetData (string type)
{
return handler.GetData (type);
}
public Stream GetDataStream (string type)
{
var buffer = GetData (type);
if (buffer != null)
return new MemoryStream (buffer, false);
else
return null;
}
public void SetString (string value, string type)
{
handler.SetString (value, type);
}
public string GetString (string type)
{
return handler.GetString (type);
}
public string Text {
get { return handler.Text; }
set { handler.Text = value ?? ""; } // null check for consistency across platforms (Winforms throws an exception)
}
public string Html {
get { return handler.Html; }
set { handler.Html = value ?? ""; } // null check for consistency across platforms (Winforms throws an exception)
}
public Image Image {
get { return handler.Image; }
set { handler.Image = value; }
}
public void Clear ()
{
handler.Clear ();
}
}
}
| using System;
using Eto;
using Eto.Drawing;
using System.IO;
namespace Eto.Forms
{
public interface IClipboard : IInstanceWidget
{
string[] Types { get; }
void SetString (string value, string type);
void SetData (byte[] value, string type);
string GetString (string type);
byte[] GetData (string type);
string Text { get; set; }
string Html { get; set; }
Image Image { get; set; }
void Clear ();
}
public class Clipboard : InstanceWidget
{
IClipboard handler;
public Clipboard ()
: this(Generator.Current)
{
}
public Clipboard (Generator generator)
: base(generator, typeof(IClipboard))
{
handler = (IClipboard)Handler;
}
public string[] Types {
get { return handler.Types; }
}
public void SetDataStream (Stream stream, string type)
{
byte[] buffer = new byte[stream.Length];
if (stream.CanSeek && stream.Position != 0)
stream.Seek (0, SeekOrigin.Begin);
stream.Read (buffer, 0, buffer.Length);
SetData (buffer, type);
}
public void SetData (byte[] value, string type)
{
handler.SetData (value, type);
}
public byte[] GetData (string type)
{
return handler.GetData (type);
}
public Stream GetDataStream (string type)
{
var buffer = GetData (type);
if (buffer != null)
return new MemoryStream (buffer, false);
else
return null;
}
public void SetString (string value, string type)
{
handler.SetString (value, type);
}
public string GetString (string type)
{
return handler.GetString (type);
}
public string Text {
get { return handler.Text; }
set { handler.Text = value; }
}
public string Html {
get { return handler.Html; }
set { handler.Html = value; }
}
public Image Image {
get { return handler.Image; }
set { handler.Image = value; }
}
public void Clear ()
{
handler.Clear ();
}
}
}
| bsd-3-clause | C# |
771972cb3737df32719984f40d0ea542ca4e9d0e | Add Document.EmbeddedSource for later | fnajera-rac-de/cecil,jbevain/cecil,sailro/cecil,mono/cecil | Mono.Cecil.Cil/Document.cs | Mono.Cecil.Cil/Document.cs | //
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
namespace Mono.Cecil.Cil {
public enum DocumentType {
Other,
Text,
}
public enum DocumentHashAlgorithm {
None,
MD5,
SHA1,
SHA256,
}
public enum DocumentLanguage {
Other,
C,
Cpp,
CSharp,
Basic,
Java,
Cobol,
Pascal,
Cil,
JScript,
Smc,
MCpp,
FSharp,
}
public enum DocumentLanguageVendor {
Other,
Microsoft,
}
public sealed class Document : DebugInformation {
string url;
Guid type;
Guid hash_algorithm;
Guid language;
Guid language_vendor;
byte [] hash;
byte [] embedded_source;
public string Url {
get { return url; }
set { url = value; }
}
public DocumentType Type {
get { return type.ToType (); }
set { type = value.ToGuid (); }
}
public Guid TypeGuid {
get { return type; }
set { type = value; }
}
public DocumentHashAlgorithm HashAlgorithm {
get { return hash_algorithm.ToHashAlgorithm (); }
set { hash_algorithm = value.ToGuid (); }
}
public Guid HashAlgorithmGuid {
get { return hash_algorithm; }
set { hash_algorithm = value; }
}
public DocumentLanguage Language {
get { return language.ToLanguage (); }
set { language = value.ToGuid (); }
}
public Guid LanguageGuid {
get { return language; }
set { language = value; }
}
public DocumentLanguageVendor LanguageVendor {
get { return language_vendor.ToVendor (); }
set { language_vendor = value.ToGuid (); }
}
public Guid LanguageVendorGuid {
get { return language_vendor; }
set { language_vendor = value; }
}
public byte [] Hash {
get { return hash; }
set { hash = value; }
}
public byte[] EmbeddedSource {
get { return embedded_source; }
set { embedded_source = value; }
}
public Document (string url)
{
this.url = url;
this.hash = Empty<byte>.Array;
this.embedded_source = Empty<byte>.Array;
this.token = new MetadataToken (TokenType.Document);
}
}
}
| //
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
namespace Mono.Cecil.Cil {
public enum DocumentType {
Other,
Text,
}
public enum DocumentHashAlgorithm {
None,
MD5,
SHA1,
SHA256,
}
public enum DocumentLanguage {
Other,
C,
Cpp,
CSharp,
Basic,
Java,
Cobol,
Pascal,
Cil,
JScript,
Smc,
MCpp,
FSharp,
}
public enum DocumentLanguageVendor {
Other,
Microsoft,
}
public sealed class Document : DebugInformation {
string url;
Guid type;
Guid hash_algorithm;
Guid language;
Guid language_vendor;
byte [] hash;
public string Url {
get { return url; }
set { url = value; }
}
public DocumentType Type {
get { return type.ToType (); }
set { type = value.ToGuid (); }
}
public Guid TypeGuid {
get { return type; }
set { type = value; }
}
public DocumentHashAlgorithm HashAlgorithm {
get { return hash_algorithm.ToHashAlgorithm (); }
set { hash_algorithm = value.ToGuid (); }
}
public Guid HashAlgorithmGuid {
get { return hash_algorithm; }
set { hash_algorithm = value; }
}
public DocumentLanguage Language {
get { return language.ToLanguage (); }
set { language = value.ToGuid (); }
}
public Guid LanguageGuid {
get { return language; }
set { language = value; }
}
public DocumentLanguageVendor LanguageVendor {
get { return language_vendor.ToVendor (); }
set { language_vendor = value.ToGuid (); }
}
public Guid LanguageVendorGuid {
get { return language_vendor; }
set { language_vendor = value; }
}
public byte [] Hash {
get { return hash; }
set { hash = value; }
}
public Document (string url)
{
this.url = url;
this.hash = Empty<byte>.Array;
this.token = new MetadataToken (TokenType.Document);
}
}
}
| mit | C# |
8698ccb086c4d3062bb95e91a8c7cc0c35697c52 | add api for update cards | netxph/cards | src/Cards.Web/Controllers/Api/CardsController.cs | src/Cards.Web/Controllers/Api/CardsController.cs | using Cards.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Cards.Web.Controllers.Api
{
public class CardsController : ApiController
{
public Card Post(Card card)
{
return Card.Create(card.Name, card.AreaID);
}
public Card Put(int id, Card card)
{
return Card.Update(id, card.Name, card.AreaID);
}
}
}
| using Cards.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Cards.Web.Controllers.Api
{
public class CardsController : ApiController
{
public Card Create(Card card)
{
return Card.Create(card.Name, card.AreaID);
}
}
}
| mit | C# |
cb5b3d8e57698dbac830ed8cc172669e529465c7 | Simplify x86 hook | diryboy/roslyn,heejaechang/roslyn,wvdd007/roslyn,weltkante/roslyn,weltkante/roslyn,dotnet/roslyn,weltkante/roslyn,tmat/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,eriawan/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,mavasani/roslyn,physhi/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,tmat/roslyn,jasonmalinowski/roslyn,physhi/roslyn,tmat/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,tannergooding/roslyn,diryboy/roslyn,tannergooding/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,diryboy/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,eriawan/roslyn,dotnet/roslyn,physhi/roslyn,AlekseyTs/roslyn | src/EditorFeatures/XunitHook/XunitDisposeHook.cs | src/EditorFeatures/XunitHook/XunitDisposeHook.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
internal sealed class XunitDisposeHook : MarshalByRefObject
{
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Invoked across app domains")]
public void Execute()
{
if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
throw new InvalidOperationException();
var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray();
foreach (var xunitUtility in xunitUtilities)
{
var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain");
if (appDomainManagerType is null)
continue;
var method = appDomainManagerType.GetMethod("Dispose");
RuntimeHelpers.PrepareMethod(method.MethodHandle);
var functionPointer = method.MethodHandle.GetFunctionPointer();
if (IntPtr.Size == 4)
{
// Overwrite the compiled method to just return
// ret
Marshal.WriteByte(functionPointer, 0xC3);
}
else
{
// Overwrite the compiled method to just return
// ret
Marshal.WriteByte(functionPointer, 0xC3);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
internal sealed class XunitDisposeHook : MarshalByRefObject
{
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Invoked across app domains")]
public void Execute()
{
if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
throw new InvalidOperationException();
var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray();
foreach (var xunitUtility in xunitUtilities)
{
var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain");
if (appDomainManagerType is null)
continue;
var method = appDomainManagerType.GetMethod("Dispose");
RuntimeHelpers.PrepareMethod(method.MethodHandle);
var functionPointer = method.MethodHandle.GetFunctionPointer();
if (IntPtr.Size == 4)
{
// Overwrite the compiled method to just return
var offset = 0;
// push ebp
Marshal.WriteByte(functionPointer, offset++, 0x55);
// mov ebp,esp
Marshal.WriteByte(functionPointer, offset++, 0x8B);
Marshal.WriteByte(functionPointer, offset++, 0xEC);
// lea esp,[ebp-8]
Marshal.WriteByte(functionPointer, offset++, 0x8D);
Marshal.WriteByte(functionPointer, offset++, 0x65);
Marshal.WriteByte(functionPointer, offset++, 0xF8);
// pop ebp
Marshal.WriteByte(functionPointer, offset++, 0x5D);
// ret
Marshal.WriteByte(functionPointer, offset++, 0xC3);
}
else
{
// Overwrite the compiled method to just return
// ret
Marshal.WriteByte(functionPointer, 0xC3);
}
}
}
}
}
| mit | C# |
520dd682b0d38fd9d080c0eb5698d691e831a6e5 | Remove redundant class | simplcommerce/SimplCommerce,simplcommerce/SimplCommerce,simplcommerce/SimplCommerce,arst/SimplCommerce,arst/SimplCommerce,arst/SimplCommerce,arst/SimplCommerce,simplcommerce/SimplCommerce | src/HvCommerce.Web/RouteConfigs/CategoryRoute.cs | src/HvCommerce.Web/RouteConfigs/CategoryRoute.cs | using System;
using System.Threading.Tasks;
using HvCommerce.Core.ApplicationServices;
using Microsoft.AspNet.Routing;
namespace HvCommerce.Web.RouteConfigs
{
public class CategoryRoute : ICategoryRoute
{
private readonly IRouter _target;
private readonly ICategoryService _categoryService;
public CategoryRoute(ICategoryService categoryService, IRouter target)
{
_categoryService = categoryService;
_target = target;
}
public async Task RouteAsync(RouteContext context)
{
var requestPath = context.HttpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/')
{
// Trim the leading slash
requestPath = requestPath.Substring(1);
}
//Invoke MVC controller/action
var oldRouteData = context.RouteData;
var newRouteData = new RouteData(oldRouteData);
newRouteData.Routers.Add(this._target);
var isExistCategory = await _categoryService.CheckExistBySeoTitle(requestPath);
if (!isExistCategory)
{
return;
}
// TODO: (Idea) We might use objects from the database to get both the controller and action,
// and possibly even an area.
// Alternatively, we could create a route for each table and hard-code
// this information.
newRouteData.Values["controller"] = "Product";
newRouteData.Values["action"] = "ProductsByCategory";
newRouteData.Values["catSeoTitle"] = requestPath;
try
{
context.RouteData = newRouteData;
await this._target.RouteAsync(context);
}
finally
{
if (!context.IsHandled)
{
context.RouteData = oldRouteData;
}
}
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return null;
}
}
}
| using System;
using System.Threading.Tasks;
using HvCommerce.Core.ApplicationServices;
using Microsoft.AspNet.Routing;
namespace HvCommerce.Web.RouteConfigs
{
public class CategoryRoute : Attribute, ICategoryRoute
{
private readonly IRouter _target;
private readonly ICategoryService _categoryService;
public CategoryRoute(ICategoryService categoryService, IRouter target)
{
_categoryService = categoryService;
_target = target;
}
public async Task RouteAsync(RouteContext context)
{
var requestPath = context.HttpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/')
{
// Trim the leading slash
requestPath = requestPath.Substring(1);
}
//Invoke MVC controller/action
var oldRouteData = context.RouteData;
var newRouteData = new RouteData(oldRouteData);
newRouteData.Routers.Add(this._target);
var isExistCategory = await _categoryService.CheckExistBySeoTitle(requestPath);
if (!isExistCategory)
{
return;
}
// TODO: (Idea) We might use objects from the database to get both the controller and action,
// and possibly even an area.
// Alternatively, we could create a route for each table and hard-code
// this information.
newRouteData.Values["controller"] = "Product";
newRouteData.Values["action"] = "ProductsByCategory";
newRouteData.Values["catSeoTitle"] = requestPath;
try
{
context.RouteData = newRouteData;
await this._target.RouteAsync(context);
}
finally
{
if (!context.IsHandled)
{
context.RouteData = oldRouteData;
}
}
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return null;
}
}
}
| apache-2.0 | C# |
f4bb52452dce675da94a64504ceeddc4163d1bb0 | Add FolderScanProgress event | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/SyncThing/ApiClient/EventType.cs | src/SyncTrayzor/SyncThing/ApiClient/EventType.cs | using Newtonsoft.Json;
namespace SyncTrayzor.SyncThing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
RelayStateChanged,
ExternalPortMappingChanged,
FolderScanProgress
}
}
| using Newtonsoft.Json;
namespace SyncTrayzor.SyncThing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
RelayStateChanged,
ExternalPortMappingChanged,
}
}
| mit | C# |
390d3a30a0fc39be456469774045cb3cc0b414fd | Put comment text between quotes | igece/SoxSharp | src/OutputFormatOptions.cs | src/OutputFormatOptions.cs | using System.Text;
namespace SoxSharp
{
/// <summary>
/// Format options to be applied to the output file. For any property not set here, SoX will infer the value from the input file.
/// </summary>
public class OutputFormatOptions : FormatOptions
{
/// <summary>
/// Compression factor for output format.
/// </summary>
public double? Compression { get; set; }
/// <summary>
/// Set comment for output file.
/// </summary>
public string Comment { get; set; }
/// <summary>
/// Add comment to output file.
/// </summary>
public string AddComment { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:SoxSharp.OutputFormatOptions"/> class.
/// </summary>
public OutputFormatOptions()
: base()
{
}
/// <summary>
/// Translate a <see cref="OutputFormatOptions"/> instance to a set of command arguments to be passed to SoX (adds additional command arguments to <see cref="FormatOptions.ToString()"/>).
/// </summary>
/// <returns>String containing SoX command arguments.</returns>
public override string ToString()
{
StringBuilder outputOptions = new StringBuilder(base.ToString());
if (Compression.HasValue)
outputOptions.Append(" --compression " + Compression.Value);
if (AddComment != null)
outputOptions.Append(" --add-comment \"" + AddComment + "\"");
if (Comment != null)
outputOptions.Append(" --comment \"" + Comment + "\"");
return outputOptions.ToString();
}
}
}
| using System.Text;
namespace SoxSharp
{
/// <summary>
/// Format options to be applied to the output file. For any property not set here, SoX will infer the value from the input file.
/// </summary>
public class OutputFormatOptions : FormatOptions
{
/// <summary>
/// Compression factor for output format.
/// </summary>
public double? Compression { get; set; }
/// <summary>
/// Set comment for output file.
/// </summary>
public string Comment { get; set; }
/// <summary>
/// Add comment to output file.
/// </summary>
public string AddComment { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:SoxSharp.OutputFormatOptions"/> class.
/// </summary>
public OutputFormatOptions()
: base()
{
}
/// <summary>
/// Translate a <see cref="OutputFormatOptions"/> instance to a set of command arguments to be passed to SoX (adds additional command arguments to <see cref="FormatOptions.ToString()"/>).
/// </summary>
/// <returns>String containing SoX command arguments.</returns>
public override string ToString()
{
StringBuilder outputOptions = new StringBuilder(base.ToString());
if (Compression.HasValue)
outputOptions.Append(" --compression " + Compression.Value);
if (AddComment != null)
outputOptions.Append(" --add-comment " + AddComment);
if (Comment != null)
outputOptions.Append(" --comment " + Comment);
return outputOptions.ToString();
}
}
}
| apache-2.0 | C# |
f465d6e6d76256170b876c183e861427ff62c8a7 | remove whitespace at start of namespaces | DigDes/SoapCore | src/SoapCore/Namespaces.cs | src/SoapCore/Namespaces.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace SoapCore
{
public static class Namespaces
{
#pragma warning disable SA1310 // Field names must not contain underscore
public const string XMLNS_XSD = "http://www.w3.org/2001/XMLSchema";
public const string XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance";
public const string TRANSPORT_SCHEMA = "http://schemas.xmlsoap.org/soap/http";
public const string WSDL_NS = "http://schemas.xmlsoap.org/wsdl/";
public const string SOAP11_NS = "http://schemas.xmlsoap.org/wsdl/soap/";
public const string SOAP12_NS = "http://schemas.xmlsoap.org/wsdl/soap12/";
public const string SOAP11_ENVELOPE_NS = "http://schemas.xmlsoap.org/soap/envelope/";
public const string SOAP12_ENVELOPE_NS = "http://www.w3.org/2003/05/soap-envelope";
public const string ARRAYS_NS = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
public const string SYSTEM_NS = "http://schemas.datacontract.org/2004/07/System";
public const string DataContractNamespace = "http://schemas.datacontract.org/2004/07/";
public const string SERIALIZATION_NS = "http://schemas.microsoft.com/2003/10/Serialization/";
public const string WSP_NS = "http://schemas.xmlsoap.org/ws/2004/09/policy";
public const string WSAM_NS = "http://www.w3.org/2007/05/addressing/metadata";
public const string SystemData_NS = "http://schemas.datacontract.org/2004/07/System.Data";
#pragma warning restore SA1310 // Field names must not contain underscore
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace SoapCore
{
public static class Namespaces
{
#pragma warning disable SA1310 // Field names must not contain underscore
public const string XMLNS_XSD = " http://www.w3.org/2001/XMLSchema";
public const string XMLNS_XSI = " http://www.w3.org/2001/XMLSchema-instance";
public const string TRANSPORT_SCHEMA = " http://schemas.xmlsoap.org/soap/http";
public const string WSDL_NS = " http://schemas.xmlsoap.org/wsdl/";
public const string SOAP11_NS = " http://schemas.xmlsoap.org/wsdl/soap/";
public const string SOAP12_NS = " http://schemas.xmlsoap.org/wsdl/soap12/";
public const string SOAP11_ENVELOPE_NS = " http://schemas.xmlsoap.org/soap/envelope/";
public const string SOAP12_ENVELOPE_NS = " http://www.w3.org/2003/05/soap-envelope";
public const string ARRAYS_NS = " http://schemas.microsoft.com/2003/10/Serialization/Arrays";
public const string SYSTEM_NS = " http://schemas.datacontract.org/2004/07/System";
public const string DataContractNamespace = " http://schemas.datacontract.org/2004/07/";
public const string SERIALIZATION_NS = " http://schemas.microsoft.com/2003/10/Serialization/";
public const string WSP_NS = " http://schemas.xmlsoap.org/ws/2004/09/policy";
public const string WSAM_NS = " http://www.w3.org/2007/05/addressing/metadata";
public const string SystemData_NS = " http://schemas.datacontract.org/2004/07/System.Data";
#pragma warning restore SA1310 // Field names must not contain underscore
}
}
| mit | C# |
1317ebef46be20c147f9fc74c747cd4a9c66f926 | add variables | appharbor/AppHarbor.Web.Security | AppHarbor.Web.Security/KeyedHashValidation.cs | AppHarbor.Web.Security/KeyedHashValidation.cs | using System;
using System.Linq;
using System.Security.Cryptography;
namespace AppHarbor.Web.Security
{
public class KeyedHashValidation : Validation
{
private readonly KeyedHashAlgorithm _algorithm;
public KeyedHashValidation(KeyedHashAlgorithm algorithm, byte[] secretKey)
{
_algorithm = algorithm;
_algorithm.Key = secretKey;
}
public override void Dispose()
{
_algorithm.Dispose();
}
public override byte[] ComputeSignature(byte[] data)
{
return ComputeSignature(data, 0, data.Length);
}
private byte[] ComputeSignature(byte[] data, int offset, int count)
{
return _algorithm.ComputeHash(data, offset, count);
}
public override byte[] Sign(byte[] data)
{
var hashLength = _algorithm.HashSize / 8;
var signedMessageLength = data.Length + hashLength;
var signedMessage = new byte[signedMessageLength];
Buffer.BlockCopy(data, 0, signedMessage, 0, data.Length);
Buffer.BlockCopy(ComputeSignature(data), 0, signedMessage, data.Length, hashLength);
return signedMessage;
}
public override byte[] StripSignature(byte[] signedMessage)
{
var hashLength = _algorithm.HashSize / 8;
var dataLength = signedMessage.Length - hashLength;
var data = new byte[dataLength];
Buffer.BlockCopy(signedMessage, 0, data, 0, data.Length);
return data;
}
public override bool Validate(byte[] signedMessage)
{
var hashLength = _algorithm.HashSize / 8;
var dataLength = signedMessage.Length - hashLength;
return Validate(signedMessage, dataLength);
}
private bool Validate(byte[] signedMessage, int dataLength)
{
var validSignature = ComputeSignature(signedMessage, 0, dataLength);
return validSignature.SequenceEqual(signedMessage.Skip(dataLength));
}
}
public class KeyedHashValidation<T> : KeyedHashValidation where T : KeyedHashAlgorithm, new()
{
public KeyedHashValidation(byte[] key)
: base(new T(), key)
{
}
}
}
| using System;
using System.Linq;
using System.Security.Cryptography;
namespace AppHarbor.Web.Security
{
public class KeyedHashValidation : Validation
{
private readonly KeyedHashAlgorithm _algorithm;
public KeyedHashValidation(KeyedHashAlgorithm algorithm, byte[] secretKey)
{
_algorithm = algorithm;
_algorithm.Key = secretKey;
}
public override void Dispose()
{
_algorithm.Dispose();
}
public override byte[] ComputeSignature(byte[] data)
{
return ComputeSignature(data, 0, data.Length);
}
private byte[] ComputeSignature(byte[] data, int offset, int count)
{
return _algorithm.ComputeHash(data, offset, count);
}
public override byte[] Sign(byte[] data)
{
byte[] signedMessage = new byte[data.Length + _algorithm.HashSize / 8];
Buffer.BlockCopy(data, 0, signedMessage, 0, data.Length);
Buffer.BlockCopy(ComputeSignature(data), 0, signedMessage, data.Length, _algorithm.HashSize / 8);
return signedMessage;
}
public override byte[] StripSignature(byte[] signedMessage)
{
var data = new byte[signedMessage.Length - _algorithm.HashSize / 8];
Buffer.BlockCopy(signedMessage, 0, data, 0, data.Length);
return data;
}
public override bool Validate(byte[] signedMessage)
{
return Validate(signedMessage, signedMessage.Length - _algorithm.HashSize / 8);
}
private bool Validate(byte[] signedMessage, int dataLength)
{
byte[] validSignature = ComputeSignature(signedMessage, 0, dataLength);
return validSignature.SequenceEqual(signedMessage.Skip(dataLength));
}
}
public class KeyedHashValidation<T> : KeyedHashValidation where T : KeyedHashAlgorithm, new()
{
public KeyedHashValidation(byte[] key)
: base(new T(), key)
{
}
}
}
| mit | C# |
219d7cd51958519b96f4d9e4bb1d178700569655 | Add frozen tier support to ILM phases (#5354) (#5367) | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/XPack/Ilm/Phases.cs | src/Nest/XPack/Ilm/Phases.cs | // Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Runtime.Serialization;
namespace Nest
{
[ReadAs(typeof(Phases))]
public interface IPhases
{
[DataMember(Name = "cold")]
IPhase Cold { get; set; }
[DataMember(Name = "delete")]
IPhase Delete { get; set; }
[DataMember(Name = "hot")]
IPhase Hot { get; set; }
[DataMember(Name = "warm")]
IPhase Warm { get; set; }
[DataMember(Name = "frozen")]
IPhase Frozen { get; set; }
}
public class Phases : IPhases
{
public IPhase Cold { get; set; }
public IPhase Delete { get; set; }
public IPhase Hot { get; set; }
public IPhase Warm { get; set; }
public IPhase Frozen { get; set; }
}
public class PhasesDescriptor : DescriptorBase<PhasesDescriptor, IPhases>, IPhases
{
IPhase IPhases.Cold { get; set; }
IPhase IPhases.Delete { get; set; }
IPhase IPhases.Hot { get; set; }
IPhase IPhases.Warm { get; set; }
IPhase IPhases.Frozen { get; set; }
public PhasesDescriptor Warm(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Warm = v?.InvokeOrDefault(new PhaseDescriptor()));
public PhasesDescriptor Hot(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Hot = v?.InvokeOrDefault(new PhaseDescriptor()));
public PhasesDescriptor Cold(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Cold = v?.InvokeOrDefault(new PhaseDescriptor()));
public PhasesDescriptor Delete(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Delete = v?.InvokeOrDefault(new PhaseDescriptor()));
public PhasesDescriptor Frozen(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Frozen = v?.InvokeOrDefault(new PhaseDescriptor()));
}
}
| // Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Runtime.Serialization;
namespace Nest
{
[ReadAs(typeof(Phases))]
public interface IPhases
{
[DataMember(Name = "cold")]
IPhase Cold { get; set; }
[DataMember(Name = "delete")]
IPhase Delete { get; set; }
[DataMember(Name = "hot")]
IPhase Hot { get; set; }
[DataMember(Name = "warm")]
IPhase Warm { get; set; }
}
public class Phases : IPhases
{
public IPhase Cold { get; set; }
public IPhase Delete { get; set; }
public IPhase Hot { get; set; }
public IPhase Warm { get; set; }
}
public class PhasesDescriptor : DescriptorBase<PhasesDescriptor, IPhases>, IPhases
{
IPhase IPhases.Cold { get; set; }
IPhase IPhases.Delete { get; set; }
IPhase IPhases.Hot { get; set; }
IPhase IPhases.Warm { get; set; }
public PhasesDescriptor Warm(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Warm = v?.InvokeOrDefault(new PhaseDescriptor()));
public PhasesDescriptor Hot(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Hot = v?.InvokeOrDefault(new PhaseDescriptor()));
public PhasesDescriptor Cold(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Cold = v?.InvokeOrDefault(new PhaseDescriptor()));
public PhasesDescriptor Delete(Func<PhaseDescriptor, IPhase> selector) =>
Assign(selector, (a, v) => a.Delete = v?.InvokeOrDefault(new PhaseDescriptor()));
}
}
| apache-2.0 | C# |
70ea1d9f632bf176800153cb09859247c1bcc7ed | fix Firefox warning (#378) (Resolve #377) | DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit | AjaxControlToolkit/AjaxFileUpload/AjaxFileUploadHandler.cs | AjaxControlToolkit/AjaxFileUpload/AjaxFileUploadHandler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
namespace AjaxControlToolkit {
// Map this handler as AjaxFileUploadHandler.axd
public class AjaxFileUploadHandler : IHttpHandler, IReadOnlySessionState {
public bool IsReusable {
get { return true; }
}
public void ProcessRequest(HttpContext context) {
var request = context.Request;
if(request.QueryString["contextKey"] != AjaxFileUpload.ContextKey)
throw new Exception("Invalid context key");
if(request.Headers["Content-Type"] != null &&
request.Headers["Content-Type"].StartsWith("multipart/form-data;") &&
request.Headers["Content-Length"] != null)
AjaxFileUploadHelper.Process(context);
else
throw new Exception("Invalid upload request.");
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "text/plain";
context.Response.End();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
namespace AjaxControlToolkit {
// Map this handler as AjaxFileUploadHandler.axd
public class AjaxFileUploadHandler : IHttpHandler, IReadOnlySessionState {
public bool IsReusable {
get { return true; }
}
public void ProcessRequest(HttpContext context) {
var request = context.Request;
if(request.QueryString["contextKey"] != AjaxFileUpload.ContextKey)
throw new Exception("Invalid context key");
if(request.Headers["Content-Type"] != null &&
request.Headers["Content-Type"].StartsWith("multipart/form-data;") &&
request.Headers["Content-Length"] != null)
AjaxFileUploadHelper.Process(context);
else
throw new Exception("Invalid upload request.");
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.End();
}
}
}
| bsd-3-clause | C# |
d463ca39ba3f56f4de1e6f3ff48e0636a7d3241b | Update CopyingColumns.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Articles/CopyRowsColumns/CopyingColumns.cs | Examples/CSharp/Articles/CopyRowsColumns/CopyingColumns.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles.CopyRowsColumns
{
public class CopyingColumns
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a new Workbook
//Open an existing excel file
Workbook workbook = new Workbook(dataDir+ "aspose-sample.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Get the Cells collection
Cells cells = worksheet.Cells;
//Copy the first column to the third column
cells.CopyColumn(cells, 0, 2);
//Save the excel file
workbook.Save(dataDir+ "outaspose-sample.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles.CopyRowsColumns
{
public class CopyingColumns
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a new Workbook
//Open an existing excel file
Workbook workbook = new Workbook(dataDir+ "aspose-sample.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Get the Cells collection
Cells cells = worksheet.Cells;
//Copy the first column to the third column
cells.CopyColumn(cells, 0, 2);
//Save the excel file
workbook.Save(dataDir+ "outaspose-sample.out.xlsx");
}
}
} | mit | C# |
1df4ffe548ae6c77280cfef0a913372223bd59d3 | Build warning fix | simontaylor81/Syrup,simontaylor81/Syrup | ShaderEditorApp/ViewModel/Scene/ScenePrimitiveViewModel.cs | ShaderEditorApp/ViewModel/Scene/ScenePrimitiveViewModel.cs | using ReactiveUI;
using SlimDX;
using SRPCommon.Scene;
using SRPCommon.UserProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Text;
using System.Windows.Input;
namespace ShaderEditorApp.ViewModel.Scene
{
abstract class ScenePrimitiveViewModel : ReactiveObject, IHierarchicalBrowserNodeViewModel
{
private Primitive _primitive;
#region IHierarchicalBrowserNodeViewModel interface
public abstract string DisplayName { get; }
public IEnumerable<ICommand> Commands
{
get { return Enumerable.Empty<ICommand>(); }
}
public IEnumerable<IUserProperty> UserProperties
{
get { return _primitive.UserProperties; }
}
// No children
public IEnumerable<IHierarchicalBrowserNodeViewModel> Children { get { return null; } }
public ICommand DefaultCmd
{
get { return null; }
}
public bool IsDefault { get { return false; } }
#endregion
public static ScenePrimitiveViewModel Create(Primitive primitive)
{
var mesh = primitive as MeshInstancePrimitive;
var sphere = primitive as SpherePrimitive;
if (mesh != null)
{
return new MeshInstancePrimitiveViewModel(mesh);
}
else if (sphere != null)
{
return new SpherePrimitiveViewModel(sphere);
}
throw new ArgumentException("Unknown primitive type");
}
protected ScenePrimitiveViewModel(Primitive primitive)
{
_primitive = primitive;
}
}
}
| using ReactiveUI;
using SlimDX;
using SRPCommon.Scene;
using SRPCommon.UserProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Text;
using System.Windows.Input;
namespace ShaderEditorApp.ViewModel.Scene
{
abstract class ScenePrimitiveViewModel : ReactiveObject, IHierarchicalBrowserNodeViewModel
{
private Primitive _primitive;
#region IHierarchicalBrowserNodeViewModel interface
public abstract string DisplayName { get; }
public IEnumerable<ICommand> Commands
{
get { return Enumerable.Empty<ICommand>(); }
}
private IEnumerable<IUserProperty> _userProperties;
public IEnumerable<IUserProperty> UserProperties
{
get { return _primitive.UserProperties; }
}
// No children
public IEnumerable<IHierarchicalBrowserNodeViewModel> Children { get { return null; } }
public ICommand DefaultCmd
{
get { return null; }
}
public bool IsDefault { get { return false; } }
#endregion
public static ScenePrimitiveViewModel Create(Primitive primitive)
{
var mesh = primitive as MeshInstancePrimitive;
var sphere = primitive as SpherePrimitive;
if (mesh != null)
{
return new MeshInstancePrimitiveViewModel(mesh);
}
else if (sphere != null)
{
return new SpherePrimitiveViewModel(sphere);
}
throw new ArgumentException("Unknown primitive type");
}
protected ScenePrimitiveViewModel(Primitive primitive)
{
_primitive = primitive;
}
}
}
| mit | C# |
b2c5986544e0d94a0c5cb0d17bcb64c8274edec1 | Add MoveToBlock closes #15 | Yonom/BotBits,EEJesse/BotBits | BotBits/Packages/Actions/ActionsExtensions.cs | BotBits/Packages/Actions/ActionsExtensions.cs | namespace BotBits
{
public static class ActionsExtensions
{
public static void GetCrown(this Actions actions)
{
actions.GetCrown(0, 0);
}
public static void CompleteLevel(this Actions actions)
{
actions.CompleteLevel(0, 0);
}
public static void PressKey(this Actions actions, Key key)
{
actions.PressKey(key, 0, 0);
}
public static void MoveToBlock(this Actions actions, int x, int y)
{
actions.Move(x * 16, y * 16);
}
public static void Move(this Actions actions, int x, int y)
{
actions.Move(x, y, 0, 0, 0, 0, 0, 0);
}
public static void Move(this Actions actions,
int x, int y,
double speedX, double speedY,
double modifierX, double modifierY,
double horizontal, double vertical)
{
actions.Move(x, y, speedX, speedY, modifierX, modifierY, horizontal, vertical, false, false);
}
public static void Move(this Actions actions,
int x, int y,
double speedX, double speedY,
double modifierX, double modifierY,
double horizontal, double vertical,
bool spaceDown, bool spaceJustDown)
{
actions.Move(x, y, speedX, speedY, modifierX, modifierY, horizontal, vertical, spaceDown, spaceJustDown, 0);
}
}
} | namespace BotBits
{
public static class ActionsExtensions
{
public static void GetCrown(this Actions actions)
{
actions.GetCrown(0, 0);
}
public static void CompleteLevel(this Actions actions)
{
actions.CompleteLevel(0, 0);
}
public static void PressKey(this Actions actions, Key key)
{
actions.PressKey(key, 0, 0);
}
public static void Move(this Actions actions, int x, int y)
{
actions.Move(x, y, 0, 0, 0, 0, 0, 0);
}
public static void Move(this Actions actions,
int x, int y,
double speedX, double speedY,
double modifierX, double modifierY,
double horizontal, double vertical)
{
actions.Move(x, y, speedX, speedY, modifierX, modifierY, horizontal, vertical, false, false);
}
public static void Move(this Actions actions,
int x, int y,
double speedX, double speedY,
double modifierX, double modifierY,
double horizontal, double vertical,
bool spaceDown, bool spaceJustDown)
{
actions.Move(x, y, speedX, speedY, modifierX, modifierY, horizontal, vertical, spaceDown, spaceJustDown, 0);
}
}
} | mit | C# |
4bdde2b8b517724b44469a9dfb2e283b3d5be9a0 | Remove code that runs login screen | NiallHow/Software-Eng,M-Zuber/MyHome | MyHome.UI/Program.cs | MyHome.UI/Program.cs | using System;
using System.Collections.Generic;
using System.Windows.Forms;
using FrameWork;
namespace MyHome.UI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Globals.LogFiles["ProgramActivityLog"].AddMessage("The program was started at: " + DateTime.Now);
Application.Run(new MenuMDIUI());
// With the current configuration there is no login needed.
// The code is left as it may change soon, and while we do have source control it will be easier to simply uncomment this
// If the settings for connecting to the database are not set yet
//if (!Globals.SettingFiles["DatabaseSettings"].AreSettingsSet(
// new List<string>() { "Database Name", "User Id", "Password" }))
//{
// // Intializes and runs an instance of the login form
// Login connecting = new Login();
// Application.Run(connecting);
// // If the user enters correct connection parameters
// if (connecting.ConnectionSuccess)
// {
// // Runs the main application
// Application.Run(new MenuMDIUI());
// }
//}
//// If the database settings where previously set
//else
//{
// // Getse all the settings
// Dictionary<string, string> allSettings =
// Globals.SettingFiles["DatabaseSettings"].GetAllSettings();
// // Sets the local variables with the parameters saved in the database
// Globals.DataBaseName = allSettings["Database Name"];
// Globals.UserId = allSettings["User Id"];
// Globals.Password = allSettings["Password"];
// // Runs the main application
// Application.Run(new MenuMDIUI());
//}
Globals.LogFiles["ProgramActivityLog"].AddMessage("The program was closed at: " + DateTime.Now);
}
}
}
| using System;
using System.Collections.Generic;
using System.Windows.Forms;
using FrameWork;
namespace MyHome.UI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Globals.LogFiles["ProgramActivityLog"].AddMessage("The program was started at: " + DateTime.Now);
// If the settings for connecting to the database are not set yet
if (!Globals.SettingFiles["DatabaseSettings"].AreSettingsSet(
new List<string>() { "Database Name", "User Id", "Password" }))
{
// Intializes and runs an instance of the login form
Login connecting = new Login();
Application.Run(connecting);
// If the user enters correct connection parameters
if (connecting.ConnectionSuccess)
{
// Runs the main application
Application.Run(new MenuMDIUI());
}
}
// If the database settings where previously set
else
{
// Getse all the settings
Dictionary<string, string> allSettings =
Globals.SettingFiles["DatabaseSettings"].GetAllSettings();
// Sets the local variables with the parameters saved in the database
Globals.DataBaseName = allSettings["Database Name"];
Globals.UserId = allSettings["User Id"];
Globals.Password = allSettings["Password"];
// Runs the main application
Application.Run(new MenuMDIUI());
}
Globals.LogFiles["ProgramActivityLog"].AddMessage("The program was closed at: " + DateTime.Now);
}
}
}
| mit | C# |
77c3e930f6016c1c2aff0632e3dae30701c9391d | Fix for ?? operator priority | MassTransit/MassTransit,MassTransit/MassTransit,phatboyg/MassTransit,phatboyg/MassTransit | src/MassTransit.AmazonSqsTransport/Topology/AmazonSqsHostEqualityComparer.cs | src/MassTransit.AmazonSqsTransport/Topology/AmazonSqsHostEqualityComparer.cs | // Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.AmazonSqsTransport.Topology
{
using System;
using System.Collections.Generic;
public sealed class AmazonSqsHostEqualityComparer :
IEqualityComparer<AmazonSqsHostSettings>
{
public static IEqualityComparer<AmazonSqsHostSettings> Default { get; } = new AmazonSqsHostEqualityComparer();
public bool Equals(AmazonSqsHostSettings x, AmazonSqsHostSettings y)
{
if (ReferenceEquals(x, y))
return true;
if (ReferenceEquals(x, null))
return false;
if (ReferenceEquals(y, null))
return false;
return string.Equals(x.Region.SystemName, y.Region.SystemName, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(AmazonSqsHostSettings obj)
{
unchecked
{
var hashCode = obj.AccessKey?.GetHashCode() ?? 0;
hashCode = (hashCode * 397) ^ (obj.Region?.GetHashCode() ?? 0);
return hashCode;
}
}
}
}
| // Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.AmazonSqsTransport.Topology
{
using System;
using System.Collections.Generic;
public sealed class AmazonSqsHostEqualityComparer :
IEqualityComparer<AmazonSqsHostSettings>
{
public static IEqualityComparer<AmazonSqsHostSettings> Default { get; } = new AmazonSqsHostEqualityComparer();
public bool Equals(AmazonSqsHostSettings x, AmazonSqsHostSettings y)
{
if (ReferenceEquals(x, y))
return true;
if (ReferenceEquals(x, null))
return false;
if (ReferenceEquals(y, null))
return false;
return string.Equals(x.Region.SystemName, y.Region.SystemName, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(AmazonSqsHostSettings obj)
{
unchecked
{
var hashCode = obj.AccessKey?.GetHashCode() ?? 0;
hashCode = (hashCode * 397) ^ obj.Region?.GetHashCode() ?? 0;
return hashCode;
}
}
}
}
| apache-2.0 | C# |
c16fc06cb9fd28c21556f83855498985739e41e8 | Modify warning about policy behavior (#924) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Authorization/DefaultAuthorizationPolicyProvider.cs | src/Microsoft.AspNetCore.Authorization/DefaultAuthorizationPolicyProvider.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authorization
{
/// <summary>
/// The default implementation of a policy provider,
/// which provides a <see cref="AuthorizationPolicy"/> for a particular name.
/// </summary>
public class DefaultAuthorizationPolicyProvider : IAuthorizationPolicyProvider
{
private readonly AuthorizationOptions _options;
/// <summary>
/// Creates a new instance of <see cref="DefaultAuthorizationPolicyProvider"/>.
/// </summary>
/// <param name="options">The options used to configure this instance.</param>
public DefaultAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_options = options.Value;
}
/// <summary>
/// Gets the default authorization policy.
/// </summary>
/// <returns>The default authorization policy.</returns>
public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
{
return Task.FromResult(_options.DefaultPolicy);
}
/// <summary>
/// Gets a <see cref="AuthorizationPolicy"/> from the given <paramref name="policyName"/>
/// </summary>
/// <param name="policyName">The policy name to retrieve.</param>
/// <returns>The named <see cref="AuthorizationPolicy"/>.</returns>
public virtual Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
{
// MVC caches policies specifically for this class, so this method MUST return the same policy per
// policyName for every request or it could allow undesired access. It also must return synchronously.
// A change to either of these behaviors would require shipping a patch of MVC as well.
return Task.FromResult(_options.GetPolicy(policyName));
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authorization
{
/// <summary>
/// The default implementation of a policy provider,
/// which provides a <see cref="AuthorizationPolicy"/> for a particular name.
/// </summary>
public class DefaultAuthorizationPolicyProvider : IAuthorizationPolicyProvider
{
private readonly AuthorizationOptions _options;
/// <summary>
/// Creates a new instance of <see cref="DefaultAuthorizationPolicyProvider"/>.
/// </summary>
/// <param name="options">The options used to configure this instance.</param>
public DefaultAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_options = options.Value;
}
/// <summary>
/// Gets the default authorization policy.
/// </summary>
/// <returns>The default authorization policy.</returns>
public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
{
return Task.FromResult(_options.DefaultPolicy);
}
/// <summary>
/// Gets a <see cref="AuthorizationPolicy"/> from the given <paramref name="policyName"/>
/// </summary>
/// <param name="policyName">The policy name to retrieve.</param>
/// <returns>The named <see cref="AuthorizationPolicy"/>.</returns>
public virtual Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
{
// MVC relies on DefaultAuthorizationPolicyProvider providing the same policy for the same requests.
return Task.FromResult(_options.GetPolicy(policyName));
}
}
}
| apache-2.0 | C# |
9cec603d46ac5a550332e0c967b5f9a4bb62375d | Add RuntimeModeValidators() extension method | abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS | src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Collections.cs | src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Collections.cs | using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Packaging;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Infrastructure.Persistence.Mappers;
using Umbraco.Cms.Infrastructure.Runtime;
namespace Umbraco.Extensions;
/// <summary>
/// Provides extension methods to the <see cref="IUmbracoBuilder" /> class.
/// </summary>
public static partial class UmbracoBuilderExtensions
{
/// <summary>
/// Gets the mappers collection builder.
/// </summary>
/// <param name="builder">The builder.</param>
public static MapperCollectionBuilder? Mappers(this IUmbracoBuilder builder)
=> builder.WithCollectionBuilder<MapperCollectionBuilder>();
/// <summary>
/// Gets the NPoco mappers collection builder.
/// </summary>
/// <param name="builder">The builder.</param>
public static NPocoMapperCollectionBuilder? NPocoMappers(this IUmbracoBuilder builder)
=> builder.WithCollectionBuilder<NPocoMapperCollectionBuilder>();
/// <summary>
/// Gets the package migration plans collection builder.
/// </summary>
/// <param name="builder">The builder.</param>
public static PackageMigrationPlanCollectionBuilder? PackageMigrationPlans(this IUmbracoBuilder builder)
=> builder.WithCollectionBuilder<PackageMigrationPlanCollectionBuilder>();
/// <summary>
/// Gets the runtime mode validators collection builder.
/// </summary>
/// <param name="builder">The builder.</param>
public static RuntimeModeValidatorCollectionBuilder RuntimeModeValidators(this IUmbracoBuilder builder)
=> builder.WithCollectionBuilder<RuntimeModeValidatorCollectionBuilder>();
}
| using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Packaging;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Infrastructure.Persistence.Mappers;
namespace Umbraco.Extensions;
/// <summary>
/// Provides extension methods to the <see cref="IUmbracoBuilder" /> class.
/// </summary>
public static partial class UmbracoBuilderExtensions
{
/// <summary>
/// Gets the mappers collection builder.
/// </summary>
/// <param name="builder">The builder.</param>
public static MapperCollectionBuilder? Mappers(this IUmbracoBuilder builder)
=> builder.WithCollectionBuilder<MapperCollectionBuilder>();
public static NPocoMapperCollectionBuilder? NPocoMappers(this IUmbracoBuilder builder)
=> builder.WithCollectionBuilder<NPocoMapperCollectionBuilder>();
/// <summary>
/// Gets the package migration plans collection builder.
/// </summary>
/// <param name="builder">The builder.</param>
public static PackageMigrationPlanCollectionBuilder? PackageMigrationPlans(this IUmbracoBuilder builder)
=> builder.WithCollectionBuilder<PackageMigrationPlanCollectionBuilder>();
}
| mit | C# |
d787cde8102491a6ed09d05786d396b0704f646a | Add punctuation | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Gma/QrCodeNet/Encoding/DataEncodation/CharCountIndicatorTable.cs | WalletWasabi/Gma/QrCodeNet/Encoding/DataEncodation/CharCountIndicatorTable.cs | using System;
namespace Gma.QrCodeNet.Encoding.DataEncodation
{
public static class CharCountIndicatorTable
{
/// <remarks>ISO/IEC 18004:2000 Table 3 Page 18</remarks>
public static int[] GetCharCountIndicatorSet()
{
return new int[] { 8, 16, 16 };
}
public static int GetBitCountInCharCountIndicator(int version)
{
int[] charCountIndicatorSet = GetCharCountIndicatorSet();
int versionGroup = GetVersionGroup(version);
return charCountIndicatorSet[versionGroup];
}
/// <summary>
/// Used to define length of the Character Count Indicator <see cref="GetBitCountInCharCountIndicator"/>
/// </summary>
/// <returns>Returns the 0 based index of the row from Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator. </returns>
private static int GetVersionGroup(int version)
{
if (version > 40)
{
throw new InvalidOperationException($"Unexpected version: {version}.");
}
else if (version >= 27)
{
return 2;
}
else if (version >= 10)
{
return 1;
}
else if (version > 0)
{
return 0;
}
else
{
throw new InvalidOperationException($"Unexpected version: {version}.");
}
}
}
}
| using System;
namespace Gma.QrCodeNet.Encoding.DataEncodation
{
public static class CharCountIndicatorTable
{
/// <remarks>ISO/IEC 18004:2000 Table 3 Page 18</remarks>
public static int[] GetCharCountIndicatorSet()
{
return new int[] { 8, 16, 16 };
} //
public static int GetBitCountInCharCountIndicator(int version)
{
int[] charCountIndicatorSet = GetCharCountIndicatorSet();
int versionGroup = GetVersionGroup(version);
return charCountIndicatorSet[versionGroup];
}
/// <summary>
/// Used to define length of the Character Count Indicator <see cref="GetBitCountInCharCountIndicator"/>
/// </summary>
/// <returns>Returns the 0 based index of the row from Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator. </returns>
private static int GetVersionGroup(int version)
{
if (version > 40)
{
throw new InvalidOperationException($"Unexpected version: {version}");
}
else if (version >= 27)
{
return 2;
}
else if (version >= 10)
{
return 1;
}
else if (version > 0)
{
return 0;
}
else
{
throw new InvalidOperationException($"Unexpected version: {version}");
}
}
}
}
| mit | C# |
b22112350ae5c2fc591652f8553935c4a301cc87 | remove static | punker76/Markdown-Edit,jokamjohn/Markdown-Edit,dsuess/Markdown-Edit,mike-ward/Markdown-Edit,Tdue21/Markdown-Edit,chris84948/Markdown-Edit,Pulgafree/Markdown-Edit | src/MarkdownEdit/MarkdownConverters/CommonMarkConverter.cs | src/MarkdownEdit/MarkdownConverters/CommonMarkConverter.cs | using System;
using System.IO;
using System.Text.RegularExpressions;
using CommonMark;
using MarkdownEdit.Properties;
namespace MarkdownEdit
{
public class CommonMarkConverter : IMarkdownConverter
{
private readonly Func<string, string> _uriResolver = Utility.Memoize<string, string>(UriResolver);
public string ConvertToHtml(string markdown)
{
return CommonMark.CommonMarkConverter.Convert(markdown, new CommonMarkSettings {UriResolver = _uriResolver});
}
private static string UriResolver(string text)
{
if (Regex.IsMatch(text, @"^\w+://")) return text;
var lastOpen = Settings.Default.LastOpenFile;
if (string.IsNullOrEmpty(lastOpen)) return text;
var path = Path.GetDirectoryName(lastOpen);
if (string.IsNullOrEmpty(path)) return text;
var file = text.TrimStart('/');
return FindAsset(path, file) ?? text;
}
private static string FindAsset(string path, string file)
{
try
{
var asset = Path.Combine(path, file);
for (var i = 0; i < 4; ++i)
{
if (File.Exists(asset)) return "file://" + asset.Replace('\\', '/');
var parent = Directory.GetParent(path);
if (parent == null) break;
path = parent.FullName;
asset = Path.Combine(path, file);
}
}
catch (ArgumentException)
{
}
return null;
}
}
} | using System;
using System.IO;
using System.Text.RegularExpressions;
using CommonMark;
using MarkdownEdit.Properties;
namespace MarkdownEdit
{
public class CommonMarkConverter : IMarkdownConverter
{
private static readonly Func<string, string> _uriResolver = Utility.Memoize<string, string>(UriResolver);
public string ConvertToHtml(string markdown)
{
return CommonMark.CommonMarkConverter.Convert(markdown, new CommonMarkSettings {UriResolver = _uriResolver});
}
private static string UriResolver(string text)
{
if (Regex.IsMatch(text, @"^\w+://")) return text;
var lastOpen = Settings.Default.LastOpenFile;
if (string.IsNullOrEmpty(lastOpen)) return text;
var path = Path.GetDirectoryName(lastOpen);
if (string.IsNullOrEmpty(path)) return text;
var file = text.TrimStart('/');
return FindAsset(path, file) ?? text;
}
private static string FindAsset(string path, string file)
{
try
{
var asset = Path.Combine(path, file);
for (var i = 0; i < 4; ++i)
{
if (File.Exists(asset)) return "file://" + asset.Replace('\\', '/');
var parent = Directory.GetParent(path);
if (parent == null) break;
path = parent.FullName;
asset = Path.Combine(path, file);
}
}
catch (ArgumentException)
{
}
return null;
}
}
} | mit | C# |
a3d9fcc821b4b17ddecdd7164e90d16ba64f9169 | use the right sp! | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance/Data/ExpiredFundsRepository.cs | src/SFA.DAS.EmployerFinance/Data/ExpiredFundsRepository.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EmployerFinance.Extensions;
using SFA.DAS.NLog.Logger;
using SFA.DAS.Sql.Client;
using SFA.DAS.EmployerFinance.Models.ExpiredFunds;
namespace SFA.DAS.EmployerFinance.Data
{
public class ExpiredFundsRepository : BaseRepository, IExpiredFundsRepository
{
private readonly Lazy<EmployerFinanceDbContext> _db;
public ExpiredFundsRepository(string connectionString, ILog logger, Lazy<EmployerFinanceDbContext> db) : base(connectionString, logger)
{
_db = db;
}
public async Task Create(long accountId, IEnumerable<ExpiredFund> expiredFunds)
{
var expiredFundsTable = expiredFunds.ToExpiredFundsDataTable();
var parameters = new DynamicParameters();
parameters.Add("@accountId", accountId);
parameters.Add("@expiredFunds", expiredFundsTable.AsTableValuedParameter("[employer_financial].[ExpiredFundsTable]"));
await _db.Value.Database.Connection.ExecuteAsync(
sql: "[employer_financial].[CreateExpiredFunds]",
param: parameters,
transaction: _db.Value.Database.CurrentTransaction.UnderlyingTransaction,
commandType: CommandType.StoredProcedure);
}
public async Task<IEnumerable<ExpiredFund>> Get(long accountId)
{
var parameters = new DynamicParameters();
parameters.Add("@AccountId", accountId);
return await _db.Value.Database.Connection.QueryAsync<ExpiredFund>(
"[employer_financial].[GetExpiredFunds]",
param: parameters,
transaction: _db.Value.Database.CurrentTransaction.UnderlyingTransaction,
commandType: CommandType.StoredProcedure
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EmployerFinance.Extensions;
using SFA.DAS.NLog.Logger;
using SFA.DAS.Sql.Client;
using SFA.DAS.EmployerFinance.Models.ExpiredFunds;
namespace SFA.DAS.EmployerFinance.Data
{
public class ExpiredFundsRepository : BaseRepository, IExpiredFundsRepository
{
private readonly Lazy<EmployerFinanceDbContext> _db;
public ExpiredFundsRepository(string connectionString, ILog logger, Lazy<EmployerFinanceDbContext> db) : base(connectionString, logger)
{
_db = db;
}
public async Task Create(long accountId, IEnumerable<ExpiredFund> expiredFunds)
{
var expiredFundsTable = expiredFunds.ToExpiredFundsDataTable();
var parameters = new DynamicParameters();
parameters.Add("@accountId", accountId);
parameters.Add("@expiredFunds", expiredFundsTable.AsTableValuedParameter("[employer_financial].[ExpiredFundsTable]"));
await _db.Value.Database.Connection.ExecuteAsync(
sql: "[employer_financial].[CreateExpiredFunds]",
param: parameters,
transaction: _db.Value.Database.CurrentTransaction.UnderlyingTransaction,
commandType: CommandType.StoredProcedure);
}
public async Task<IEnumerable<ExpiredFund>> Get(long accountId)
{
var parameters = new DynamicParameters();
parameters.Add("@AccountId", accountId);
return await _db.Value.Database.Connection.QueryAsync<ExpiredFund>(
"[employer_financial].[GetFundsIn]",
param: parameters,
transaction: _db.Value.Database.CurrentTransaction.UnderlyingTransaction,
commandType: CommandType.StoredProcedure
);
}
}
}
| mit | C# |
6361141f8efdeb65c19261c5d08cc5140959d64b | Enable nullable: System.Management.Automation.IDispatch (#14185) | daxian-dbw/PowerShell,PaulHigin/PowerShell,TravisEz13/PowerShell,TravisEz13/PowerShell,daxian-dbw/PowerShell,TravisEz13/PowerShell,PaulHigin/PowerShell,JamesWTruher/PowerShell-1,JamesWTruher/PowerShell-1,PaulHigin/PowerShell,TravisEz13/PowerShell,daxian-dbw/PowerShell,PaulHigin/PowerShell,JamesWTruher/PowerShell-1,JamesWTruher/PowerShell-1,daxian-dbw/PowerShell | src/System.Management.Automation/engine/COM/ComDispatch.cs | src/System.Management.Automation/engine/COM/ComDispatch.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Runtime.InteropServices;
using COM = System.Runtime.InteropServices.ComTypes;
#nullable enable
namespace System.Management.Automation
{
/// <summary>
/// The IDispatch interface.
/// </summary>
[Guid("00020400-0000-0000-c000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
internal interface IDispatch
{
[PreserveSig]
int GetTypeInfoCount(out int info);
[PreserveSig]
int GetTypeInfo(int iTInfo, int lcid, out COM.ITypeInfo? ppTInfo);
void GetIDsOfNames(
[MarshalAs(UnmanagedType.LPStruct)] Guid iid,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] rgszNames,
int cNames,
int lcid,
[Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4)] int[] rgDispId);
void Invoke(
int dispIdMember,
[MarshalAs(UnmanagedType.LPStruct)] Guid iid,
int lcid,
COM.INVOKEKIND wFlags,
[In, Out][MarshalAs(UnmanagedType.LPArray)] COM.DISPPARAMS[] paramArray,
out object? pVarResult,
out ComInvoker.EXCEPINFO pExcepInfo,
out uint puArgErr);
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Runtime.InteropServices;
using COM = System.Runtime.InteropServices.ComTypes;
namespace System.Management.Automation
{
/// <summary>
/// The IDispatch interface.
/// </summary>
[Guid("00020400-0000-0000-c000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
internal interface IDispatch
{
[PreserveSig]
int GetTypeInfoCount(out int info);
[PreserveSig]
int GetTypeInfo(int iTInfo, int lcid, out COM.ITypeInfo ppTInfo);
void GetIDsOfNames(
[MarshalAs(UnmanagedType.LPStruct)] Guid iid,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] rgszNames,
int cNames,
int lcid,
[Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4)] int[] rgDispId);
void Invoke(
int dispIdMember,
[MarshalAs(UnmanagedType.LPStruct)] Guid iid,
int lcid,
COM.INVOKEKIND wFlags,
[In, Out][MarshalAs(UnmanagedType.LPArray)] COM.DISPPARAMS[] paramArray,
out object pVarResult,
out ComInvoker.EXCEPINFO pExcepInfo,
out uint puArgErr);
}
}
| mit | C# |
e78395dc8d4e739c8145626819e60a207c7cb841 | Split the CanCombineTwoNs test code into two line. | sdcb/sdmap | sdmap/test/sdmap.test/IntegratedTest/NamespaceTest.cs | sdmap/test/sdmap.test/IntegratedTest/NamespaceTest.cs | using sdmap.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace sdmap.test.IntegratedTest
{
public class NamespaceTest
{
[Fact]
public void CanReferenceOtherInOneNamespace()
{
var code = "namespace ns{sql v1{1#include<v2>} sql v2{2}}";
var rt = new SdmapRuntime();
rt.AddSourceCode(code);
var result = rt.Emit("ns.v1", new { A = true });
Assert.Equal("12", result);
}
[Fact]
public void CanCombineTwoNs()
{
var code =
"namespace ns1{sql sql{1#include<ns2.sql>}} \r\n" +
"namespace ns2{sql sql{2}}";
var rt = new SdmapRuntime();
rt.AddSourceCode(code);
var result = rt.Emit("ns1.sql", null);
Assert.Equal("12", result);
}
}
}
| using sdmap.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace sdmap.test.IntegratedTest
{
public class NamespaceTest
{
[Fact]
public void CanReferenceOtherInOneNamespace()
{
var code = "namespace ns{sql v1{1#include<v2>} sql v2{2}}";
var rt = new SdmapRuntime();
rt.AddSourceCode(code);
var result = rt.Emit("ns.v1", new { A = true });
Assert.Equal("12", result);
}
[Fact]
public void CanCombineTwoNs()
{
var code = "namespace ns1{sql sql{1#include<ns2.sql>}} namespace ns2{sql sql{2}}";
var rt = new SdmapRuntime();
rt.AddSourceCode(code);
var result = rt.Emit("ns1.sql", null);
Assert.Equal("12", result);
}
}
}
| mit | C# |
3ad38824648c2ad5f9b163be6765894cea208be3 | Make EthernetDevice compile again and dispose resources better | shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg | trunk/src/bindings/EthernetDevice.cs | trunk/src/bindings/EthernetDevice.cs |
using System;
using System.Runtime.InteropServices;
namespace TAPCfg {
public class EthernetDevice : IDisposable {
private const int MTU = 1522;
private IntPtr handle;
private bool disposed = false;
public EthernetDevice() {
handle = tapcfg_init();
}
public void Start() {
tapcfg_start(handle);
}
public byte[] Read() {
int length;
byte[] buffer = new byte[MTU];
length = tapcfg_read(handle, buffer, buffer.Length);
byte[] outbuf = new byte[length];
Array.Copy(buffer, 0, outbuf, 0, length);
return outbuf;
}
public void Write(byte[] data) {
byte[] buffer = new byte[MTU];
Array.Copy(data, 0, buffer, 0, data.Length);
int ret = tapcfg_write(handle, buffer, data.Length);
}
public void Enabled(bool enabled) {
if (enabled)
tapcfg_iface_change_status(handle, 1);
else
tapcfg_iface_change_status(handle, 0);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (!disposed) {
if (disposing) {
// Managed resources can be disposed here
}
tapcfg_stop(handle);
tapcfg_destroy(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start();
dev.Enabled(true);
System.Threading.Thread.Sleep(100000);
}
[DllImport("libtapcfg")]
private static extern IntPtr tapcfg_init();
[DllImport("libtapcfg")]
private static extern void tapcfg_destroy(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_start(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern void tapcfg_stop(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_has_data(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_read(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern int tapcfg_write(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern string tapcfg_get_ifname(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_get_status(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_change_status(IntPtr tapcfg, int enabled);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv4(IntPtr tapcfg, string addr, Byte netbits);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv6(IntPtr tapcfg, string addr, Byte netbits);
}
}
|
using System;
using System.Runtime.InteropServices;
namespace TAPCfg {
public class EthernetDevice : IDisposable {
private const int MTU = 1522;
private IntPtr handle;
public EthernetDevice() {
handle = tapcfg_init();
}
public void Start() {
tapcfg_start(handle);
}
public byte[] Read() {
int length;
byte[] buffer = new byte[MTU];
length = tapcfg_read(handle, buffer, buffer.Length);
byte[] outbuf = new byte[length];
Array.Copy(buffer, 0, outbuf, 0, length);
return outbuf;
}
public void Write(byte[] data) {
byte[] buffer = new byte[MTU];
Array.Copy(data, 0, buffer, 0, data.Length);
int ret = tapcfg_write(handle, buffer, data.Length);
}
public void Enabled(bool enabled) {
if (enabled)
tapcfg_iface_change_status(handle, 1);
else
tapcfg_iface_change_status(handle, 0);
}
public void Dispose() {
this.Dispose(true);
}
protected virtual void Dispose(bool fromDisposeMethod) {
tapcfg_stop(handle);
tapcfg_destroy(handle);
if (fromDisposeMethod) {
GC.SuppressFinalize(this);
}
}
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start();
dev.Enabled(true);
System.Threading.Thread.Sleep(100000);
}
[DllImport("libtapcfg")]
private static extern IntPtr tapcfg_init();
[DllImport("libtapcfg")]
private static extern void tapcfg_destroy(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_start(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern void tapcfg_stop(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_has_data(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_read(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern int tapcfg_write(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern string tapcfg_get_ifname(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_get_status(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_change_status(IntPtr tapcfg, int enabled);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv4(IntPtr tapcfg, string addr, Uint8 netbits);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv6(IntPtr tapcfg, string addr, Uint8 netbits);
}
}
| lgpl-2.1 | C# |
8336056636a9311c9336253c80016ab271a67a8e | fix problem with Result.cs properties in linux | ilovepi/Compiler,ilovepi/Compiler | compiler/frontend/Result.cs | compiler/frontend/Result.cs | using System;
namespace compiler
{
public enum Kind
{
Constant,
Variable,
Register,
Conditional
}
public struct Result
{
/// <summary>
/// Const, Variable, Register, Conditional
/// </summary>
public int Kind { get; }
/// <summary>
/// Numeric value
/// </summary>
public int Value { get; }
/// <summary>
/// UUID for an identifier
/// </summary>
public int Id { get; }
/// <summary>
/// Register number
/// </summary>
public int Regno { get; }
/// <summary>
/// Comparison Code ??? maybe I forgot what this was
/// </summary>
public int Cc { get; }
/// <summary>
/// True branch offset
/// </summary>
public int TrueValue { get; }
/// <summary>
/// False branch offset
/// </summary>
public int FalseValue { get; }
}
}
| using System;
namespace compiler
{
public enum Kind
{
Constant,
Variable,
Register,
Conditional
}
public struct Result
{
private int kind; // const, var, register, conditional
private int value; // numeric value
private int id; //id number
private int regno; // register number
private int cc; // conditional code: GT, GTE, LT, LTE, EQ, NEQ,
private int trueValue; // branch offset for true
private int falseValue; // branch offset for false
public int Kind { get => kind; set => kind = value; }
public int Value { get => value; set => this.value = value; }
public int Id { get => id; set => id = value; }
public int Regno { get => regno; set => regno = value; }
public int Cc { get => cc; set => cc = value; }
public int TrueValue { get => trueValue; set => trueValue = value; }
public int FalseValue { get => falseValue; set => falseValue = value; }
}
}
| mit | C# |
b14ab254fe2e60d4f3fc5e81d81210264a7761f6 | fix hpm again | radasuka/ShinraMeter,Seyuna/ShinraMeter,neowutran/TeraDamageMeter,neowutran/ShinraMeter | DamageMeter.UI/SkillDetail/SkillDetailDps.xaml.cs | DamageMeter.UI/SkillDetail/SkillDetailDps.xaml.cs | using System;
using System.Windows;
using System.Windows.Input;
using Lang;
namespace DamageMeter.UI.SkillDetail
{
/// <summary>
/// Logique d'interaction pour SkillContent.xaml
/// </summary>
public partial class SkillDetailDps
{
public SkillDetailDps(Tera.Game.Skill skill, SkillAggregate skillAggregate)
{
InitializeComponent();
Update(skill, skillAggregate);
}
public void Update(Tera.Game.Skill skill, SkillAggregate skillAggregate)
{
var chained = skill.IsChained;
var hit = skill.Detail;
if (skill.IsHotDot) { hit = LP.Dot; }
if (hit != null) { LabelName.Content = hit; }
if (chained == true) { LabelName.Content += " " + LP.Chained; }
LabelName.ToolTip = skill.Id;
LabelCritRateDmg.Content = skillAggregate.CritRate(skill.Id) + "%";
LabelDamagePercentage.Content = skillAggregate.DamagePercent(skill.Id) + "%";
LabelTotalDamage.Content = FormatHelpers.Instance.FormatValue(skillAggregate.Amount(skill.Id));
var hits = skillAggregate.Hits(skill.Id);
LabelNumberHitDmg.Content = hits;
LabelNumberCritDmg.Content = skillAggregate.Crits(skill.Id);
LabelAverageCrit.Content = FormatHelpers.Instance.FormatValue((long) skillAggregate.AvgCrit(skill.Id));
LabelBiggestCrit.Content = FormatHelpers.Instance.FormatValue(skillAggregate.BiggestCrit(skill.Id));
LabelAverageHit.Content = FormatHelpers.Instance.FormatValue((long) skillAggregate.AvgWhite(skill.Id));
LabelAverageTotal.Content = FormatHelpers.Instance.FormatValue((long) skillAggregate.Avg(skill.Id));
LabelNumberHPM.Content = FormatHelpers.Instance.FormatDouble(skillAggregate.Interval == 0 ? 0 : (double)hits / skillAggregate.Interval * TimeSpan.TicksPerMinute);
}
private void DragWindow(object sender, MouseButtonEventArgs e) { ((ClickThrouWindow)Window.GetWindow(this))?.Move(sender, e); }
}
} | using System;
using System.Windows;
using System.Windows.Input;
using Lang;
namespace DamageMeter.UI.SkillDetail
{
/// <summary>
/// Logique d'interaction pour SkillContent.xaml
/// </summary>
public partial class SkillDetailDps
{
public SkillDetailDps(Tera.Game.Skill skill, SkillAggregate skillAggregate)
{
InitializeComponent();
Update(skill, skillAggregate);
}
public void Update(Tera.Game.Skill skill, SkillAggregate skillAggregate)
{
var chained = skill.IsChained;
var hit = skill.Detail;
if (skill.IsHotDot) { hit = LP.Dot; }
if (hit != null) { LabelName.Content = hit; }
if (chained == true) { LabelName.Content += " " + LP.Chained; }
LabelName.ToolTip = skill.Id;
LabelCritRateDmg.Content = skillAggregate.CritRate(skill.Id) + "%";
LabelDamagePercentage.Content = skillAggregate.DamagePercent(skill.Id) + "%";
LabelTotalDamage.Content = FormatHelpers.Instance.FormatValue(skillAggregate.Amount(skill.Id));
var hits = skillAggregate.Hits(skill.Id);
LabelNumberHitDmg.Content = hits;
LabelNumberCritDmg.Content = skillAggregate.Crits(skill.Id);
LabelAverageCrit.Content = FormatHelpers.Instance.FormatValue((long) skillAggregate.AvgCrit(skill.Id));
LabelBiggestCrit.Content = FormatHelpers.Instance.FormatValue(skillAggregate.BiggestCrit(skill.Id));
LabelAverageHit.Content = FormatHelpers.Instance.FormatValue((long) skillAggregate.AvgWhite(skill.Id));
LabelAverageTotal.Content = FormatHelpers.Instance.FormatValue((long) skillAggregate.Avg(skill.Id));
LabelNumberHPM.Content = FormatHelpers.Instance.FormatDouble(skillAggregate.Interval == 0 ? 0 : (double)hits / skillAggregate.Interval / TimeSpan.TicksPerMinute);
}
private void DragWindow(object sender, MouseButtonEventArgs e) { ((ClickThrouWindow)Window.GetWindow(this))?.Move(sender, e); }
}
} | mit | C# |
548b169b6ba226f52d1e8117d934d280e71b6b67 | increment minor version, | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.10.0")]
[assembly: AssemblyInformationalVersion("0.10.0")]
/*
* Version 0.10.0
*
* Publishes a new nuget package called 'Experiment.Idioms', which facilitates
* running idiomatic, regular unit-tests.
*
* This release includes the first idiomatic-test as
* `GuardClauseAssertionTestCases`. This assertion verifies guard-clause
* assertions for all public API.
*
* [FirstClassTheorem]
* public IEnumerable<ITestCase> Demo()
* {
* return new GuardClauseAssertionTestCases(typeof(Foo));
* }
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.9.8")]
[assembly: AssemblyInformationalVersion("0.9.8")]
/*
* Version 0.9.8
*
* Uses single quotation mark to show the display name of `FirstClassCommand`,
* because double quotation mark can mislead that a value is string, but
* actually not.
*/ | mit | C# |
e5104c2fea9b11e7a6f23cf4ffe08f754d10be0c | Remove duplicate UIComponentDefinitionAttribute.Properties property; Remove duplicate IPropertySettings interface from UIComponentDefinitionAttribute | atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata | src/Atata/Attributes/UIComponentDefinitionAttribute.cs | src/Atata/Attributes/UIComponentDefinitionAttribute.cs | using System.Linq;
namespace Atata
{
public abstract class UIComponentDefinitionAttribute : ScopeDefinitionAttribute
{
protected UIComponentDefinitionAttribute(string scopeXPath = DefaultScopeXPath)
: base(scopeXPath)
{
}
public string ComponentTypeName { get; set; }
public string IgnoreNameEndings { get; set; }
public string[] GetIgnoreNameEndingValues()
{
return IgnoreNameEndings != null ? IgnoreNameEndings.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToArray() : new string[0];
}
public string NormalizeNameIgnoringEnding(string name)
{
string endingToIgnore = GetIgnoreNameEndingValues().
FirstOrDefault(x => name.EndsWith(x) && name.Length > x.Length);
return endingToIgnore != null
? name.Substring(0, name.Length - endingToIgnore.Length).TrimEnd()
: name;
}
}
}
| using System.Linq;
namespace Atata
{
public abstract class UIComponentDefinitionAttribute : ScopeDefinitionAttribute, IPropertySettings
{
protected UIComponentDefinitionAttribute(string scopeXPath = DefaultScopeXPath)
: base(scopeXPath)
{
}
public PropertyBag Properties { get; } = new PropertyBag();
public string ComponentTypeName { get; set; }
public string IgnoreNameEndings { get; set; }
public string[] GetIgnoreNameEndingValues()
{
return IgnoreNameEndings != null ? IgnoreNameEndings.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToArray() : new string[0];
}
public string NormalizeNameIgnoringEnding(string name)
{
string endingToIgnore = GetIgnoreNameEndingValues().
FirstOrDefault(x => name.EndsWith(x) && name.Length > x.Length);
return endingToIgnore != null
? name.Substring(0, name.Length - endingToIgnore.Length).TrimEnd()
: name;
}
}
}
| apache-2.0 | C# |
61230348c5704bca7184ae73ae7e3531a2163317 | Write to console on failed apu write | izik1/JAGBE | JAGBE/GB/Computation/Apu.cs | JAGBE/GB/Computation/Apu.cs | using System;
namespace JAGBE.GB.Computation
{
internal sealed class Apu
{
private byte NR50;
private byte NR51;
private byte NR52;
internal void Clear()
{
this.NR50 = 0;
this.NR51 = 0;
}
internal byte GetRegister(byte num)
{
switch (num)
{
case 0x24:
return this.NR50;
case 0x25:
return this.NR51;
case 0x26:
return (byte)(this.NR52 | 0x70);
default:
Console.WriteLine("Possible bad Read from ALU 0x" + num.ToString("X2") + " (reg number)");
return 0xFF;
}
}
internal bool SetRegister(byte num, byte value)
{
switch (num)
{
case 0x24:
this.NR50 = value;
return true;
case 0x25:
this.NR51 = value;
return true;
case 0x26:
this.NR52 = (byte)((value & 0x80) | (this.NR52 & 0x7F));
if (!this.NR52.GetBit(7))
{
Clear();
}
return true;
default:
return false;
}
}
}
}
| namespace JAGBE.GB.Computation
{
internal sealed class Apu
{
private byte NR50;
private byte NR51;
private byte NR52;
internal void Clear()
{
this.NR50 = 0;
this.NR51 = 0;
}
internal byte GetRegister(byte num)
{
switch (num)
{
case 0x24:
return this.NR50;
case 0x25:
return this.NR51;
case 0x26:
return (byte)(this.NR52 | 0x70);
default:
return 0xFF;
}
}
internal bool SetRegister(byte num, byte value)
{
switch (num)
{
case 0x24:
this.NR50 = value;
return true;
case 0x25:
this.NR51 = value;
return true;
case 0x26:
this.NR52 = (byte)((value & 0x80) | (this.NR52 & 0x7F));
if (!this.NR52.GetBit(7))
{
Clear();
}
return true;
default:
return false;
}
}
}
}
| mit | C# |
23a9948a781a7c500dc9773e188f3afead264a18 | Adjust AssemblyInfo | Makar8000/ACT-Discord-Triggers | ACT_DiscordTriggers/ACT_DiscordTriggers/Properties/AssemblyInfo.cs | ACT_DiscordTriggers/ACT_DiscordTriggers/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("ACT_DiscordTriggers")]
[assembly: AssemblyDescription("An ACT Plugin for sending triggers through Discord.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ACT_DiscordTriggers")]
[assembly: AssemblyCopyright("Copyright © 2017 Makar")]
[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("2809ee1e-e77d-4bc2-b656-08a82b86cd9a")]
// 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("ACT_DiscordTriggers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ACT_DiscordTriggers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("2809ee1e-e77d-4bc2-b656-08a82b86cd9a")]
// 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# |
9e12df615006e94837d25aca83daa8635cdd44eb | Fix lock of scrapes list | dipeshc/BTDeploy | src/MonoTorrent/MonoTorrent.Tracker/RequestMonitor.cs | src/MonoTorrent/MonoTorrent.Tracker/RequestMonitor.cs | using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Client;
using MonoTorrent.Common;
namespace MonoTorrent.Tracker
{
public class RequestMonitor
{
#region Member Variables
private SpeedMonitor announces;
private SpeedMonitor scrapes;
#endregion Member Variables
#region Properties
public int AnnounceRate
{
get { return announces.Rate; }
}
public int ScrapeRate
{
get { return scrapes.Rate; }
}
public int TotalAnnounces
{
get { return (int)announces.Total; }
}
public int TotalScrapes
{
get { return (int)scrapes.Total; }
}
#endregion Properties
#region Constructors
public RequestMonitor()
{
announces = new SpeedMonitor();
scrapes = new SpeedMonitor();
}
#endregion Constructors
#region Methods
internal void AnnounceReceived()
{
lock (announces)
announces.AddDelta(1);
}
internal void ScrapeReceived()
{
lock (scrapes)
scrapes.AddDelta(1);
}
#endregion Methods
internal void Tick()
{
lock (announces)
this.announces.Tick();
lock (scrapes)
this.scrapes.Tick();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Client;
using MonoTorrent.Common;
namespace MonoTorrent.Tracker
{
public class RequestMonitor
{
#region Member Variables
private SpeedMonitor announces;
private SpeedMonitor scrapes;
#endregion Member Variables
#region Properties
public int AnnounceRate
{
get { return announces.Rate; }
}
public int ScrapeRate
{
get { return scrapes.Rate; }
}
public int TotalAnnounces
{
get { return (int)announces.Total; }
}
public int TotalScrapes
{
get { return (int)scrapes.Total; }
}
#endregion Properties
#region Constructors
public RequestMonitor()
{
announces = new SpeedMonitor();
scrapes = new SpeedMonitor();
}
#endregion Constructors
#region Methods
internal void AnnounceReceived()
{
lock (announces)
announces.AddDelta(1);
}
internal void ScrapeReceived()
{
lock (announces)
scrapes.AddDelta(1);
}
#endregion Methods
internal void Tick()
{
lock (announces)
this.announces.Tick();
lock (scrapes)
this.scrapes.Tick();
}
}
}
| mit | C# |
cc32835f640f3a3ddd2a7963ea810bbd6179c6c4 | Add Radius() to circle geo shape filter descriptor | ststeiger/elasticsearch-net,tkirill/elasticsearch-net,tkirill/elasticsearch-net,wawrzyn/elasticsearch-net,adam-mccoy/elasticsearch-net,KodrAus/elasticsearch-net,gayancc/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,robertlyson/elasticsearch-net,wawrzyn/elasticsearch-net,robertlyson/elasticsearch-net,UdiBen/elasticsearch-net,TheFireCookie/elasticsearch-net,SeanKilleen/elasticsearch-net,DavidSSL/elasticsearch-net,jonyadamit/elasticsearch-net,adam-mccoy/elasticsearch-net,KodrAus/elasticsearch-net,faisal00813/elasticsearch-net,wawrzyn/elasticsearch-net,Grastveit/NEST,DavidSSL/elasticsearch-net,jonyadamit/elasticsearch-net,jonyadamit/elasticsearch-net,abibell/elasticsearch-net,robertlyson/elasticsearch-net,starckgates/elasticsearch-net,amyzheng424/elasticsearch-net,elastic/elasticsearch-net,DavidSSL/elasticsearch-net,SeanKilleen/elasticsearch-net,joehmchan/elasticsearch-net,ststeiger/elasticsearch-net,junlapong/elasticsearch-net,amyzheng424/elasticsearch-net,amyzheng424/elasticsearch-net,cstlaurent/elasticsearch-net,junlapong/elasticsearch-net,azubanov/elasticsearch-net,elastic/elasticsearch-net,RossLieberman/NEST,RossLieberman/NEST,abibell/elasticsearch-net,mac2000/elasticsearch-net,cstlaurent/elasticsearch-net,LeoYao/elasticsearch-net,LeoYao/elasticsearch-net,faisal00813/elasticsearch-net,geofeedia/elasticsearch-net,geofeedia/elasticsearch-net,adam-mccoy/elasticsearch-net,LeoYao/elasticsearch-net,UdiBen/elasticsearch-net,abibell/elasticsearch-net,robrich/elasticsearch-net,UdiBen/elasticsearch-net,geofeedia/elasticsearch-net,ststeiger/elasticsearch-net,starckgates/elasticsearch-net,tkirill/elasticsearch-net,robrich/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,joehmchan/elasticsearch-net,mac2000/elasticsearch-net,robrich/elasticsearch-net,joehmchan/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,gayancc/elasticsearch-net,gayancc/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,starckgates/elasticsearch-net,junlapong/elasticsearch-net,Grastveit/NEST,CSGOpenSource/elasticsearch-net,Grastveit/NEST,cstlaurent/elasticsearch-net,mac2000/elasticsearch-net,faisal00813/elasticsearch-net,SeanKilleen/elasticsearch-net | src/Nest/DSL/Filter/GeoShapeCircleFilterDescriptor.cs | src/Nest/DSL/Filter/GeoShapeCircleFilterDescriptor.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nest.Resolvers;
using Nest.Resolvers.Converters;
using Nest.Resolvers.Converters.Filters;
using Newtonsoft.Json;
using Elasticsearch.Net;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public interface IGeoShapeCircleFilter : IGeoShapeBaseFilter
{
[JsonProperty("shape")]
ICircleGeoShape Shape { get; set; }
}
public class GeoShapeCircleFilter : PlainFilter, IGeoShapeCircleFilter
{
protected internal override void WrapInContainer(IFilterContainer container)
{
container.GeoShape = this;
}
public PropertyPathMarker Field { get; set; }
public ICircleGeoShape Shape { get; set; }
}
public class GeoShapeCircleFilterDescriptor : FilterBase, IGeoShapeCircleFilter
{
IGeoShapeCircleFilter Self { get { return this; } }
bool IFilter.IsConditionless
{
get
{
return this.Self.Shape == null || !this.Self.Shape.Coordinates.HasAny();
}
}
PropertyPathMarker IFieldNameFilter.Field { get; set; }
ICircleGeoShape IGeoShapeCircleFilter.Shape { get; set; }
public GeoShapeCircleFilterDescriptor Coordinates(IEnumerable<double> coordinates)
{
if (this.Self.Shape == null)
this.Self.Shape = new CircleGeoShape();
this.Self.Shape.Coordinates = coordinates;
return this;
}
public GeoShapeCircleFilterDescriptor Radius(string radius)
{
if (this.Self.Shape == null)
this.Self.Shape = new CircleGeoShape();
this.Self.Shape.Radius = radius;
return this;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nest.Resolvers;
using Nest.Resolvers.Converters;
using Nest.Resolvers.Converters.Filters;
using Newtonsoft.Json;
using Elasticsearch.Net;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public interface IGeoShapeCircleFilter : IGeoShapeBaseFilter
{
[JsonProperty("shape")]
ICircleGeoShape Shape { get; set; }
}
public class GeoShapeCircleFilter : PlainFilter, IGeoShapeCircleFilter
{
protected internal override void WrapInContainer(IFilterContainer container)
{
container.GeoShape = this;
}
public PropertyPathMarker Field { get; set; }
public ICircleGeoShape Shape { get; set; }
}
public class GeoShapeCircleFilterDescriptor : FilterBase, IGeoShapeCircleFilter
{
IGeoShapeCircleFilter Self { get { return this; } }
bool IFilter.IsConditionless
{
get
{
return this.Self.Shape == null || !this.Self.Shape.Coordinates.HasAny();
}
}
PropertyPathMarker IFieldNameFilter.Field { get; set; }
ICircleGeoShape IGeoShapeCircleFilter.Shape { get; set; }
public GeoShapeCircleFilterDescriptor Coordinates(IEnumerable<double> coordinates)
{
if (this.Self.Shape == null)
this.Self.Shape = new CircleGeoShape();
this.Self.Shape.Coordinates = coordinates;
return this;
}
}
}
| apache-2.0 | C# |
90093052964338991566beb936a7e52b82201fe5 | Change visibility of members of ExportInfo; expose DefaultPriority. | bfriesen/Rock.StaticDependencyInjection,RockFramework/Rock.StaticDependencyInjection | src/StaticDependencyInjection/ExportInfo.Generated.cs | src/StaticDependencyInjection/ExportInfo.Generated.cs | using System;
namespace Rock.StaticDependencyInjection
{
/// <summary>
/// Provides information about an export.
/// </summary>
internal class ExportInfo
{
/// <summary>
/// The default priority for an instance of <see cref="ExportInfo"/> if not specified.
/// </summary>
public const int DefaultPriority = -1;
private readonly Type _targetClass;
private readonly int _priority;
/// <summary>
/// Initializes a new instance of the <see cref="ExportInfo"/> class with
/// a priority with the value of <see cref="DefaultPriority"/>.
/// </summary>
/// <param name="targetClass">The class to be exported.</param>
public ExportInfo(Type targetClass)
: this(targetClass, DefaultPriority)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExportInfo"/> class.
/// </summary>
/// <param name="targetClass">The class to be exported.</param>
/// <param name="priority">
/// The priority of the export, relative to the priority of other exports.
/// </param>
public ExportInfo(Type targetClass, int priority)
{
if (targetClass == null)
{
throw new ArgumentNullException("targetClass");
}
if (targetClass.Assembly.ReflectionOnly)
{
targetClass = Type.GetType(targetClass.AssemblyQualifiedName);
}
_targetClass = targetClass;
_priority = priority;
}
/// <summary>
/// Gets the class to be exported.
/// </summary>
public Type TargetClass { get { return _targetClass; } }
/// <summary>
/// Gets the priority of the export, relative to the priority of other exports.
/// The default value, if not specified in the constructor is negative one.
/// This value is used during import operations to sort the discovered classes.
/// </summary>
public int Priority { get { return _priority; } }
/// <summary>
/// Gets or sets the name of the export. This value is compared against the
/// name parameter in various import operations.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the type indicated by
/// <see cref="TargetClass"/> should be excluded from consideration during an
/// import operation.
/// </summary>
public bool Disabled { get; set; }
}
} | using System;
namespace Rock.StaticDependencyInjection
{
/// <summary>
/// Provides information about an export.
/// </summary>
internal class ExportInfo
{
private const int _defaultPriority = -1;
private readonly Type _targetClass;
private readonly int _priority;
/// <summary>
/// Initializes a new instance of the <see cref="ExportInfo"/> class with
/// a priority of negative one.
/// </summary>
/// <param name="targetClass">The class to be exported.</param>
internal ExportInfo(Type targetClass)
: this(targetClass, _defaultPriority)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExportInfo"/> class.
/// </summary>
/// <param name="targetClass">The class to be exported.</param>
/// <param name="priority">
/// The priority of the export, relative to the priority of other exports.
/// </param>
internal ExportInfo(Type targetClass, int priority)
{
if (targetClass == null)
{
throw new ArgumentNullException("targetClass");
}
if (targetClass.Assembly.ReflectionOnly)
{
targetClass = Type.GetType(targetClass.AssemblyQualifiedName);
}
_targetClass = targetClass;
_priority = priority;
}
/// <summary>
/// Gets the class to be exported.
/// </summary>
internal Type TargetClass { get { return _targetClass; } }
/// <summary>
/// Gets the priority of the export, relative to the priority of other exports.
/// The default value, if not specified in the constructor is negative one.
/// This value is used during import operations to sort the discovered classes.
/// </summary>
internal int Priority { get { return _priority; } }
/// <summary>
/// Gets or sets the name of the export. This value is compared against the
/// name parameter in various import operations.
/// </summary>
internal string Name { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the type indicated by
/// <see cref="TargetClass"/> should be excluded from consideration during an
/// import operation.
/// </summary>
internal bool Disabled { get; set; }
}
} | mit | C# |
dede5e7050fc29f613e5da584b40a55df59645d5 | allow test of eidas signitures | crocs-muni/roca,crocs-muni/roca,crocs-muni/roca,crocs-muni/roca | csharp/RocaTest/Program.cs | csharp/RocaTest/Program.cs | using System;
using System.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.X509;
using iTextSharp.text.pdf;
using System.Collections.Generic;
using System.Security.Cryptography.Pkcs;
namespace RocaTest
{
class Program
{
static void Main(string[] args)
{
foreach (string certFile in Directory.GetFiles("data")) {
if (certFile.EndsWith(".pdf")) {
TestPDF(certFile);
} else {
if (certFile.EndsWith(".pem")) {
Console.WriteLine(certFile + " - contains RSA public key vulnerable to ROCA (CVE-2017-15361)");
} else {
Console.WriteLine(certFile + " - Certificate does not contain RSA public key vulnerable to ROCA (CVE-2017-15361)");
}
}
Console.ReadLine();
}
}
static void TestPDF(string path)
{
Console.WriteLine("processing PDF");
AcroFields acroFields = new PdfReader(path).AcroFields;
List<string> names = acroFields.GetSignatureNames();
foreach (var name in names) {
try {
Console.WriteLine(name);
PdfDictionary dict = acroFields.GetSignatureDictionary(name);
PdfString contents = (PdfString)PdfReader.GetPdfObject(dict.Get(PdfName.CONTENTS));
byte[] PKCS7 = contents.GetOriginalBytes();
var signedData = new SignedCms();
signedData.Decode(PKCS7);
Console.WriteLine(signedData.Certificates.Count);
int i = 0;
foreach (var certificate in signedData.Certificates) {
i++;
X509CertificateParser x509CertificateParser = new X509CertificateParser();
X509Certificate x509Certificate = x509CertificateParser.ReadCertificate(certificate.GetRawCertData());
RsaKeyParameters rsaKeyParameters = x509Certificate.GetPublicKey() as RsaKeyParameters;
if (RocaTest.IsVulnerable(rsaKeyParameters)) {
Console.WriteLine("Cetificate #" + i + " is vulnerable. Cert Hash: " + certificate.GetCertHashString());
} else {
Console.WriteLine("Cetificate #" + i + " is NOT vulnerable");
}
}
} catch (Exception exc) {
Console.WriteLine(exc.Message);
}
}
}
static bool TestCert(string certFile)
{
X509CertificateParser x509CertificateParser = new X509CertificateParser();
X509Certificate x509Certificate = x509CertificateParser.ReadCertificate(File.ReadAllBytes(certFile));
RsaKeyParameters rsaKeyParameters = x509Certificate.GetPublicKey() as RsaKeyParameters;
return RocaTest.IsVulnerable(rsaKeyParameters);
}
}
}
| using System;
using System.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.X509;
namespace RocaTest
{
class Program
{
static void Main(string[] args)
{
foreach (string certFile in Directory.GetFiles("data"))
{
if (TestCert(certFile))
Console.WriteLine(certFile + " - contains RSA public key vulnerable to ROCA (CVE-2017-15361)");
else
Console.WriteLine(certFile + " - Certificate does not contain RSA public key vulnerable to ROCA (CVE-2017-15361)");
}
}
static bool TestCert(string certFile)
{
X509CertificateParser x509CertificateParser = new X509CertificateParser();
X509Certificate x509Certificate = x509CertificateParser.ReadCertificate(File.ReadAllBytes(certFile));
RsaKeyParameters rsaKeyParameters = x509Certificate.GetPublicKey() as RsaKeyParameters;
return RocaTest.IsVulnerable(rsaKeyParameters);
}
}
}
| mit | C# |
8e5c781667fc5d76bf5f24937249ff3abc2b15b4 | make class public | IUMDPI/IUMediaHelperApps | Packager/Exceptions/NormalizeOriginalException.cs | Packager/Exceptions/NormalizeOriginalException.cs | using System;
namespace Packager.Exceptions
{
public class NormalizeOriginalException : AbstractEngineException
{
public NormalizeOriginalException(string baseMessage, params object[] parameters) : base(baseMessage, parameters)
{
}
public NormalizeOriginalException(Exception innerException, string baseMessage, params object[] parameters) : base(innerException, baseMessage, parameters)
{
}
}
} | using System;
namespace Packager.Exceptions
{
internal class NormalizeOriginalException : AbstractEngineException
{
public NormalizeOriginalException(string baseMessage, params object[] parameters) : base(baseMessage, parameters)
{
}
public NormalizeOriginalException(Exception innerException, string baseMessage, params object[] parameters) : base(innerException, baseMessage, parameters)
{
}
}
} | apache-2.0 | C# |
861a43f7b3246f8aa397fb789fdcb4c41a1a98b0 | Add GetHashCode() to RuntimeHelpers | dot42/api | System/Runtime/CompilerServices/RuntimeHelpers.cs | System/Runtime/CompilerServices/RuntimeHelpers.cs | // Copyright (C) 2014 dot42
//
// Original filename: RuntimeHelpers.cs
//
// 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 Dot42;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Various compiler services not intended to be used directly.
/// </summary>
public static class RuntimeHelpers
{
/// <summary>
/// Initialize the given array from data stored in the assembly.
/// </summary>
[DexNative]
public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
public static int GetHashCode(Object o)
{
return Java.Lang.System.IdentityHashCode(o);
}
}
}
| // Copyright (C) 2014 dot42
//
// Original filename: RuntimeHelpers.cs
//
// 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 Dot42;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Various compiler services not intended to be used directly.
/// </summary>
public static class RuntimeHelpers
{
/// <summary>
/// Initialize the given array from data stored in the assembly.
/// </summary>
[DexNative]
public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
}
}
| apache-2.0 | C# |
9a92bc05dbccaaf1974f7f07d576c177f10d8760 | fix json types | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs | BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs | using System;
using System.Collections.Generic;
using BTCPayServer.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BTCPayServer.Client.Models
{
public class InvoicePaymentMethodDataModel
{
public string Destination { get; set; }
public string PaymentLink { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public decimal Rate { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal PaymentMethodPaid { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal TotalPaid { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal Due { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal Amount { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal NetworkFee { get; set; }
public List<Payment> Payments { get; set; }
public string PaymentMethod { get; set; }
public class Payment
{
public string Id { get; set; }
[JsonConverter(typeof(NBitcoin.JsonConverters.DateTimeToUnixTimeConverter))]
public DateTime ReceivedDate { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal Value { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal Fee { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public PaymentStatus Status { get; set; }
public string Destination { get; set; }
public enum PaymentStatus
{
Invalid,
AwaitingConfirmation,
AwaitingCompletion,
Complete
}
}
}
}
| using System;
using System.Collections.Generic;
using BTCPayServer.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BTCPayServer.Client.Models
{
public class InvoicePaymentMethodDataModel
{
public string Destination { get; set; }
public string PaymentLink { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal Rate { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal PaymentMethodPaid { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal TotalPaid { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal Due { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal Amount { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal NetworkFee { get; set; }
public List<Payment> Payments { get; set; }
public string PaymentMethod { get; set; }
public class Payment
{
public string Id { get; set; }
[JsonConverter(typeof(NBitcoin.JsonConverters.DateTimeToUnixTimeConverter))]
public DateTime ReceivedDate { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal Value { get; set; }
[JsonProperty(ItemConverterType = typeof(NumericStringJsonConverter))]
public decimal Fee { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public PaymentStatus Status { get; set; }
public string Destination { get; set; }
public enum PaymentStatus
{
Invalid,
AwaitingConfirmation,
AwaitingCompletion,
Complete
}
}
}
}
| mit | C# |
a17928ee735eccdceea77e21b9da43bafded03ef | Update ChangePassword form markup | peterblazejewicz/aspnet-5-bootstrap-4,peterblazejewicz/aspnet-5-bootstrap-4 | WebApplication/Views/Manage/ChangePassword.cshtml | WebApplication/Views/Manage/ChangePassword.cshtml | @model ChangePasswordViewModel
@{
ViewData["Title"] = "Change Password";
}
<h2>@ViewData["Title"].</h2>
<form asp-controller="Manage" asp-action="ChangePassword" method="post" role="form">
<h4>Change Password Form</h4>
<hr />
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
<fieldset>
<div class="form-group row">
<label asp-for="OldPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="OldPassword" class="form-control" />
<span asp-validation-for="OldPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="NewPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="NewPassword" class="form-control" />
<span asp-validation-for="NewPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="ConfirmPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary">Change password</button>
</div>
</div>
</fieldset>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
| @model ChangePasswordViewModel
@{
ViewData["Title"] = "Change Password";
}
<h2>@ViewData["Title"].</h2>
<form asp-controller="Manage" asp-action="ChangePassword" method="post" role="form">
<h4>Change Password Form</h4>
<hr />
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
<div class="form-group">
<label asp-for="OldPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="OldPassword" class="form-control" />
<span asp-validation-for="OldPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="NewPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="NewPassword" class="form-control" />
<span asp-validation-for="NewPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="ConfirmPassword" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Change password</button>
</div>
</div>
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
| mit | C# |
c2dc35359f3aa4475ddf0ba95d7297e1fd082c80 | Enable `MaximizeBox` for `PatchingWizard` | kc284/xenadmin,kc284/xenadmin,xenserver/xenadmin,xenserver/xenadmin,kc284/xenadmin,kc284/xenadmin,kc284/xenadmin,xenserver/xenadmin | XenAdmin/Wizards/PatchingWizard/PatchingWizard.Designer.cs | XenAdmin/Wizards/PatchingWizard/PatchingWizard.Designer.cs | using System.Windows.Forms;
namespace XenAdmin.Wizards.PatchingWizard
{
partial class PatchingWizard
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PatchingWizard));
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWizard)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.XSHelpButton)).BeginInit();
this.SuspendLayout();
//
// pictureBoxWizard
//
resources.ApplyResources(this.pictureBoxWizard, "pictureBoxWizard");
this.pictureBoxWizard.Image = global::XenAdmin.Properties.Resources._000_Patch_h32bit_32;
//
// XSHelpButton
//
resources.ApplyResources(this.XSHelpButton, "XSHelpButton");
//
// PatchingWizard
//
resources.ApplyResources(this, "$this");
this.Name = "PatchingWizard";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWizard)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.XSHelpButton)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
this.MaximizeBox = true;
}
#endregion
}
} | using System.Windows.Forms;
namespace XenAdmin.Wizards.PatchingWizard
{
partial class PatchingWizard
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PatchingWizard));
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWizard)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.XSHelpButton)).BeginInit();
this.SuspendLayout();
//
// pictureBoxWizard
//
resources.ApplyResources(this.pictureBoxWizard, "pictureBoxWizard");
this.pictureBoxWizard.Image = global::XenAdmin.Properties.Resources._000_Patch_h32bit_32;
//
// XSHelpButton
//
resources.ApplyResources(this.XSHelpButton, "XSHelpButton");
//
// PatchingWizard
//
resources.ApplyResources(this, "$this");
this.Name = "PatchingWizard";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWizard)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.XSHelpButton)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
} | bsd-2-clause | C# |
211c8192c0704477396943b1f86c4652ae88071b | Fix sample | StanleyGoldman/NRules,NRules/NRules,StanleyGoldman/NRules,prashanthr/NRules | samples/SimpleRulesTest/SimpleRulesTest/Program.cs | samples/SimpleRulesTest/SimpleRulesTest/Program.cs | using NRules;
using NRules.Fluent;
namespace SimpleRulesTest
{
internal class Program
{
private static void Main(string[] args)
{
var dwelling = new Dwelling {Address = "1 Main Street, New York, NY", Type = DwellingTypes.SingleHouse};
var dwelling2 = new Dwelling {Address = "2 Main Street, New York, NY", Type = DwellingTypes.SingleHouse};
var policy1 = new Policy {Name = "Silver", PolicyType = PolicyTypes.Home, Price = 1200, Dwelling = dwelling};
var policy2 = new Policy {Name = "Gold", PolicyType = PolicyTypes.Home, Price = 2300, Dwelling = dwelling2};
var customer1 = new Customer {Name = "John Do", Age = 22, Sex = SexTypes.Male, Policy = policy1};
var customer2 = new Customer {Name = "Emily Brown", Age = 32, Sex = SexTypes.Female, Policy = policy2};
var repository = new RuleRepository();
repository.Load(x => x.From(typeof (Program).Assembly));
var ruleSets = repository.GetRuleSets();
var compiler = new RuleCompiler();
ISessionFactory factory = compiler.Compile(ruleSets);
ISession session = factory.CreateSession();
session.Insert(policy1);
session.Insert(policy2);
session.Insert(customer1);
session.Insert(customer2);
session.Insert(dwelling);
session.Insert(dwelling2);
customer1.Age = 10;
session.Update(customer1);
session.Retract(customer2);
session.Fire();
session.Insert(customer2);
session.Fire();
customer1.Age = 30;
session.Update(customer1);
session.Fire();
}
}
} | using NRules;
using NRules.Fluent;
namespace SimpleRulesTest
{
internal class Program
{
private static void Main(string[] args)
{
var dwelling = new Dwelling {Address = "1 Main Street, New York, NY", Type = DwellingTypes.SingleHouse};
var dwelling2 = new Dwelling {Address = "2 Main Street, New York, NY", Type = DwellingTypes.SingleHouse};
var policy1 = new Policy {Name = "Silver", PolicyType = PolicyTypes.Home, Price = 1200, Dwelling = dwelling};
var policy2 = new Policy {Name = "Gold", PolicyType = PolicyTypes.Home, Price = 2300, Dwelling = dwelling2};
var customer1 = new Customer {Name = "John Do", Age = 22, Sex = SexTypes.Male, Policy = policy1};
var customer2 = new Customer {Name = "Emily Brown", Age = 32, Sex = SexTypes.Female, Policy = policy2};
var repository = new RuleRepository();
repository.Load(x => x.From(typeof (Program).Assembly));
var ruleSets = repository.GetRuleSets();
IRuleCompiler compiler = new RuleCompiler();
ISessionFactory factory = compiler.Compile(ruleSets);
ISession session = factory.CreateSession();
session.Insert(policy1);
session.Insert(policy2);
session.Insert(customer1);
session.Insert(customer2);
session.Insert(dwelling);
session.Insert(dwelling2);
customer1.Age = 10;
session.Update(customer1);
session.Retract(customer2);
session.Fire();
session.Insert(customer2);
session.Fire();
customer1.Age = 30;
session.Update(customer1);
session.Fire();
}
}
} | mit | C# |
16fbb8fa0dac761b3e5a7fef0e8a74e615d6c10c | Fix setting control size when it is visible | PowerOfCode/Eto,l8s/Eto,l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1 | Source/Eto.Platform.Gtk/Forms/GtkContainer.cs | Source/Eto.Platform.Gtk/Forms/GtkContainer.cs | using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Platform.GtkSharp
{
public interface IGtkContainer
{
void SetLayout(Layout inner);
object ContainerObject { get; }
}
public abstract class GtkContainer<T, W> : GtkControl<T, W>, IContainer, IGtkContainer
where T: Gtk.Widget
where W: Container
{
public abstract object ContainerObject { get; }
public virtual Size ClientSize {
get { return this.Size; }
set {
this.Size = value;
}
}
public virtual Gtk.Container MainContainerControl
{
get { return (Gtk.Container)base.ContainerControl; }
}
public sealed override Gtk.Widget ContainerControl
{
get { return MainContainerControl; }
}
public override void OnLoad (EventArgs e)
{
base.OnLoad (e);
ContainerControl.SizeRequested += delegate(object o, Gtk.SizeRequestedArgs args) {
if (MinimumSize != null) {
var alloc = args.Requisition;
if (MinimumSize.Value.Width > 0) alloc.Width = Math.Max (alloc.Width, MinimumSize.Value.Width);
if (MinimumSize.Value.Height > 0) alloc.Height = Math.Max (alloc.Height, MinimumSize.Value.Height);
args.Requisition = alloc;
}
};
/*
Control.SizeAllocated += delegate(object o, Gtk.SizeAllocatedArgs args) {
if (MinimumSize != null) {
var alloc = args.Allocation;
if (MinimumSize.Value.Width > 0) alloc.Width = Math.Max (alloc.Width, MinimumSize.Value.Width);
if (MinimumSize.Value.Height > 0) alloc.Height = Math.Max (alloc.Height, MinimumSize.Value.Height);
if (alloc.Width != args.Allocation.Width || alloc.Height != args.Allocation.Height) {
Control.SetSizeRequest(alloc.Width, alloc.Height);
Control.Allocation = alloc; //.SetSizeRequest(alloc.Width, alloc.Height);
}
}
};*/
}
public override Size Size {
get {
if (ContainerControl.Visible)
return ContainerControl.Allocation.Size.ToEto ();
else
return ContainerControl.SizeRequest ().ToEto ();
}
set {
ContainerControl.SetSizeRequest (value.Width, value.Height);
}
}
public Size? MinimumSize {
get; set;
}
}
}
| using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Platform.GtkSharp
{
public interface IGtkContainer
{
void SetLayout(Layout inner);
object ContainerObject { get; }
}
public abstract class GtkContainer<T, W> : GtkControl<T, W>, IContainer, IGtkContainer
where T: Gtk.Widget
where W: Container
{
public abstract object ContainerObject { get; }
public virtual Size ClientSize {
get { return this.Size; }
set {
this.Size = value;
}
}
public virtual Gtk.Container MainContainerControl
{
get { return (Gtk.Container)base.ContainerControl; }
}
public sealed override Gtk.Widget ContainerControl
{
get { return MainContainerControl; }
}
public override void OnLoad (EventArgs e)
{
base.OnLoad (e);
ContainerControl.SizeRequested += delegate(object o, Gtk.SizeRequestedArgs args) {
if (MinimumSize != null) {
var alloc = args.Requisition;
if (MinimumSize.Value.Width > 0) alloc.Width = Math.Max (alloc.Width, MinimumSize.Value.Width);
if (MinimumSize.Value.Height > 0) alloc.Height = Math.Max (alloc.Height, MinimumSize.Value.Height);
args.Requisition = alloc;
}
};
/*
Control.SizeAllocated += delegate(object o, Gtk.SizeAllocatedArgs args) {
if (MinimumSize != null) {
var alloc = args.Allocation;
if (MinimumSize.Value.Width > 0) alloc.Width = Math.Max (alloc.Width, MinimumSize.Value.Width);
if (MinimumSize.Value.Height > 0) alloc.Height = Math.Max (alloc.Height, MinimumSize.Value.Height);
if (alloc.Width != args.Allocation.Width || alloc.Height != args.Allocation.Height) {
Control.SetSizeRequest(alloc.Width, alloc.Height);
Control.Allocation = alloc; //.SetSizeRequest(alloc.Width, alloc.Height);
}
}
};*/
}
public override Size Size {
get {
if (ContainerControl.Visible)
return ContainerControl.Allocation.Size.ToEto ();
else
return ContainerControl.SizeRequest ().ToEto ();
}
set {
if (ContainerControl.Visible)
ContainerControl.Allocation = new Gdk.Rectangle(Control.Allocation.Location, value.ToGdk ());
else
ContainerControl.SetSizeRequest (value.Width, value.Height);
}
}
public Size? MinimumSize {
get; set;
}
}
}
| bsd-3-clause | C# |
9f6a220099dc45c41812bc1b8e4a3cb1330ec679 | Fix broken (admittedly crappy) test. | TicketSolutionsPtyLtd/TeamCityBuildChanges,BenPhegan/TeamCityBuildChanges | TeamCityBuildChanges.Tests/HtmlOutputTests.cs | TeamCityBuildChanges.Tests/HtmlOutputTests.cs | using System.Globalization;
using NUnit.Framework;
using TeamCityBuildChanges.Output;
using TeamCityBuildChanges.Testing;
namespace TeamCityBuildChanges.Tests
{
[TestFixture]
public class HtmlOutputTests
{
[Test]
public void CanRenderSimpleTemplate()
{
var result = new RazorOutputRenderer(@".\templates\text.cshtml").Render(TestHelpers.CreateSimpleChangeManifest());
Assert.True(result.ToString(CultureInfo.InvariantCulture).StartsWith(" Version"));//Giddyup.
}
}
}
| using NUnit.Framework;
using TeamCityBuildChanges.Output;
using TeamCityBuildChanges.Testing;
namespace TeamCityBuildChanges.Tests
{
[TestFixture]
public class HtmlOutputTests
{
[Test]
public void CanRenderSimpleTemplate()
{
var result = new RazorOutputRenderer(@".\templates\text.cshtml").Render(TestHelpers.CreateSimpleChangeManifest());
Assert.True(result.ToString().StartsWith("Version"));//Giddyup.
}
}
}
| mit | C# |
da025ad462e626db89a4acab347f0b03e361b9de | exclude from netcore | hazzik/Humanizer,MehdiK/Humanizer | src/Humanizer.Tests/ApiApprover/DiffPlexReporter.cs | src/Humanizer.Tests/ApiApprover/DiffPlexReporter.cs | #if NET46
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using ApprovalTests.Core;
using DiffPlex;
using DiffPlex.DiffBuilder;
using DiffPlex.DiffBuilder.Model;
using System.IO;
using Xunit.Abstractions;
namespace Humanizer.Tests.ApiApprover
{
public class DiffPlexReporter : IApprovalFailureReporter
{
public static readonly DiffPlexReporter Instance = new DiffPlexReporter();
public ITestOutputHelper Output { get; set; }
public void Report(string approved, string received)
{
var approvedText = File.Exists(approved) ? File.ReadAllText(approved) : string.Empty;
var receivedText = File.ReadAllText(received);
var diffBuilder = new InlineDiffBuilder(new Differ());
var diff = diffBuilder.BuildDiffModel(approvedText, receivedText);
foreach (var line in diff.Lines)
{
if (line.Type == ChangeType.Unchanged) continue;
var prefix = " ";
switch (line.Type)
{
case ChangeType.Inserted:
prefix = "+ ";
break;
case ChangeType.Deleted:
prefix = "- ";
break;
}
Output.WriteLine("{0}{1}", prefix, line.Text);
}
}
}
}
#endif
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using ApprovalTests.Core;
using DiffPlex;
using DiffPlex.DiffBuilder;
using DiffPlex.DiffBuilder.Model;
using System.IO;
using Xunit.Abstractions;
namespace Humanizer.Tests.ApiApprover
{
public class DiffPlexReporter : IApprovalFailureReporter
{
public static readonly DiffPlexReporter Instance = new DiffPlexReporter();
public ITestOutputHelper Output { get; set; }
public void Report(string approved, string received)
{
var approvedText = File.Exists(approved) ? File.ReadAllText(approved) : string.Empty;
var receivedText = File.ReadAllText(received);
var diffBuilder = new InlineDiffBuilder(new Differ());
var diff = diffBuilder.BuildDiffModel(approvedText, receivedText);
foreach (var line in diff.Lines)
{
if (line.Type == ChangeType.Unchanged) continue;
var prefix = " ";
switch (line.Type)
{
case ChangeType.Inserted:
prefix = "+ ";
break;
case ChangeType.Deleted:
prefix = "- ";
break;
}
Output.WriteLine("{0}{1}", prefix, line.Text);
}
}
}
}
| mit | C# |
9b44f4418a1effef56ac371eb731ad37944aecf9 | Remove commented out line | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/AtomicChessPuzzles/Views/Shared/_Layout.cshtml | src/AtomicChessPuzzles/Views/Shared/_Layout.cshtml | @using Microsoft.AspNet.Http;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
@if (IsSectionDefined("Title"))
{
@RenderSection("title");@: | Atomic Chess Puzzles
}
else
{
@:No title | Atomic Chess Puzzles
}
</title>
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link href="~/styles/topbar.css" rel="stylesheet">
<link href="~/styles/main.css" rel="stylesheet">
<script src="~/scripts/main.js" type="text/javascript"></script>
@if (IsSectionDefined("AddToHead"))
{
RenderSection("AddToHead");
}
</head>
<body>
<div id="topbar">
<ul id="topbar-menu">
<li>@Html.ActionLink("Home", "Index", "Home", null, null)</li>
<li>@Html.ActionLink("Train", "Train", "Puzzle", null, null)</li>
<li>@Html.ActionLink("Contribute", "Editor", "Puzzle", null, null)</li>
<li class="right">
@{ string u = null;
if (string.IsNullOrEmpty((u = Context.Session.GetString("username"))))
{
@:@Html.ActionLink("Log in", "Login", "User", null, null)
}
else
{
@:<a id="username" href="#">@u</a><ul id="user-nav-content" class="invisible"><li>@Html.ActionLink("Profile", "Profile", "User", new { name = u }, null)</li><li>@Html.ActionLink("Log out", "Logout", "User")</li></ul>
}
}
</li>
</ul>
</div>
<div id="bodycontainer">
@RenderBody()
</div>
</body>
</html>
| @using Microsoft.AspNet.Http;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
@if (IsSectionDefined("Title"))
{
@RenderSection("title");@: | Atomic Chess Puzzles
}
else
{
@:No title | Atomic Chess Puzzles
}
</title>
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link href="~/styles/topbar.css" rel="stylesheet">
<link href="~/styles/main.css" rel="stylesheet">
<script src="~/scripts/main.js" type="text/javascript"></script>
@if (IsSectionDefined("AddToHead"))
{
RenderSection("AddToHead");
}
</head>
<body>
<div id="topbar">
<ul id="topbar-menu">
<li>@Html.ActionLink("Home", "Index", "Home", null, null)</li>
<li>@Html.ActionLink("Train", "Train", "Puzzle", null, null)</li>
<li>@Html.ActionLink("Contribute", "Editor", "Puzzle", null, null)</li>
<li class="right">
@{ string u = null;
if (string.IsNullOrEmpty((u = Context.Session.GetString("username"))))
{
@:@Html.ActionLink("Log in", "Login", "User", null, null)
}
else
{
//@:@Html.ActionLink(u, "Profile", "User", new { name = u }, null)
@:<a id="username" href="#">@u</a><ul id="user-nav-content" class="invisible"><li>@Html.ActionLink("Profile", "Profile", "User", new { name = u }, null)</li><li>@Html.ActionLink("Log out", "Logout", "User")</li></ul>
}
}
</li>
</ul>
</div>
<div id="bodycontainer">
@RenderBody()
</div>
</body>
</html>
| agpl-3.0 | C# |
359cb3ad102c0005b99bbcc832da2127c4f356f7 | Mark as Serializable | RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core | src/NHibernate/Dialect/BitwiseFunctionOperation.cs | src/NHibernate/Dialect/BitwiseFunctionOperation.cs | using System;
using System.Collections;
using NHibernate.Dialect.Function;
using NHibernate.Engine;
using NHibernate.SqlCommand;
using NHibernate.Type;
namespace NHibernate.Dialect
{
[Serializable]
public class BitwiseFunctionOperation : ISQLFunction
{
private readonly string _functionName;
private SqlStringBuilder _sqlBuffer;
private Queue _args;
public BitwiseFunctionOperation(string functionName)
{
_functionName = functionName;
}
#region ISQLFunction Members
public IType ReturnType(IType columnType, IMapping mapping)
{
return NHibernateUtil.Int64;
}
public bool HasArguments
{
get { return true; }
}
public bool HasParenthesesIfNoArguments
{
get { return true; }
}
public SqlString Render(IList args, ISessionFactoryImplementor factory)
{
Prepare(args);
Function();
OpenParens();
Arguments();
CloseParens();
return _sqlBuffer.ToSqlString();
}
#endregion
private void Prepare(IList args)
{
_sqlBuffer = new SqlStringBuilder();
_args = new Queue();
foreach (var arg in args)
{
if (!IsParens(arg.ToString()))
_args.Enqueue(arg);
}
}
private static bool IsParens(string candidate)
{
return candidate == "(" || candidate == ")";
}
private void Function()
{
_sqlBuffer.Add(_functionName);
}
private void OpenParens()
{
_sqlBuffer.Add("(");
}
private void Arguments()
{
while (_args.Count > 0)
{
var arg = _args.Dequeue();
if (arg is Parameter || arg is SqlString)
_sqlBuffer.AddObject(arg);
else
_sqlBuffer.Add(arg.ToString());
if (_args.Count > 0)
_sqlBuffer.Add(", ");
}
}
private void CloseParens()
{
_sqlBuffer.Add(")");
}
}
}
| using System.Collections;
using NHibernate.Dialect.Function;
using NHibernate.Engine;
using NHibernate.SqlCommand;
using NHibernate.Type;
namespace NHibernate.Dialect
{
public class BitwiseFunctionOperation : ISQLFunction
{
private readonly string _functionName;
private SqlStringBuilder _sqlBuffer;
private Queue _args;
public BitwiseFunctionOperation(string functionName)
{
_functionName = functionName;
}
#region ISQLFunction Members
public IType ReturnType(IType columnType, IMapping mapping)
{
return NHibernateUtil.Int64;
}
public bool HasArguments
{
get { return true; }
}
public bool HasParenthesesIfNoArguments
{
get { return true; }
}
public SqlString Render(IList args, ISessionFactoryImplementor factory)
{
Prepare(args);
Function();
OpenParens();
Arguments();
CloseParens();
return _sqlBuffer.ToSqlString();
}
#endregion
private void Prepare(IList args)
{
_sqlBuffer = new SqlStringBuilder();
_args = new Queue();
foreach (var arg in args)
{
if (!IsParens(arg.ToString()))
_args.Enqueue(arg);
}
}
private static bool IsParens(string candidate)
{
return candidate == "(" || candidate == ")";
}
private void Function()
{
_sqlBuffer.Add(_functionName);
}
private void OpenParens()
{
_sqlBuffer.Add("(");
}
private void Arguments()
{
while (_args.Count > 0)
{
var arg = _args.Dequeue();
if (arg is Parameter || arg is SqlString)
_sqlBuffer.AddObject(arg);
else
_sqlBuffer.Add(arg.ToString());
if (_args.Count > 0)
_sqlBuffer.Add(", ");
}
}
private void CloseParens()
{
_sqlBuffer.Add(")");
}
}
}
| lgpl-2.1 | C# |
cf2781724ad71a34e1cb24c6c6a61f000178021b | Set proper version for WixUiClient | rzhw/Squirrel.Windows,rzhw/Squirrel.Windows | src/Shimmer.WiXUiClient/Properties/AssemblyInfo.cs | src/Shimmer.WiXUiClient/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("Shimmer.WiXUiClient")]
[assembly: AssemblyDescription("Shimmer library for creating custom Setup UIs")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GitHub")]
[assembly: AssemblyProduct("Shimmer")]
[assembly: AssemblyCopyright("Copyright © 2012 GitHub")]
// 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("df7541af-f05d-47ff-ad41-8582c41c9406")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("0.5.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("Shimmer.WiXUiClient")]
[assembly: AssemblyDescription("Shimmer library for creating custom Setup UIs")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GitHub")]
[assembly: AssemblyProduct("Shimmer")]
[assembly: AssemblyCopyright("Copyright © 2012 GitHub")]
// 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("df7541af-f05d-47ff-ad41-8582c41c9406")]
// 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# |
8ca15e20d262ebafdea2cc38c8497e1ec53a931e | Add missing imports | smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ZLima12/osu-framework | osu.Framework.Android/AndroidGameWindow.cs | osu.Framework.Android/AndroidGameWindow.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osuTK.Graphics;
using System;
using System.Collections.Generic;
namespace osu.Framework.Android
{
public class AndroidGameWindow : GameWindow
{
public override IGraphicsContext Context
=> View.GraphicsContext;
internal static AndroidGameView View;
public override bool Focused
=> true;
public override osuTK.WindowState WindowState {
get => osuTK.WindowState.Normal;
set { }
}
public AndroidGameWindow() : base(View)
{
}
public override void SetupWindow(FrameworkConfigManager config)
{
// Let's just say the cursor is always in the window.
CursorInWindow = true;
}
protected override IEnumerable<WindowMode> DefaultSupportedWindowModes => new WindowMode[]
{
Configuration.WindowMode.Fullscreen,
};
public override void Run()
{
}
public override void Run(double updateRate)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osuTK.Graphics;
namespace osu.Framework.Android
{
public class AndroidGameWindow : GameWindow
{
public override IGraphicsContext Context
=> View.GraphicsContext;
internal static AndroidGameView View;
public override bool Focused
=> true;
public override osuTK.WindowState WindowState {
get => osuTK.WindowState.Normal;
set { }
}
public AndroidGameWindow() : base(View)
{
}
public override void SetupWindow(FrameworkConfigManager config)
{
// Let's just say the cursor is always in the window.
CursorInWindow = true;
}
protected override IEnumerable<WindowMode> DefaultSupportedWindowModes => new WindowMode[]
{
Configuration.WindowMode.Fullscreen,
};
public override void Run()
{
}
public override void Run(double updateRate)
{
}
}
}
| mit | C# |
fef1f8c21c0f9c0d858d4f672e093640ec54ba7e | Use ProvideBindingRedirection for GHfVS assemblies | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.VisualStudio/Properties/AssemblyInfo.cs | src/GitHub.VisualStudio/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
[assembly: AssemblyTitle("GitHub.VisualStudio")]
[assembly: AssemblyDescription("GitHub for Visual Studio VSPackage")]
[assembly: Guid("fad77eaa-3fe1-4c4b-88dc-3753b6263cd7")]
[assembly: ProvideBindingRedirection(AssemblyName = "GitHub.UI", CodeBase = @"$PackageFolder$\GitHub.UI.dll",
OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = AssemblyVersionInformation.Version)]
[assembly: ProvideBindingRedirection(AssemblyName = "GitHub.VisualStudio.UI", CodeBase = @"$PackageFolder$\GitHub.VisualStudio.UI.dll",
OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = AssemblyVersionInformation.Version)]
[assembly: ProvideBindingRedirection(AssemblyName = "GitHub.Exports", CodeBase = @"$PackageFolder$\GitHub.Exports.dll",
OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = AssemblyVersionInformation.Version)]
[assembly: ProvideBindingRedirection(AssemblyName = "GitHub.Extensions", CodeBase = @"$PackageFolder$\GitHub.Extensions.dll",
OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = AssemblyVersionInformation.Version)]
[assembly: ProvideCodeBase(AssemblyName = "Octokit", CodeBase = @"$PackageFolder$\Octokit.dll")]
[assembly: ProvideCodeBase(AssemblyName = "LibGit2Sharp", CodeBase = @"$PackageFolder$\LibGit2Sharp.dll")]
[assembly: ProvideCodeBase(AssemblyName = "Splat", CodeBase = @"$PackageFolder$\Splat.dll")]
[assembly: ProvideCodeBase(AssemblyName = "Rothko", CodeBase = @"$PackageFolder$\Rothko.dll")]
| using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
[assembly: AssemblyTitle("GitHub.VisualStudio")]
[assembly: AssemblyDescription("GitHub for Visual Studio VSPackage")]
[assembly: Guid("fad77eaa-3fe1-4c4b-88dc-3753b6263cd7")]
[assembly: ProvideCodeBase(AssemblyName = "GitHub.UI", CodeBase = @"$PackageFolder$\GitHub.UI.dll")]
[assembly: ProvideCodeBase(AssemblyName = "GitHub.VisualStudio.UI", CodeBase = @"$PackageFolder$\GitHub.VisualStudio.UI.dll")]
[assembly: ProvideCodeBase(AssemblyName = "GitHub.Exports", CodeBase = @"$PackageFolder$\GitHub.Exports.dll")]
[assembly: ProvideCodeBase(AssemblyName = "GitHub.Extensions", CodeBase = @"$PackageFolder$\GitHub.Extensions.dll")]
[assembly: ProvideCodeBase(AssemblyName = "Octokit", CodeBase = @"$PackageFolder$\Octokit.dll")]
[assembly: ProvideCodeBase(AssemblyName = "LibGit2Sharp", CodeBase = @"$PackageFolder$\LibGit2Sharp.dll")]
[assembly: ProvideCodeBase(AssemblyName = "Splat", CodeBase = @"$PackageFolder$\Splat.dll")]
[assembly: ProvideCodeBase(AssemblyName = "Rothko", CodeBase = @"$PackageFolder$\Rothko.dll")]
| mit | C# |
69776e272f52944b0e0deb780eb4b393bf1e9e18 | Fix assembly name | takenet/lime-csharp | src/Lime.Transport.Http/Properties/AssemblyInfo.cs | src/Lime.Transport.Http/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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lime.Transport.Http.Core")]
[assembly: AssemblyTrademark("")]
// 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("c572407b-ba88-4810-917e-80bff3506c7a")]
[assembly: InternalsVisibleTo("Lime.Transport.Http.UnitTests")]
| 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lime.Transport.Http.Core")]
[assembly: AssemblyTrademark("")]
// 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("c572407b-ba88-4810-917e-80bff3506c7a")]
[assembly: InternalsVisibleTo("Lime.Transport.Http.UnitTests.Core")]
| apache-2.0 | C# |
766543a80c79b7d12b39c2a1982e88f1620d1fbc | Add RestPostComment object | Aux/NTwitch,Aux/NTwitch | src/NTwitch.Rest/Entities/Feeds/RestPostComment.cs | src/NTwitch.Rest/Entities/Feeds/RestPostComment.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class RestPostComment : RestEntity, IPostComment
{
public string Body { get; }
public DateTime CreatedAt { get; }
public IEnumerable<IEmote> Emotes { get; }
public bool IsDeleted { get; }
public IPostPermissions Permissions { get; }
public IEnumerable<IPostReaction> Reactions { get; }
public IUser User { get; }
public RestPostComment(TwitchRestClient client, ulong id) : base(client, id) { }
public Task CreateReactionAsync(ulong emoteid)
{
throw new NotImplementedException();
}
public Task DeleteReactionAsync(ulong emoteid)
{
throw new NotImplementedException();
}
//IPostComment
IEnumerable<IEmote> IPostComment.Emotes
=> Emotes;
IPostPermissions IPostComment.Permissions
=> Permissions;
IEnumerable<IPostReaction> IPostComment.Reactions
=> Reactions;
IUser IPostComment.User
=> User;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NTwitch.Rest.Entities.Feeds
{
public class RestPostComment
{
}
}
| mit | C# |
e8a6a6a0f6a458369090a8b2dd94d23a7f9d661e | Change lbo methods to internal | AshleyPoole/Noobot.Modules | src/Noobot.Modules.LoadBalancerDotOrg/LboPlugin.cs | src/Noobot.Modules.LoadBalancerDotOrg/LboPlugin.cs | using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Common.Logging;
using Newtonsoft.Json;
using Noobot.Core.Configuration;
using Noobot.Core.Plugins;
using Noobot.Modules.LoadBalancerDotOrg.Models;
namespace Noobot.Modules.LoadBalancerDotOrg
{
public class LboPlugin : IPlugin
{
private readonly IConfigReader configReader;
private readonly ILog log;
public LboPlugin(IConfigReader configReader, ILog log)
{
this.configReader = configReader;
this.log = log;
}
public void Start()
{
}
public void Stop()
{
}
internal static bool CommandWellFormatted(string message)
{
return message.Split(" ", StringSplitOptions.RemoveEmptyEntries).Length == 5;
}
internal LoadBalanacerAppliance GetAppliance(string applianceName)
{
try
{
var applianceConfig = this.configReader.GetConfigEntry<string>($"{Configuration.Prefix}:{applianceName}");
var appliance = JsonConvert.DeserializeObject<LoadBalanacerAppliance>(applianceConfig);
return appliance;
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
internal bool TrustAllCerts => this.configReader.GetConfigEntry<bool>($"{Configuration.Prefix}:trustAllCerts");
internal AuthenticationHeaderValue GetAuthHeader(LoadBalanacerAppliance appliance)
{
var bytes = Encoding.ASCII.GetBytes($"{appliance.Username}:{appliance.Password}");
return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
}
internal StringContent GetRequestContent(LoadBalanacerAppliance applaince, LoadBalancerRequest request)
{
var apiRequest = new ApiRequest(applaince.ApiKey, request.Command, request.Vip, request.Rip);
return new StringContent(JsonConvert.SerializeObject(apiRequest), Encoding.UTF8);
}
}
}
| using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Common.Logging;
using Newtonsoft.Json;
using Noobot.Core.Configuration;
using Noobot.Core.Plugins;
using Noobot.Modules.LoadBalancerDotOrg.Models;
namespace Noobot.Modules.LoadBalancerDotOrg
{
public class LboPlugin : IPlugin
{
private readonly IConfigReader configReader;
private readonly ILog log;
public LboPlugin(IConfigReader configReader, ILog log)
{
this.configReader = configReader;
this.log = log;
}
public void Start()
{
}
public void Stop()
{
}
public static bool CommandWellFormatted(string message)
{
return message.Split(" ", StringSplitOptions.RemoveEmptyEntries).Length == 5;
}
public LoadBalanacerAppliance GetAppliance(string applianceName)
{
try
{
var applianceConfig = this.configReader.GetConfigEntry<string>($"{Configuration.Prefix}:{applianceName}");
var appliance = JsonConvert.DeserializeObject<LoadBalanacerAppliance>(applianceConfig);
return appliance;
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
public bool TrustAllCerts => this.configReader.GetConfigEntry<bool>($"{Configuration.Prefix}:trustAllCerts");
public AuthenticationHeaderValue GetAuthHeader(LoadBalanacerAppliance appliance)
{
var bytes = Encoding.ASCII.GetBytes($"{appliance.Username}:{appliance.Password}");
return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
}
public StringContent GetRequestContent(LoadBalanacerAppliance applaince, LoadBalancerRequest request)
{
var apiRequest = new ApiRequest(applaince.ApiKey, request.Command, request.Vip, request.Rip);
return new StringContent(JsonConvert.SerializeObject(apiRequest), Encoding.UTF8);
}
}
}
| mit | C# |
27f20386dfd32a61e22f59a9f62bb9cf99357fbf | Add confirmation button to recovery codes view (#984) | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Manage/GenerateRecoveryCodes.cshtml | BTCPayServer/Views/Manage/GenerateRecoveryCodes.cshtml | @model GenerateRecoveryCodesViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.TwoFactorAuthentication, "Recovery codes");
}
<div class="alert alert-warning" role="alert">
<p>
<span class="fa fa-warning"></span>
<strong>Put these codes in a safe place.</strong>
</p>
<p>
If you lose your device and don't have the recovery codes you will lose access to your account.
</p>
</div>
<div class="row">
<div class="col-md-12">
@for(var row = 0; row < Model.RecoveryCodes.Count(); row += 2)
{
<code>@Model.RecoveryCodes[row]</code><text> </text><code>@Model.RecoveryCodes[row + 1]</code><br />
}
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<a asp-action="Index" class="btn btn-primary">I wrote down my recovery codes</a>
</div>
</div>
| @model GenerateRecoveryCodesViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.TwoFactorAuthentication, "Recovery codes");
}
<div class="alert alert-warning" role="alert">
<p>
<span class="fa fa-warning"></span>
<strong>Put these codes in a safe place.</strong>
</p>
<p>
If you lose your device and don't have the recovery codes you will lose access to your account.
</p>
</div>
<div class="row">
<div class="col-md-12">
@for(var row = 0; row < Model.RecoveryCodes.Count(); row += 2)
{
<code>@Model.RecoveryCodes[row]</code><text> </text><code>@Model.RecoveryCodes[row + 1]</code><br />
}
</div>
</div>
| mit | C# |
a8957b9b5e2e8c8bc6ab902759da179c69149e4a | Add dynamic method constuctor codes (didn't use it yet, other developer may learn something from the function) | insthync/LiteNetLibManager,insthync/LiteNetLibManager | Scripts/Utils/Reflection.cs | Scripts/Utils/Reflection.cs | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection.Emit;
namespace LiteNetLibManager.Utils
{
public class Reflection
{
private static readonly Dictionary<string, Func<object>> expressionActivators = new Dictionary<string, Func<object>>();
private static readonly Dictionary<string, DynamicMethod> dynamicMethodActivators = new Dictionary<string, DynamicMethod>();
// Improve reflection constructor performance with Linq expression (https://rogerjohansson.blog/2008/02/28/linq-expressions-creating-objects/)
public static object GetExpressionActivator(Type type)
{
if (!expressionActivators.ContainsKey(type.FullName))
{
if (type.IsClass)
expressionActivators.Add(type.FullName, Expression.Lambda<Func<object>>(Expression.New(type)).Compile());
else
expressionActivators.Add(type.FullName, Expression.Lambda<Func<object>>(Expression.Convert(Expression.New(type), typeof(object))).Compile());
}
return expressionActivators[type.FullName].Invoke();
}
public static object GetDynamicMethodActivator(Type type)
{
if (!dynamicMethodActivators.ContainsKey(type.FullName))
{
DynamicMethod method = new DynamicMethod("", typeof(object), Type.EmptyTypes);
ILGenerator il = method.GetILGenerator();
if (type.IsValueType)
{
var local = il.DeclareLocal(type);
il.Emit(OpCodes.Ldloc, local);
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Ret);
}
else
{
var ctor = type.GetConstructor(Type.EmptyTypes);
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
}
dynamicMethodActivators.Add(type.FullName, method);
}
return dynamicMethodActivators[type.FullName].Invoke(null, null);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace LiteNetLibManager.Utils
{
public class Reflection
{
private static readonly Dictionary<string, ObjectActivator> objectActivators = new Dictionary<string, ObjectActivator>();
private static string tempTypeName;
// Improve reflection constructor performance with Linq expression (https://rogerjohansson.blog/2008/02/28/linq-expressions-creating-objects/)
public delegate object ObjectActivator();
public static ObjectActivator GetActivator(Type type)
{
tempTypeName = type.FullName;
if (!objectActivators.ContainsKey(tempTypeName))
{
if (type.IsClass)
objectActivators.Add(tempTypeName, Expression.Lambda<ObjectActivator>(Expression.New(type)).Compile());
else
objectActivators.Add(tempTypeName, Expression.Lambda<ObjectActivator>(Expression.Convert(Expression.New(type), typeof(object))).Compile());
}
return objectActivators[tempTypeName];
}
}
}
| mit | C# |
54330a6be2298053343b54a1fc9dac19ab26da34 | Make DebugAssertFailureException serializable in all available builds | physhi/roslyn,DustinCampbell/roslyn,diryboy/roslyn,xasx/roslyn,brettfo/roslyn,eriawan/roslyn,xasx/roslyn,dpoeschl/roslyn,dotnet/roslyn,wvdd007/roslyn,dpoeschl/roslyn,sharwell/roslyn,diryboy/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,bkoelman/roslyn,tmat/roslyn,nguerrera/roslyn,DustinCampbell/roslyn,AmadeusW/roslyn,mavasani/roslyn,gafter/roslyn,KirillOsenkov/roslyn,physhi/roslyn,gafter/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,dpoeschl/roslyn,CyrusNajmabadi/roslyn,abock/roslyn,genlu/roslyn,dotnet/roslyn,heejaechang/roslyn,MichalStrehovsky/roslyn,VSadov/roslyn,weltkante/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,paulvanbrenk/roslyn,MichalStrehovsky/roslyn,jmarolf/roslyn,swaroop-sridhar/roslyn,cston/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,swaroop-sridhar/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,tmeschter/roslyn,dotnet/roslyn,panopticoncentral/roslyn,jcouv/roslyn,cston/roslyn,cston/roslyn,jcouv/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,xasx/roslyn,physhi/roslyn,swaroop-sridhar/roslyn,bkoelman/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bartdesmet/roslyn,jamesqo/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,jamesqo/roslyn,nguerrera/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,AmadeusW/roslyn,paulvanbrenk/roslyn,tmeschter/roslyn,VSadov/roslyn,panopticoncentral/roslyn,davkean/roslyn,wvdd007/roslyn,bartdesmet/roslyn,heejaechang/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,sharwell/roslyn,bkoelman/roslyn,aelij/roslyn,KirillOsenkov/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,brettfo/roslyn,reaction1989/roslyn,sharwell/roslyn,jcouv/roslyn,abock/roslyn,jmarolf/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,abock/roslyn,tannergooding/roslyn,weltkante/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,DustinCampbell/roslyn,stephentoub/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,brettfo/roslyn,eriawan/roslyn,jmarolf/roslyn,weltkante/roslyn,jamesqo/roslyn,davkean/roslyn,diryboy/roslyn,agocke/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,OmarTawfik/roslyn,OmarTawfik/roslyn,agocke/roslyn,davkean/roslyn,KevinRansom/roslyn,VSadov/roslyn,tmat/roslyn,mavasani/roslyn,gafter/roslyn,AlekseyTs/roslyn,paulvanbrenk/roslyn,agocke/roslyn,reaction1989/roslyn,genlu/roslyn,aelij/roslyn,tmat/roslyn | src/Test/Utilities/Portable/ThrowingTraceListener.cs | src/Test/Utilities/Portable/ThrowingTraceListener.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.Diagnostics;
#if !NETSTANDARD1_3
using System.Runtime.Serialization;
#endif
namespace Microsoft.CodeAnalysis
{
// To enable this for a process, add the following to the app.config for the project:
//
// <configuration>
// <system.diagnostics>
// <trace>
// <listeners>
// <remove name="Default" />
// <add name="ThrowingTraceListener" type="Microsoft.CodeAnalysis.ThrowingTraceListener, Roslyn.Test.Utilities" />
// </listeners>
// </trace>
// </system.diagnostics>
//</configuration>
public sealed class ThrowingTraceListener : TraceListener
{
public override void Fail(string message, string detailMessage)
{
throw new DebugAssertFailureException(message + Environment.NewLine + detailMessage);
}
public override void Write(object o)
{
}
public override void Write(object o, string category)
{
}
public override void Write(string message)
{
}
public override void Write(string message, string category)
{
}
public override void WriteLine(object o)
{
}
public override void WriteLine(object o, string category)
{
}
public override void WriteLine(string message)
{
}
public override void WriteLine(string message, string category)
{
}
#if !NETSTANDARD1_3
[Serializable]
#endif
public class DebugAssertFailureException : Exception
{
public DebugAssertFailureException() { }
public DebugAssertFailureException(string message) : base(message) { }
public DebugAssertFailureException(string message, Exception innerException) : base(message, innerException) { }
#if !NETSTANDARD1_3
protected DebugAssertFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
}
}
| // 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.Diagnostics;
namespace Microsoft.CodeAnalysis
{
// To enable this for a process, add the following to the app.config for the project:
//
// <configuration>
// <system.diagnostics>
// <trace>
// <listeners>
// <remove name="Default" />
// <add name="ThrowingTraceListener" type="Microsoft.CodeAnalysis.ThrowingTraceListener, Roslyn.Test.Utilities" />
// </listeners>
// </trace>
// </system.diagnostics>
//</configuration>
public sealed class ThrowingTraceListener : TraceListener
{
public override void Fail(string message, string detailMessage)
{
throw new DebugAssertFailureException(message + Environment.NewLine + detailMessage);
}
public override void Write(object o)
{
}
public override void Write(object o, string category)
{
}
public override void Write(string message)
{
}
public override void Write(string message, string category)
{
}
public override void WriteLine(object o)
{
}
public override void WriteLine(object o, string category)
{
}
public override void WriteLine(string message)
{
}
public override void WriteLine(string message, string category)
{
}
public class DebugAssertFailureException : Exception
{
public DebugAssertFailureException() { }
public DebugAssertFailureException(string message) : base(message) { }
public DebugAssertFailureException(string message, Exception inner) : base(message, inner) { }
}
}
}
| mit | C# |
f829d8cb93d524ee044f4658d2ea52c1349fc2e3 | change namespace | naamunds/cli,jonsequitur/cli,johnbeisner/cli,nguerrera/cli,harshjain2/cli,weshaggard/cli,nguerrera/cli,AbhitejJohn/cli,weshaggard/cli,MichaelSimons/cli,livarcocc/cli-1,weshaggard/cli,livarcocc/cli-1,harshjain2/cli,AbhitejJohn/cli,Faizan2304/cli,blackdwarf/cli,nguerrera/cli,svick/cli,naamunds/cli,ravimeda/cli,EdwardBlair/cli,dasMulli/cli,Faizan2304/cli,naamunds/cli,johnbeisner/cli,EdwardBlair/cli,AbhitejJohn/cli,naamunds/cli,mlorbetske/cli,naamunds/cli,dasMulli/cli,MichaelSimons/cli,jonsequitur/cli,dasMulli/cli,blackdwarf/cli,weshaggard/cli,weshaggard/cli,blackdwarf/cli,MichaelSimons/cli,AbhitejJohn/cli,MichaelSimons/cli,ravimeda/cli,ravimeda/cli,jonsequitur/cli,Faizan2304/cli,nguerrera/cli,mlorbetske/cli,livarcocc/cli-1,harshjain2/cli,MichaelSimons/cli,EdwardBlair/cli,blackdwarf/cli,mlorbetske/cli,mlorbetske/cli,johnbeisner/cli,jonsequitur/cli,svick/cli,svick/cli | test/Microsoft.DotNet.Compiler.Common.Tests/Tests.cs | test/Microsoft.DotNet.Compiler.Common.Tests/Tests.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
namespace Microsoft.DotNet.Cli.Compiler.Common.Tests
{
public class Tests : TestBase
{
[Fact]
public void SimpleSerialize()
{
var options = new CommonCompilerOptions();
options.AdditionalArguments = new[] { "-highentropyva+" };
var args = options.SerializeToArgs();
Assert.Equal(new [] { "--additional-argument:-highentropyva+" }, args);
}
[Fact]
public void WithSpaces()
{
var options = new CommonCompilerOptions();
options.AdditionalArguments = new[] { "-highentropyva+", "-addmodule:\"path with spaces\";\"after semicolon\"" };
var args = options.SerializeToArgs();
Assert.Equal(new [] {
"--additional-argument:-highentropyva+",
"--additional-argument:-addmodule:\"path with spaces\";\"after semicolon\""
}, args);
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
namespace Microsoft.DotNet.Cli.Compiler.Common
{
public class Tests : TestBase
{
[Fact]
public void SimpleSerialize()
{
var options = new CommonCompilerOptions();
options.AdditionalArguments = new[] { "-highentropyva+" };
var args = options.SerializeToArgs();
Assert.Equal(new [] { "--additional-argument:-highentropyva+" }, args);
}
[Fact]
public void WithSpaces()
{
var options = new CommonCompilerOptions();
options.AdditionalArguments = new[] { "-highentropyva+", "-addmodule:\"path with spaces\";\"after semicolon\"" };
var args = options.SerializeToArgs();
Assert.Equal(new [] {
"--additional-argument:-highentropyva+",
"--additional-argument:-addmodule:\"path with spaces\";\"after semicolon\""
}, args);
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.