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
6d0e46134919956ba20a115218b5ba7f43fa933c
Throw if no matching property accessor found.
AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Perspex,Perspex/Perspex
src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs
src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using System.Reactive.Linq; using Avalonia.Data.Core.Plugins; namespace Avalonia.Data.Core { internal class PropertyAccessorNode : SettableNode { private readonly bool _enableValidation; private IPropertyAccessor _accessor; public PropertyAccessorNode(string propertyName, bool enableValidation) { PropertyName = propertyName; _enableValidation = enableValidation; } public override string Description => PropertyName; public string PropertyName { get; } public override Type PropertyType => _accessor?.PropertyType; protected override bool SetTargetValueCore(object value, BindingPriority priority) { if (_accessor != null) { try { return _accessor.SetValue(value, priority); } catch { } } return false; } protected override void StartListeningCore(WeakReference reference) { var plugin = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(reference.Target, PropertyName)); var accessor = plugin?.Start(reference, PropertyName); if (_enableValidation && Next == null) { foreach (var validator in ExpressionObserver.DataValidators) { if (validator.Match(reference, PropertyName)) { accessor = validator.Start(reference, PropertyName, accessor); } } } if (accessor == null) { throw new NotSupportedException( $"Could not find a matching property accessor for {PropertyName}."); } accessor.Subscribe(ValueChanged); _accessor = accessor; } protected override void StopListeningCore() { _accessor.Dispose(); _accessor = null; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using System.Reactive.Linq; using Avalonia.Data.Core.Plugins; namespace Avalonia.Data.Core { internal class PropertyAccessorNode : SettableNode { private readonly bool _enableValidation; private IPropertyAccessor _accessor; public PropertyAccessorNode(string propertyName, bool enableValidation) { PropertyName = propertyName; _enableValidation = enableValidation; } public override string Description => PropertyName; public string PropertyName { get; } public override Type PropertyType => _accessor?.PropertyType; protected override bool SetTargetValueCore(object value, BindingPriority priority) { if (_accessor != null) { try { return _accessor.SetValue(value, priority); } catch { } } return false; } protected override void StartListeningCore(WeakReference reference) { var plugin = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(reference.Target, PropertyName)); var accessor = plugin?.Start(reference, PropertyName); if (_enableValidation && Next == null) { foreach (var validator in ExpressionObserver.DataValidators) { if (validator.Match(reference, PropertyName)) { accessor = validator.Start(reference, PropertyName, accessor); } } } accessor.Subscribe(ValueChanged); _accessor = accessor; } protected override void StopListeningCore() { _accessor.Dispose(); _accessor = null; } } }
mit
C#
4dbb5ad3fa020e416ffc183010003b8d858756ae
Add test for non repo directory
AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning
src/NerdBank.GitVersioning.Tests/RepoFinderTests.cs
src/NerdBank.GitVersioning.Tests/RepoFinderTests.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Nerdbank.GitVersioning.Tests { public class RepoFinderTests : RepoTestBase { private MethodInfo _findGitDirMi; private string _gitDir; public RepoFinderTests(ITestOutputHelper logger) : base(logger) { this.InitializeSourceControl(); _findGitDirMi = typeof(VersionOracle).GetMethod("FindGitDir", BindingFlags.Static | BindingFlags.NonPublic); _gitDir = Path.Combine(this.RepoPath, ".git"); } private string FindGitDir(string startingDir) { var result = _findGitDirMi.Invoke(null, new[] { startingDir }); return (string)result; } private DirectoryInfo CreateSubDirectory() { return Directory.CreateDirectory(Path.Combine(this.RepoPath, Guid.NewGuid().ToString())); } [Fact] public void RepoRoot() { Assert.Equal(FindGitDir(this.RepoPath), _gitDir); } [Fact] public void SubDirectory() { var dir = CreateSubDirectory(); Assert.Equal(FindGitDir(dir.FullName), _gitDir); } [Theory] [InlineData("")] [InlineData("askdjn")] [InlineData("gitdir: ../qwerty")] public void SubDirectoryWithInvalidGitFile(string contents) { var dir = CreateSubDirectory(); File.WriteAllText(Path.Combine(dir.FullName, ".git"), contents); Assert.Equal(FindGitDir(dir.FullName), _gitDir); } [Fact] public void SubDirectoryWithValidGitFile() { var submodule = CreateSubDirectory(); var gitDir = CreateSubDirectory(); File.WriteAllText(Path.Combine(submodule.FullName, ".git"), $"gitdir: ../{gitDir.Name}"); Assert.Equal(FindGitDir(submodule.FullName), gitDir.FullName); } [Fact] public void NonRepoDirectory() { Assert.Equal(FindGitDir(Path.GetTempPath()), null); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Nerdbank.GitVersioning.Tests { public class RepoFinderTests : RepoTestBase { private MethodInfo _findGitDirMi; private string _gitDir; public RepoFinderTests(ITestOutputHelper logger) : base(logger) { this.InitializeSourceControl(); _findGitDirMi = typeof(VersionOracle).GetMethod("FindGitDir", BindingFlags.Static | BindingFlags.NonPublic); _gitDir = Path.Combine(this.RepoPath, ".git"); } private string FindGitDir(string startingDir) { var result = _findGitDirMi.Invoke(null, new[] { startingDir }); return (string)result; } private DirectoryInfo CreateSubDirectory() { return Directory.CreateDirectory(Path.Combine(this.RepoPath, Guid.NewGuid().ToString())); } [Fact] public void RepoRoot() { Assert.Equal(FindGitDir(this.RepoPath), _gitDir); } [Fact] public void SubDirectory() { var dir = CreateSubDirectory(); Assert.Equal(FindGitDir(dir.FullName), _gitDir); } [Theory] [InlineData("")] [InlineData("askdjn")] [InlineData("gitdir: ../qwerty")] public void SubDirectoryWithInvalidGitFile(string contents) { var dir = CreateSubDirectory(); File.WriteAllText(Path.Combine(dir.FullName, ".git"), contents); Assert.Equal(FindGitDir(dir.FullName), _gitDir); } [Fact] public void SubDirectoryWithValidGitFile() { var submodule = CreateSubDirectory(); var gitDir = CreateSubDirectory(); File.WriteAllText(Path.Combine(submodule.FullName, ".git"), $"gitdir: ../{gitDir.Name}"); Assert.Equal(FindGitDir(submodule.FullName), gitDir.FullName); } } }
mit
C#
629aa6ecfe779f02155810f9d161750d49ec0925
add bitmap to texture conversion method
TarasOsiris/Unity-Android-JNI-Toolkit
Scripts/BitmapUtils.cs
Scripts/BitmapUtils.cs
using UnityEngine; namespace DeadMosquito.JniToolkit { public static class BitmapUtils { const string AndroidGraphicsBitmapFactory = "android.graphics.BitmapFactory"; public static AndroidJavaObject Texture2DToAndroidBitmap(this Texture2D tex2D, bool isPng = true) { var encoded = isPng ? tex2D.EncodeToPNG() : tex2D.EncodeToJPG(); return AndroidGraphicsBitmapFactory.AJCCallStaticOnce<AndroidJavaObject>("decodeByteArray", encoded, 0, encoded.Length); } public static Texture2D Texture2DFromBitmap(AndroidJavaObject bitmapAjo) { var compressFormatPng = new AndroidJavaClass("android.graphics.Bitmap$CompressFormat").GetStatic<AndroidJavaObject>("PNG"); var outputStream = new AndroidJavaObject("java.io.ByteArrayOutputStream"); bitmapAjo.CallBool("compress", compressFormatPng, 100, outputStream); var buffer = outputStream.Call<byte[]>("toByteArray"); var tex = new Texture2D(2, 2); tex.LoadImage(buffer); return tex; } } }
using UnityEngine; namespace DeadMosquito.JniToolkit { public static class BitmapUtils { const string AndroidGraphicsBitmapFactory = "android.graphics.BitmapFactory"; public static AndroidJavaObject Texture2DToAndroidBitmap(this Texture2D tex2D, bool isPng = true) { var encoded = isPng ? tex2D.EncodeToPNG() : tex2D.EncodeToJPG(); return AndroidGraphicsBitmapFactory.AJCCallStaticOnce<AndroidJavaObject>("decodeByteArray", encoded, 0, encoded.Length); } } }
apache-2.0
C#
e543efe16e92b8b756f5a4ed6b72194602ba95c8
Add ErrorMessage property
dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch
src/TeacherPouch/ViewModels/PhotoCreateViewModel.cs
src/TeacherPouch/ViewModels/PhotoCreateViewModel.cs
namespace TeacherPouch.ViewModels { public class PhotoCreateViewModel { public PhotoCreateViewModel(string pendingPhotoPath) { PendingPhotoPath = pendingPhotoPath; } public string PendingPhotoPath { get; set; } public string PhotoName { get; set; } public string FileName { get; set; } public string Tags { get; set; } public bool IsPrivate { get; set; } public string Message { get; set; } public string ProposedPhotoName { get; set; } public string ErrorMessage { get; set; } } }
namespace TeacherPouch.ViewModels { public class PhotoCreateViewModel { public PhotoCreateViewModel(string pendingPhotoPath) { PendingPhotoPath = pendingPhotoPath; } public string PendingPhotoPath { get; set; } public string PhotoName { get; set; } public string FileName { get; set; } public string Tags { get; set; } public bool IsPrivate { get; set; } public string Message { get; set; } public string ProposedPhotoName { get; set; } } }
mit
C#
fc300a6fb6065ee452e685165a25f91dae3f86fc
Fix #2 - by updating to .netcore 3.0
springcomp/HttpTrackingMiddleware
src/WebApi/Controllers/WeatherForecastController.cs
src/WebApi/Controllers/WeatherForecastController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace HttpTracking.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } [HttpPost] public async Task Post() { var buffer = new byte[1024]; var count = 0; while ((count = await Request.Body.ReadAsync(buffer, 0, buffer.Length)) != 0) ; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace HttpTracking.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
apache-2.0
C#
83cecb274aed3a1c002862b806d6e0d92e45463e
Use First() instead of FirstOrDefault() in InstalledFilesTestData
feliwir/openSage,feliwir/openSage
src/OpenSage.Game.Tests/InstalledFilesTestData.cs
src/OpenSage.Game.Tests/InstalledFilesTestData.cs
using System; using System.IO; using System.Linq; using Xunit.Abstractions; namespace OpenSage.Data.Tests { internal static class InstalledFilesTestData { private static readonly IInstallationLocator Locator; static InstalledFilesTestData() { Locator = new RegistryInstallationLocator(); } public static string GetInstallationDirectory(SageGame game) => Locator.FindInstallations(game).First().Path; public static void ReadFiles(string fileExtension, ITestOutputHelper output, Action<FileSystemEntry> processFileCallback) { var rootDirectories = SageGames.GetAll().SelectMany(Locator.FindInstallations).Select(i => i.Path); var foundAtLeastOneFile = false; foreach (var rootDirectory in rootDirectories.Where(x => Directory.Exists(x))) { var fileSystem = new FileSystem(rootDirectory); foreach (var file in fileSystem.Files) { if (Path.GetExtension(file.FilePath).ToLower() != fileExtension) { continue; } output.WriteLine($"Reading file {file.FilePath}."); processFileCallback(file); foundAtLeastOneFile = true; } } if (!foundAtLeastOneFile) { throw new Exception($"No files were found matching file extension {fileExtension}"); } } } }
using System; using System.IO; using System.Linq; using Xunit.Abstractions; namespace OpenSage.Data.Tests { internal static class InstalledFilesTestData { private static readonly IInstallationLocator Locator; static InstalledFilesTestData() { Locator = new RegistryInstallationLocator(); } public static string GetInstallationDirectory(SageGame game) => Locator.FindInstallations(game).FirstOrDefault().Path; public static void ReadFiles(string fileExtension, ITestOutputHelper output, Action<FileSystemEntry> processFileCallback) { var rootDirectories = SageGames.GetAll().SelectMany(Locator.FindInstallations).Select(i => i.Path); var foundAtLeastOneFile = false; foreach (var rootDirectory in rootDirectories.Where(x => Directory.Exists(x))) { var fileSystem = new FileSystem(rootDirectory); foreach (var file in fileSystem.Files) { if (Path.GetExtension(file.FilePath).ToLower() != fileExtension) { continue; } output.WriteLine($"Reading file {file.FilePath}."); processFileCallback(file); foundAtLeastOneFile = true; } } if (!foundAtLeastOneFile) { throw new Exception($"No files were found matching file extension {fileExtension}"); } } } }
mit
C#
44eb749652e7601f996b83392241f8e2622fe35a
add max files count check
Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017
PhotoArtSystem/Web/PhotoArtSystem.Web.Infrastructure/Filters/BaseValidateFileAttribute.cs
PhotoArtSystem/Web/PhotoArtSystem.Web.Infrastructure/Filters/BaseValidateFileAttribute.cs
namespace PhotoArtSystem.Web.Infrastructure.Filters { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web; [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class BaseValidateFileAttribute : ValidationAttribute { private const int MbSizeAsBytes = 1024 * 1024; // 1 Mb protected void ValidateOrThrowException(object value, int allowedMaxSize, ICollection<string> allowedMimeTypes) { ICollection<HttpPostedFileBase> files = value as ICollection<HttpPostedFileBase>; // TODO: Extract constants if (files == null) { throw new ValidationException("Please upload a file !"); } if (files.Count < 3) { throw new ValidationException("Please upload at least 3 files !"); } if (files.Count > 15) { throw new ValidationException("Please upload at most 15 files !"); } foreach (HttpPostedFileBase file in files) { if (file == null) { throw new ValidationException("Please upload a file !"); } if (file.ContentLength == 0) { throw new ValidationException("Please upload a non-empty file !"); } if (file.ContentLength > allowedMaxSize) { throw new ValidationException(string.Format( "File size can not exceed {0} mb !", allowedMaxSize / MbSizeAsBytes)); } if (!allowedMimeTypes.Contains(file.ContentType)) { throw new ValidationException("File type not supported !"); } } } } }
namespace PhotoArtSystem.Web.Infrastructure.Filters { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web; [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class BaseValidateFileAttribute : ValidationAttribute { private const int MbSizeAsBytes = 1024 * 1024; // 1 Mb protected void ValidateOrThrowException(object value, int allowedMaxSize, ICollection<string> allowedMimeTypes) { ICollection<HttpPostedFileBase> files = value as ICollection<HttpPostedFileBase>; if (files == null) { throw new ValidationException("Please upload a file !"); } if (files.Count < 3) { throw new ValidationException("Please upload at least 3 files !"); } foreach (HttpPostedFileBase file in files) { if (file == null) { throw new ValidationException("Please upload a file !"); } if (file.ContentLength == 0) { throw new ValidationException("Please upload a non-empty file !"); } if (file.ContentLength > allowedMaxSize) { throw new ValidationException(string.Format( "File size can not exceed {0} mb !", allowedMaxSize / MbSizeAsBytes)); } if (!allowedMimeTypes.Contains(file.ContentType)) { throw new ValidationException("File type not supported !"); } } } } }
mit
C#
6b8f04ba8f472257030e3ead1b34a6192ce695cb
fix #81
AntShares/AntSharesCore
neo-gui/BigDecimal.cs
neo-gui/BigDecimal.cs
using System.Numerics; namespace Neo { internal struct BigDecimal { private readonly BigInteger value; private readonly byte decimals; public BigInteger Value => value; public byte Decimals => decimals; public BigDecimal(BigInteger value, byte decimals) { this.value = value; this.decimals = decimals; } public override string ToString() { BigInteger divisor = BigInteger.Pow(10, decimals); BigInteger result = BigInteger.DivRem(value, divisor, out BigInteger remainder); if (remainder == 0) return result.ToString(); return $"{result}.{remainder.ToString("d" + decimals)}".TrimEnd('0'); } } }
using System.Numerics; namespace Neo { internal struct BigDecimal { private readonly BigInteger value; private readonly byte decimals; public BigInteger Value => value; public byte Decimals => decimals; public BigDecimal(BigInteger value, byte decimals) { this.value = value; this.decimals = decimals; } public override string ToString() { BigInteger divisor = BigInteger.Pow(10, decimals); BigInteger result = BigInteger.DivRem(value, divisor, out BigInteger remainder); if (remainder == 0) return result.ToString(); return $"{result}.{remainder}".TrimEnd('0'); } } }
mit
C#
8333c2bce1cd3f83667ad29c5a905e0975c2575f
update output with Sir Bot
ryanswanstrom/topicnew2
messages/EchoDialog.csx
messages/EchoDialog.csx
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; // For more information about this template visit http://aka.ms/azurebots-csharp-basic [Serializable] public class EchoDialog : IDialog<object> { protected int count = 1; public Task StartAsync(IDialogContext context) { try { context.Wait(MessageReceivedAsync); } catch (OperationCanceledException error) { return Task.FromCanceled(error.CancellationToken); } catch (Exception error) { return Task.FromException(error); } return Task.CompletedTask; } public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument) { var message = await argument; if (message.Text == "reset") { PromptDialog.Confirm( context, AfterResetAsync, "Are you sure you want to reset the count?", "Didn't get that!", promptStyle: PromptStyle.Auto); } else { await context.PostAsync($"{this.count++}: Sir Bot says: {message.Text}"); context.Wait(MessageReceivedAsync); } } public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument) { var confirm = await argument; if (confirm) { this.count = 1; await context.PostAsync("Reset count."); } else { await context.PostAsync("Did not reset count."); } context.Wait(MessageReceivedAsync); } }
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; // For more information about this template visit http://aka.ms/azurebots-csharp-basic [Serializable] public class EchoDialog : IDialog<object> { protected int count = 1; public Task StartAsync(IDialogContext context) { try { context.Wait(MessageReceivedAsync); } catch (OperationCanceledException error) { return Task.FromCanceled(error.CancellationToken); } catch (Exception error) { return Task.FromException(error); } return Task.CompletedTask; } public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument) { var message = await argument; if (message.Text == "reset") { PromptDialog.Confirm( context, AfterResetAsync, "Are you sure you want to reset the count?", "Didn't get that!", promptStyle: PromptStyle.Auto); } else { await context.PostAsync($"{this.count++}: Are you a cow? Say Moo. {message.Text}"); context.Wait(MessageReceivedAsync); } } public async Task AfterResetAsync(IDialogContext context, IAwaitable<bool> argument) { var confirm = await argument; if (confirm) { this.count = 1; await context.PostAsync("Reset count."); } else { await context.PostAsync("Did not reset count."); } context.Wait(MessageReceivedAsync); } }
mit
C#
cdcdacb76a947a1d6427eebe20460272e8ffc2a2
Update comments
sonvister/Binance
src/Binance/WebSocket/IWebSocketStream.cs
src/Binance/WebSocket/IWebSocketStream.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Binance.WebSocket.Events; namespace Binance.WebSocket { /// <summary> /// WebSocket layer to add support for combined streams. /// </summary> public interface IWebSocketStream { /// <summary> /// The low-level web socket client. /// </summary> IWebSocketClient Client { get; } /// <summary> /// Get the subscribed streams. /// </summary> IEnumerable<string> SubscribedStreams { get; } /// <summary> /// Get flag indicating if using combined streams. /// </summary> bool IsCombined { get; } /// <summary> /// Subscribe a callback to a stream. /// This can be done while streaming, subscribing a new stream does not /// take effect until the stream operation is cancelled and restarted. /// </summary> /// <param name="stream">The stream name.</param> /// <param name="callback">The callback.</param> void Subscribe(string stream, Action<WebSocketStreamEventArgs> callback); /// <summary> /// Unsubscribe a callback from a stream. /// This can be done while streaming, unsubscribing a stream does not /// take effect until the stream operation is cancelled and restarted. /// </summary> /// <param name="stream">The stream name.</param> /// <param name="callback">The callback.</param> void Unsubscribe(string stream, Action<WebSocketStreamEventArgs> callback); /// <summary> /// Initiate a web socket connection and begin receiving messages. /// Runtime exceptions are thrown by this method and must be handled /// by the caller, otherwise the <see cref="Task"/> continues receiving /// and processing messages until the token is canceled. /// Open/Close events are provided by <see cref="IWebSocketClient"/>. /// </summary> /// <param name="token">The cancellation token (required to cancel operation).</param> /// <returns></returns> Task StreamAsync(CancellationToken token); } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Binance.WebSocket.Events; namespace Binance.WebSocket { /// <summary> /// WebSocket layer to add support for combined streams. /// </summary> public interface IWebSocketStream { /// <summary> /// The low-level web socket client. /// </summary> IWebSocketClient Client { get; } /// <summary> /// Get the subscribed streams. /// </summary> IEnumerable<string> SubscribedStreams { get; } /// <summary> /// Get flag indicating if using combined streams. /// </summary> bool IsCombined { get; } /// <summary> /// Subscribe a callback to a stream. /// This can be done while streaming, subscribing a new stream does not /// take effect until the stream operation is cancelled and restarted. /// </summary> /// <param name="stream">The stream name.</param> /// <param name="callback">The callback.</param> void Subscribe(string stream, Action<WebSocketStreamEventArgs> callback); /// <summary> /// Unsubscribe a callback from a stream. /// This can be done while streaming, unsubscribing a stream does not /// take effect until the stream operation is cancelled and restarted. /// </summary> /// <param name="stream">The stream name.</param> /// <param name="callback">The callback.</param> void Unsubscribe(string stream, Action<WebSocketStreamEventArgs> callback); /// <summary> /// Initiate a web socket connection and begin receiving messages. /// Runtime exceptions are thrown by this method and must be handled /// by the caller, otherwise the <see cref="Task"/> continues receiving /// and processing messages until the token is canceled. /// </summary> /// <param name="token">The cancellation token (required to cancel operation).</param> /// <returns></returns> Task StreamAsync(CancellationToken token); } }
mit
C#
7cbc835a04cb63d2aa4e4615c0358e4fc3fdb9c6
Tidy VirtualDirectoryPrepender.
BluewireTechnologies/cassette,andrewdavey/cassette,damiensawyer/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,damiensawyer/cassette,honestegg/cassette,damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette
src/Cassette/VirtualDirectoryPrepender.cs
src/Cassette/VirtualDirectoryPrepender.cs
using System; namespace Cassette { /// <summary> /// Prepends the virtual directory to the beginning of application relative URL paths. /// </summary> class VirtualDirectoryPrepender : IUrlModifier { readonly string virtualDirectory; public VirtualDirectoryPrepender(string virtualDirectory) { if (string.IsNullOrEmpty(virtualDirectory) || !virtualDirectory.StartsWith("/")) { throw new ArgumentException("Virtual directory must start with a forward slash."); } if (virtualDirectory.EndsWith("/")) { this.virtualDirectory = virtualDirectory; } else { this.virtualDirectory = virtualDirectory + "/"; } } /// <summary> /// Prepends the virtual directory to the beginning of the application relative URL path. /// </summary> public string Modify(string url) { return virtualDirectory + url.TrimStart('/'); } } }
namespace Cassette { /// <summary> /// Prepends the virtual directory to the beginning of relative URLs. /// </summary> public class VirtualDirectoryPrepender : IUrlModifier { readonly string virtualDirectory; public VirtualDirectoryPrepender(string virtualDirectory) { this.virtualDirectory = virtualDirectory.TrimEnd('/'); } public string Modify(string url) { return virtualDirectory + "/" + url.TrimStart('/'); } } }
mit
C#
779dc83d4443b920ad14341b5baf83f1e6cdc23c
Allow test.exe to connect to arbitrary buses
mono/dbus-sharp,Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp,openmedicus/dbus-sharp,openmedicus/dbus-sharp,arfbtwn/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp
examples/Test.cs
examples/Test.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main (string[] args) { string addr; if (args.Length == 0) addr = Address.Session; else { if (args[0] == "--session") addr = Address.Session; else if (args[0] == "--system") addr = Address.System; else addr = args[0]; } Connection conn = Connection.Open (addr); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; IBus bus = conn.GetObject<IBus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; string myName = bus.Hello (); Console.WriteLine ("myName: " + myName); Console.WriteLine (); string xmlData = bus.Introspect (); Console.WriteLine ("xmlData: " + xmlData); Console.WriteLine (); foreach (string n in bus.ListNames ()) Console.WriteLine (n); Console.WriteLine (); foreach (string n in bus.ListNames ()) Console.WriteLine ("Name " + n + " has owner: " + bus.NameHasOwner (n)); Console.WriteLine (); //Console.WriteLine ("NameHasOwner: " + dbus.NameHasOwner (name)); //Console.WriteLine ("NameHasOwner: " + dbus.NameHasOwner ("fiz")); } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main () { Connection conn = Connection.Open (Address.Session); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; IBus bus = conn.GetObject<IBus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; string myName = bus.Hello (); Console.WriteLine ("myName: " + myName); Console.WriteLine (); string xmlData = bus.Introspect (); Console.WriteLine ("xmlData: " + xmlData); Console.WriteLine (); foreach (string n in bus.ListNames ()) Console.WriteLine (n); Console.WriteLine (); foreach (string n in bus.ListNames ()) Console.WriteLine ("Name " + n + " has owner: " + bus.NameHasOwner (n)); Console.WriteLine (); //Console.WriteLine ("NameHasOwner: " + dbus.NameHasOwner (name)); //Console.WriteLine ("NameHasOwner: " + dbus.NameHasOwner ("fiz")); } }
mit
C#
fc6e203e0196d085055600774212f4d84a019217
make sure avatar precisely follows camera
quinkennedy/unity-yellow-sub
Assets/Scripts/FollowCam.cs
Assets/Scripts/FollowCam.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class FollowCam : NetworkBehaviour { // Use this for initialization void Start () { Debug.Log("[FollowCam:Start]"); if (isLocalPlayer && Camera.main != null) { transform.SetParent(Camera.main.transform, false); } } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class FollowCam : NetworkBehaviour { // Use this for initialization void Start () { Debug.Log("[FollowCam:Start]"); if (isLocalPlayer && Camera.main != null) { transform.SetParent(Camera.main.transform); } } // Update is called once per frame void Update () { } }
isc
C#
1ef6b9416f678ba5d3c54abc64b7355f29276dc4
Remove trailing whitespace
khellang/nancy-bootstrapper-prototype
src/Nancy.Core/DefaultPlatformServices.cs
src/Nancy.Core/DefaultPlatformServices.cs
using System; using Microsoft.Extensions.PlatformAbstractions; using Nancy.Core.Scanning; namespace Nancy.Core { public class DefaultPlatformServices : IPlatformServices { private static readonly Lazy<IPlatformServices> DefaultInstance = new Lazy<IPlatformServices>(() => new DefaultPlatformServices()); public DefaultPlatformServices() { // TODO: If LibraryManager is null here, we should use DependencyContext. var libraryManager = PlatformServices.Default.LibraryManager; // TODO: We need a fallback AssemblyCatalog for full framework. AppDomainAssemblyCatalog? AssemblyCatalog = new LibraryManagerAssemblyCatalog(libraryManager); TypeCatalog = new TypeCatalog(AssemblyCatalog); BootstrapperLocator = new BootstrapperLocator(TypeCatalog); } public static IPlatformServices Instance => DefaultInstance.Value; public IAssemblyCatalog AssemblyCatalog { get; } public ITypeCatalog TypeCatalog { get; } public IBootstrapperLocator BootstrapperLocator { get; } } }
using System; using Microsoft.Extensions.PlatformAbstractions; using Nancy.Core.Scanning; namespace Nancy.Core { public class DefaultPlatformServices : IPlatformServices { private static readonly Lazy<IPlatformServices> DefaultInstance = new Lazy<IPlatformServices>(() => new DefaultPlatformServices()); public DefaultPlatformServices() { // TODO: If LibraryManager is null here, we should use DependencyContext. var libraryManager = PlatformServices.Default.LibraryManager; // TODO: We need a fallback AssemblyCatalog for full framework. AppDomainAssemblyCatalog? AssemblyCatalog = new LibraryManagerAssemblyCatalog(libraryManager); TypeCatalog = new TypeCatalog(AssemblyCatalog); BootstrapperLocator = new BootstrapperLocator(TypeCatalog); } public static IPlatformServices Instance => DefaultInstance.Value; public IAssemblyCatalog AssemblyCatalog { get; } public ITypeCatalog TypeCatalog { get; } public IBootstrapperLocator BootstrapperLocator { get; } } }
apache-2.0
C#
84bf3872549da6dbfd1f27587300b89eed0e0b29
Handle correctly invalid public keys
openchain/openchain
src/Openchain.Ledger/SignatureEvidence.cs
src/Openchain.Ledger/SignatureEvidence.cs
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace Openchain.Ledger { /// <summary> /// Represents a digital signature. /// </summary> public class SignatureEvidence { public SignatureEvidence(ByteString publicKey, ByteString signature) { this.PublicKey = publicKey; this.Signature = signature; } /// <summary> /// Gets the public key corresponding to the signature. /// </summary> public ByteString PublicKey { get; } /// <summary> /// Gets the digital signature. /// </summary> public ByteString Signature { get; } /// <summary> /// Verify that the signature is valid. /// </summary> /// <param name="mutationHash">The data being signed.</param> /// <returns>A boolean indicating wheather the signature is valid.</returns> public bool VerifySignature(byte[] mutationHash) { ECKey key; try { key = new ECKey(PublicKey.ToByteArray()); } catch (ArgumentException) { return false; } catch (IndexOutOfRangeException) { return false; } catch (FormatException) { return false; } try { return key.VerifySignature(mutationHash, Signature.ToByteArray()); } catch (FormatException) { return false; } } } }
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace Openchain.Ledger { /// <summary> /// Represents a digital signature. /// </summary> public class SignatureEvidence { public SignatureEvidence(ByteString publicKey, ByteString signature) { this.PublicKey = publicKey; this.Signature = signature; } /// <summary> /// Gets the public key corresponding to the signature. /// </summary> public ByteString PublicKey { get; } /// <summary> /// Gets the digital signature. /// </summary> public ByteString Signature { get; } /// <summary> /// Verify that the signature is valid. /// </summary> /// <param name="mutationHash">The data being signed.</param> /// <returns>A boolean indicating wheather the signature is valid.</returns> public bool VerifySignature(byte[] mutationHash) { ECKey key; try { key = new ECKey(PublicKey.ToByteArray()); } catch (ArgumentException) { return false; } catch (IndexOutOfRangeException) { return false; } try { return key.VerifySignature(mutationHash, Signature.ToByteArray()); } catch (FormatException) { return false; } } } }
apache-2.0
C#
c276de7ad69156985e2958bb7e0693f204f70588
Update NetDesktopWinFormsWAM Program.cs add missing required header (#3592)
AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet
tests/devapps/WAM/NetFrameworkWam/Program.cs
tests/devapps/WAM/NetFrameworkWam/Program.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Windows.Forms; using Microsoft.Identity.Client.NativeInterop; namespace NetDesktopWinForms { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); Core.VerifyHandleLeaksForTest(); } } }
using System; using System.Windows.Forms; using Microsoft.Identity.Client.NativeInterop; namespace NetDesktopWinForms { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); Core.VerifyHandleLeaksForTest(); } } }
mit
C#
401c813209139a7716cb6dffc1b64f44dcc0137e
fix serialization error
DuncanmaMSFT/docfx,pascalberger/docfx,LordZoltan/docfx,superyyrrzz/docfx,928PJY/docfx,sergey-vershinin/docfx,928PJY/docfx,DuncanmaMSFT/docfx,LordZoltan/docfx,dotnet/docfx,LordZoltan/docfx,928PJY/docfx,sergey-vershinin/docfx,hellosnow/docfx,hellosnow/docfx,superyyrrzz/docfx,superyyrrzz/docfx,dotnet/docfx,sergey-vershinin/docfx,hellosnow/docfx,pascalberger/docfx,LordZoltan/docfx,pascalberger/docfx,dotnet/docfx
src/docfx/Models/FileMetadataPairsItem.cs
src/docfx/Models/FileMetadataPairsItem.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode { using System; using Microsoft.DocAsCode.Glob; using Microsoft.DocAsCode.Utility; [Serializable] public class FileMetadataPairsItem { public GlobMatcher Glob { get; } /// <summary> /// JObject, no need to transform it to object as the metadata value will not be used but only to be serialized /// </summary> public object Value { get; } public FileMetadataPairsItem(string pattern, object value) { Glob = new GlobMatcher(pattern); Value = ConvertToObjectHelper.ConvertJObjectToObject(value); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode { using System; using Microsoft.DocAsCode.Glob; [Serializable] public class FileMetadataPairsItem { public GlobMatcher Glob { get; } /// <summary> /// JObject, no need to transform it to object as the metadata value will not be used but only to be serialized /// </summary> public object Value { get; } public FileMetadataPairsItem(string pattern, object value) { Glob = new GlobMatcher(pattern); Value = value; } } }
mit
C#
79247798a3f970f46e94641da742c65a85d92afc
Fix a silly copy-paste error in ZooKeeper
mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee
Libraries/Microsoft.Experimental.Azure.ZooKeeper/ZooKeeperNodeBase.cs
Libraries/Microsoft.Experimental.Azure.ZooKeeper/ZooKeeperNodeBase.cs
using Microsoft.Experimental.Azure.JavaPlatform; using Microsoft.WindowsAzure.ServiceRuntime; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.Experimental.Azure.ZooKeeper { /// <summary> /// The base class for a typical Azure Zoo Keeper node. /// </summary> public abstract class ZooKeeperNodeBase : NodeWithJavaBase { private ZooKeeperNodeRunner _nodeRunner; private const string ZooKeeperDirectory = "ZooKeeper"; /// <summary> /// The resource directories to download. /// </summary> protected override IEnumerable<string> ResourceDirectoriesToDownload { get { return new[] { ZooKeeperDirectory }.Concat(base.ResourceDirectoriesToDownload); } } /// <summary> /// Overrides the Run method to run Zoo Keeper. /// </summary> protected override void GuardedRun() { _nodeRunner.Run(); } /// <summary> /// Overrides initialization to setup Zoo Keeper. /// </summary> protected override void PostJavaInstallInitialize() { InstallZooKeeper(); } /// <summary> /// Gets the data directory - by default we look for a "DataDirectory" local resource. /// </summary> protected virtual string DataDirectory { get { return RoleEnvironment.GetLocalResource("DataDirectory").RootPath; } } private void InstallZooKeeper() { _nodeRunner = new ZooKeeperNodeRunner( resourceFileDirectory: GetResourcesDirectory(ZooKeeperDirectory), dataDirectory: Path.Combine(DataDirectory, "Data"), configsDirectory: Path.Combine(DataDirectory, "Config"), logsDirectory: Path.Combine(DataDirectory, "Logs"), jarsDirectory: Path.Combine(InstallDirectory, "Jars"), javaHome: JavaHome); _nodeRunner.Setup(); } } }
using Microsoft.Experimental.Azure.JavaPlatform; using Microsoft.WindowsAzure.ServiceRuntime; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.Experimental.Azure.ZooKeeper { /// <summary> /// The base class for a typical Azure Zoo Keeper node. /// </summary> public abstract class ZooKeeperNodeBase : NodeWithJavaBase { private ZooKeeperNodeRunner _nodeRunner; private const string ZooKeeperDirectory = "ElasticSearch"; /// <summary> /// The resource directories to download. /// </summary> protected override IEnumerable<string> ResourceDirectoriesToDownload { get { return new[] { ZooKeeperDirectory }.Concat(base.ResourceDirectoriesToDownload); } } /// <summary> /// Overrides the Run method to run Zoo Keeper. /// </summary> protected override void GuardedRun() { _nodeRunner.Run(); } /// <summary> /// Overrides initialization to setup Zoo Keeper. /// </summary> protected override void PostJavaInstallInitialize() { InstallZooKeeper(); } /// <summary> /// Gets the data directory - by default we look for a "DataDirectory" local resource. /// </summary> protected virtual string DataDirectory { get { return RoleEnvironment.GetLocalResource("DataDirectory").RootPath; } } private void InstallZooKeeper() { _nodeRunner = new ZooKeeperNodeRunner( resourceFileDirectory: GetResourcesDirectory(ZooKeeperDirectory), dataDirectory: Path.Combine(DataDirectory, "Data"), configsDirectory: Path.Combine(DataDirectory, "Config"), logsDirectory: Path.Combine(DataDirectory, "Logs"), jarsDirectory: Path.Combine(InstallDirectory, "Jars"), javaHome: JavaHome); _nodeRunner.Setup(); } } }
mit
C#
0a8eeff2955e57895ee5f90eda6db8d6b947a396
Add a stronger dependency on UnityEngine for testing.
PrecisionMojo/Unity3D.DLLs
PluginTest/TestPlugin.cs
PluginTest/TestPlugin.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace PluginTest { public class TestPlugin : MonoBehaviour { private void Start() { Debug.Log("Start called"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PluginTest { public class TestPlugin { } }
mit
C#
771d6f8074051e4fe3d21ed1b28169ffa7b6c3bb
Update test entity with attribute to denote partition/row key
dontjee/hyde
src/Hyde.IntegrationTest/DecoratedItem.cs
src/Hyde.IntegrationTest/DecoratedItem.cs
using System.Data.Services.Common; using TechSmith.Hyde.Common.DataAnnotations; namespace TechSmith.Hyde.IntegrationTest { /// <summary> /// Class with decorated partition and row key properties, for testing purposes. /// </summary> class DecoratedItem { [PartitionKey] public string Id { get; set; } [RowKey] public string Name { get; set; } public int Age { get; set; } } [DataServiceKey( "PartitionKey", "RowKey")] class DecoratedItemEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity { public string Id { get; set; } public string Name { get; set; } public int Age { get; set; } } }
using TechSmith.Hyde.Common.DataAnnotations; namespace TechSmith.Hyde.IntegrationTest { /// <summary> /// Class with decorated partition and row key properties, for testing purposes. /// </summary> class DecoratedItem { [PartitionKey] public string Id { get; set; } [RowKey] public string Name { get; set; } public int Age { get; set; } } class DecoratedItemEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity { public string Id { get; set; } public string Name { get; set; } public int Age { get; set; } } }
bsd-3-clause
C#
16404ee7d22af5dcf8ac98bfc6441e657cb0e69b
Update Program.cs
bugrooter/UMengPush
UMengPushTest/Program.cs
UMengPushTest/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using UMengPush; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Push app = new Push("xxx", "xxx"); app.sendAndroidUnicast(); //app.sendIOSBroadcast(); /* TODO these methods are all available, just fill in some fields and do the test * demo.sendAndroidCustomizedcastFile(); * demo.sendAndroidBroadcast(); * demo.sendAndroidGroupcast(); * demo.sendAndroidCustomizedcast(); * demo.sendAndroidFilecast(); * * demo.sendIOSBroadcast(); * demo.sendIOSUnicast(); * demo.sendIOSGroupcast(); * demo.sendIOSCustomizedcast(); * demo.sendIOSFilecast(); */ Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using UMengPush; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Push app = new Push("59a40c13310c931fdb00007d", "tnysp39gh6nhphc3ml8axxjh0wyrhnmq"); app.sendAndroidUnicast(); //app.sendIOSBroadcast(); /* TODO these methods are all available, just fill in some fields and do the test * demo.sendAndroidCustomizedcastFile(); * demo.sendAndroidBroadcast(); * demo.sendAndroidGroupcast(); * demo.sendAndroidCustomizedcast(); * demo.sendAndroidFilecast(); * * demo.sendIOSBroadcast(); * demo.sendIOSUnicast(); * demo.sendIOSGroupcast(); * demo.sendIOSCustomizedcast(); * demo.sendIOSFilecast(); */ Console.ReadKey(); } } }
apache-2.0
C#
7f86dd2f680d9f1a84aaf0a971eaf62fb99d2afa
Fix namespace
AlexGhiondea/Fitbit.NET,WestDiscGolf/Fitbit.NET,aarondcoleman/Fitbit.NET,WestDiscGolf/Fitbit.NET,amammay/Fitbit.NET,AlexGhiondea/Fitbit.NET,amammay/Fitbit.NET,aarondcoleman/Fitbit.NET,WestDiscGolf/Fitbit.NET,aarondcoleman/Fitbit.NET,AlexGhiondea/Fitbit.NET,amammay/Fitbit.NET
Fitbit.Portable.Tests/JsonDotNetSerializerTests.cs
Fitbit.Portable.Tests/JsonDotNetSerializerTests.cs
using Fitbit.Api.Portable; using Newtonsoft.Json; using NUnit.Framework; namespace Fitbit.Portable.Tests { [TestFixture] public class JsonDotNetSerializerTests { public class TestClass { [JsonProperty("testproperty")] public string TestProperty { get; set; } // todo: array etc. } [Test] public void DefaultValueCreated() { var serializer = new JsonDotNetSerializer(); var defaultValue = serializer.Deserialize<TestClass>(string.Empty); Assert.AreEqual(default(TestClass), defaultValue); } [Test] public void NoRootValueCreated() { string data = "{\"testproperty\" : \"bob\" }"; var serializer = new JsonDotNetSerializer(); var value = serializer.Deserialize<TestClass>(data); Assert.IsNotNull(value); Assert.AreEqual("bob", value.TestProperty); } [Test] public void RootPropertyValueCreated() { string data = "{\"testclass\" : {\"testproperty\" : \"bob\" } }"; var serializer = new JsonDotNetSerializer(); serializer.RootProperty = "testclass"; var value = serializer.Deserialize<TestClass>(data); Assert.IsNotNull(value); Assert.AreEqual("bob", value.TestProperty); } } }
using Fitbit.Api.Portable; using Newtonsoft.Json; using NUnit.Framework; namespace Fitbit.Tests { [TestFixture] public class JsonDotNetSerializerTests { public class TestClass { [JsonProperty("testproperty")] public string TestProperty { get; set; } // todo: array etc. } [Test] public void DefaultValueCreated() { var serializer = new JsonDotNetSerializer(); var defaultValue = serializer.Deserialize<TestClass>(string.Empty); Assert.AreEqual(default(TestClass), defaultValue); } [Test] public void NoRootValueCreated() { string data = "{\"testproperty\" : \"bob\" }"; var serializer = new JsonDotNetSerializer(); var value = serializer.Deserialize<TestClass>(data); Assert.IsNotNull(value); Assert.AreEqual("bob", value.TestProperty); } [Test] public void RootPropertyValueCreated() { string data = "{\"testclass\" : {\"testproperty\" : \"bob\" } }"; var serializer = new JsonDotNetSerializer(); serializer.RootProperty = "testclass"; var value = serializer.Deserialize<TestClass>(data); Assert.IsNotNull(value); Assert.AreEqual("bob", value.TestProperty); } } }
mit
C#
58f83701b1aacd022dff7257dde9e246f95b97eb
Order usings
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.InlineReviews/Commands/ToggleInlineCommentMarginCommand.cs
src/GitHub.InlineReviews/Commands/ToggleInlineCommentMarginCommand.cs
using System; using System.Threading.Tasks; using System.ComponentModel.Composition; using GitHub.Commands; using GitHub.Services; using GitHub.Extensions; using GitHub.VisualStudio; using GitHub.InlineReviews.Margins; using GitHub.Services.Vssdk.Commands; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; namespace GitHub.InlineReviews.Commands { [Export(typeof(IToggleInlineCommentMarginCommand))] public class ToggleInlineCommentMarginCommand : VsCommand, IToggleInlineCommentMarginCommand { /// <summary> /// Gets the GUID of the group the command belongs to. /// </summary> public static readonly Guid CommandSet = Guids.CommandSetGuid; /// <summary> /// Gets the numeric identifier of the command. /// </summary> public const int CommandId = PkgCmdIDList.ToggleInlineCommentMarginId; readonly Lazy<IVsTextManager> textManager; readonly Lazy<IVsEditorAdaptersFactoryService> editorAdapter; readonly Lazy<IUsageTracker> usageTracker; [ImportingConstructor] public ToggleInlineCommentMarginCommand( IGitHubServiceProvider serviceProvider, Lazy<IVsEditorAdaptersFactoryService> editorAdapter, Lazy<IUsageTracker> usageTracker) : base(CommandSet, CommandId) { textManager = new Lazy<IVsTextManager>(() => serviceProvider.GetService<SVsTextManager, IVsTextManager>()); this.editorAdapter = editorAdapter; this.usageTracker = usageTracker; } public override Task Execute() { usageTracker.Value.IncrementCounter(x => x.ExecuteToggleInlineCommentMarginCommand).Forget(); IVsTextView activeView = null; if (textManager.Value.GetActiveView(1, null, out activeView) == VSConstants.S_OK) { var wpfTextView = editorAdapter.Value.GetWpfTextView(activeView); var options = wpfTextView.Options; var enabled = options.GetOptionValue(InlineCommentTextViewOptions.MarginEnabledId); options.SetOptionValue(InlineCommentTextViewOptions.MarginEnabledId, !enabled); } return Task.CompletedTask; } } }
using System; using System.Threading.Tasks; using System.ComponentModel.Composition; using GitHub.Commands; using GitHub.Services; using GitHub.VisualStudio; using GitHub.InlineReviews.Margins; using GitHub.Services.Vssdk.Commands; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using GitHub.Extensions; namespace GitHub.InlineReviews.Commands { [Export(typeof(IToggleInlineCommentMarginCommand))] public class ToggleInlineCommentMarginCommand : VsCommand, IToggleInlineCommentMarginCommand { /// <summary> /// Gets the GUID of the group the command belongs to. /// </summary> public static readonly Guid CommandSet = Guids.CommandSetGuid; /// <summary> /// Gets the numeric identifier of the command. /// </summary> public const int CommandId = PkgCmdIDList.ToggleInlineCommentMarginId; readonly Lazy<IVsTextManager> textManager; readonly Lazy<IVsEditorAdaptersFactoryService> editorAdapter; readonly Lazy<IUsageTracker> usageTracker; [ImportingConstructor] public ToggleInlineCommentMarginCommand( IGitHubServiceProvider serviceProvider, Lazy<IVsEditorAdaptersFactoryService> editorAdapter, Lazy<IUsageTracker> usageTracker) : base(CommandSet, CommandId) { textManager = new Lazy<IVsTextManager>(() => serviceProvider.GetService<SVsTextManager, IVsTextManager>()); this.editorAdapter = editorAdapter; this.usageTracker = usageTracker; } public override Task Execute() { usageTracker.Value.IncrementCounter(x => x.ExecuteToggleInlineCommentMarginCommand).Forget(); IVsTextView activeView = null; if (textManager.Value.GetActiveView(1, null, out activeView) == VSConstants.S_OK) { var wpfTextView = editorAdapter.Value.GetWpfTextView(activeView); var options = wpfTextView.Options; var enabled = options.GetOptionValue(InlineCommentTextViewOptions.MarginEnabledId); options.SetOptionValue(InlineCommentTextViewOptions.MarginEnabledId, !enabled); } return Task.CompletedTask; } } }
mit
C#
c25cd66dc18783e2374e1d0781f97827051ae81a
modify the link to point to Link.To(api, parameters)
2sic/app-blog,2sic/app-blog,2sic/app-blog
api/BlogController.cs
api/BlogController.cs
// Add namespaces to enable security in Oqtane & Dnn despite the differences #if NETCOREAPP using Microsoft.AspNetCore.Authorization; // .net core [AllowAnonymous] & [Authorize] using Microsoft.AspNetCore.Mvc; // .net core [HttpGet] / [HttpPost] etc. #else using System.Web.Http; // this enables [HttpGet] and [AllowAnonymous] using DotNetNuke.Web.Api; // this is to verify the AntiForgeryToken #endif using System.Xml; using System.IO; using ToSic.Razor.Blade; [AllowAnonymous] // define that all commands can be accessed without a login public class BlogController : Custom.Hybrid.Api12 { [HttpGet] public dynamic Rss() { var detailsPageTabId = Text.Has(Settings.DetailsPage) ? int.Parse((Settings.Get("DetailsPage", convertLinks: false)).Split(':')[1]) : CmsContext.Page.Id; var moduleId = CmsContext.Module.Id; var rssDoc = new XmlDocument(); rssDoc.PreserveWhitespace = true; rssDoc.LoadXml( "<?xml version='1.0' encoding='utf-8'?>" + "<rss version='2.0'>" + "</rss>" ); var root = rssDoc.DocumentElement; var channel = rssDoc.CreateElement("channel"); root.AppendChild(channel); AddTag(channel, "title", Resources.BlogTitle); AddTag(channel, "link", Link.To(api: "api/Blog/Rss", parameters: "PageId=" + detailsPageTabId + "&ModuleId=" + moduleId)); AddTag(channel, "description", Resources.RssDescription); foreach(var post in AsList(App.Query["BlogPosts"]["AllPosts"])) { var itemNode = AddTag(channel, "item", null); AddTag(itemNode, "title", post.EntityTitle); AddTag(itemNode, "link", Link.To(pageId: detailsPageTabId, parameters: "details=" + post.UrlKey)); AddTag(itemNode, "description", post.Teaser); var guidNode = AddTag(itemNode, "guid", post.EntityGuid.ToString()); var isPermaAttr = rssDoc.CreateAttribute("isPermaLink"); isPermaAttr.Value = "false"; guidNode.Attributes.Append(isPermaAttr); AddTag(itemNode, "pubDate", post.PublicationMoment.ToString("R")); } //var xmlStream = new MemoryStream(); //rssDoc.Save(xmlStream); ////var xmlWriter = XmlWriter.Create(xmlStream); ////rssDoc.WriteTo(xmlWriter); ////xmlWriter.Flush(); //xmlStream.Position = 0; return File(download: false, fileDownloadName: "rss.xml", contents: rssDoc); } private XmlElement AddTag(XmlElement parent, string name, string value) { var node = parent.OwnerDocument.CreateElement(name); node.InnerText = value; parent.AppendChild(node); return node; } }
// Add namespaces to enable security in Oqtane & Dnn despite the differences #if NETCOREAPP using Microsoft.AspNetCore.Authorization; // .net core [AllowAnonymous] & [Authorize] using Microsoft.AspNetCore.Mvc; // .net core [HttpGet] / [HttpPost] etc. #else using System.Web.Http; // this enables [HttpGet] and [AllowAnonymous] using DotNetNuke.Web.Api; // this is to verify the AntiForgeryToken #endif using System.Xml; using System.IO; using ToSic.Razor.Blade; [AllowAnonymous] // define that all commands can be accessed without a login public class BlogController : Custom.Hybrid.Api12 { // TODO: SPM // - Then modify the link to point to Link.To(api: ...) // - test with an RSS reader // - verify it works on Oqtane [HttpGet] public dynamic Rss() { var detailsPageTabId = Text.Has(Settings.DetailsPage) ? int.Parse((Settings.Get("DetailsPage", convertLinks: false)).Split(':')[1]) : CmsContext.Page.Id; var rssDoc = new XmlDocument(); rssDoc.PreserveWhitespace = true; rssDoc.LoadXml( "<?xml version='1.0' encoding='utf-8'?>" + "<rss version='2.0'>" + "</rss>" ); var root = rssDoc.DocumentElement; var channel = rssDoc.CreateElement("channel"); root.AppendChild(channel); AddTag(channel, "title", Resources.BlogTitle); //AddTag(channel, "link", Link.To(api: "api/Blog/Rss")); AddTag(channel, "link", Link.To(pageId: detailsPageTabId)); AddTag(channel, "description", Resources.RssDescription); foreach(var post in AsList(App.Query["BlogPosts"]["AllPosts"])) { var itemNode = AddTag(channel, "item", null); AddTag(itemNode, "title", post.EntityTitle); AddTag(itemNode, "link", Link.To(pageId: detailsPageTabId, parameters: "details=" + post.UrlKey)); AddTag(itemNode, "description", post.Teaser); var guidNode = AddTag(itemNode, "guid", post.EntityGuid.ToString()); var isPermaAttr = rssDoc.CreateAttribute("isPermaLink"); isPermaAttr.Value = "false"; guidNode.Attributes.Append(isPermaAttr); AddTag(itemNode, "pubDate", post.PublicationMoment.ToString("R")); } //var xmlStream = new MemoryStream(); //rssDoc.Save(xmlStream); ////var xmlWriter = XmlWriter.Create(xmlStream); ////rssDoc.WriteTo(xmlWriter); ////xmlWriter.Flush(); //xmlStream.Position = 0; return File(download: false, fileDownloadName: "rss.xml", contents: rssDoc); } private XmlElement AddTag(XmlElement parent, string name, string value) { var node = parent.OwnerDocument.CreateElement(name); node.InnerText = value; parent.AppendChild(node); return node; } }
mit
C#
e946886a0033b5d81b68a206e513cc85667fdcf4
Update copyright year
codingteam/codingteam.org.ru,codingteam/codingteam.org.ru
Views/Shared/_Layout.cshtml
Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <title>@ViewData["Title"]</title> <link rel="icon" type="image/png" href="favicon.png"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="~/style.css"/> </head> <body> <div class="container"> <header> <nav class="navbar navbar-default"> <a class="navbar-brand" href="~/"><img src="images/logo-transparent-dark.svg"/></a> <ul class="nav navbar-nav"> <li><a href="~/">Logs</a></li> <li><a href="~/resources">Resources</a> </ul> </nav> </header> <div id="main" role="main"> @RenderBody() </div> <footer>© 2014&ndash;2018 <a href="https://github.com/codingteam/codingteam.org.ru">codingteam</a></footer> </div> </body> </html>
<!DOCTYPE html> <html> <head> <title>@ViewData["Title"]</title> <link rel="icon" type="image/png" href="favicon.png"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="~/style.css"/> </head> <body> <div class="container"> <header> <nav class="navbar navbar-default"> <a class="navbar-brand" href="~/"><img src="images/logo-transparent-dark.svg"/></a> <ul class="nav navbar-nav"> <li><a href="~/">Logs</a></li> <li><a href="~/resources">Resources</a> </ul> </nav> </header> <div id="main" role="main"> @RenderBody() </div> <footer>© 2017 <a href="https://github.com/codingteam/codingteam.org.ru">codingteam</a></footer> </div> </body> </html>
mit
C#
8253aa43b714f26d2532b11545151c87a4ba0bb6
Update MaciejHorbacz.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/MaciejHorbacz.cs
src/Firehose.Web/Authors/MaciejHorbacz.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MaciejHorbacz : IAmACommunityMember { public string FirstName => "Maciej"; public string LastName => "Horbacz"; public string ShortBioOrTagLine => "I use Powershell for daily tasks and automation of every process."; public string StateOrRegion => "Wroclaw, Poland"; public string EmailAddress => "maciej.horbacz@gmail.com"; public string TwitterHandle => "Universecitiz3n"; public string GitHubHandle => "Universecitiz3n"; public string GravatarHash => "f59ba35493d7f1b99e25b6455dc39f5b"; public GeoPosition Position => new GeoPosition(51.1078850,17.0385380); public Uri WebSite => new Uri("https://www.universecitiz3n.tech"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.universecitiz3n.tech/feed.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MateuszCzerniawski : IAmACommunityMember { public string FirstName => "Maciej"; public string LastName => "Horbacz"; public string ShortBioOrTagLine => "I use Powershell for daily tasks and automation of every process."; public string StateOrRegion => "Wroclaw, Poland"; public string EmailAddress => "maciej.horbacz@gmail.com"; public string TwitterHandle => "Universecitiz3n"; public string GitHubHandle => "Universecitiz3n"; public string GravatarHash => "f59ba35493d7f1b99e25b6455dc39f5b"; public GeoPosition Position => new GeoPosition(51.1078850,17.0385380); public Uri WebSite => new Uri("https://www.universecitiz3n.tech"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.universecitiz3n.tech/feed.xml"); } } public string FeedLanguageCode => "en"; } }
mit
C#
73b9a8a4326f1fc6cb5b52ed9cfd0114a7138c4c
Add index action stub
appharbor/foo,appharbor/foo
src/Foo.Web/Controllers/HomeController.cs
src/Foo.Web/Controllers/HomeController.cs
using System; using System.Web.Mvc; namespace Foo.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { throw new NotImplementedException(); } } }
using System.Web.Mvc; namespace Foo.Web.Controllers { public class HomeController : Controller { } }
mit
C#
b8dbfa31045f3e801918e512118c2f094daf2b4b
move model declaration outside of clode block
albertodall/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers
src/Web/WebMVC/Views/Catalog/Index.cshtml
src/Web/WebMVC/Views/Catalog/Index.cshtml
@model Microsoft.eShopOnContainers.WebMVC.ViewModels.CatalogViewModels.IndexViewModel @{ ViewData["Title"] = "Catalog"; } <section class="esh-catalog-hero"> <div class="container"> <img class="esh-catalog-title" src="~/images/main_banner_text.png" /> </div> </section> <section class="esh-catalog-filters"> <div class="container"> <form asp-action="Index" asp-controller="Catalog" method="post"> <label class="esh-catalog-label" data-title="brand"> <select asp-for="@Model.BrandFilterApplied" asp-items="@Model.Brands" class="esh-catalog-filter"></select> </label> <label class="esh-catalog-label" data-title="type"> <select asp-for="@Model.TypesFilterApplied" asp-items="@Model.Types" class="esh-catalog-filter"></select> </label> <input class="esh-catalog-send" type="image" src="~/images/arrow-right.svg" /> </form> </div> </section> <div class="container"> <div class="row"> <br /> @if(ViewBag.BasketInoperativeMsg != null) { <div class="alert alert-warning" role="alert"> &nbsp;@ViewBag.BasketInoperativeMsg </div> } </div> @if (Model.CatalogItems.Count() > 0) { <partial name="_pagination" for="PaginationInfo" /> <div class="esh-catalog-items row"> @foreach (var catalogItem in Model.CatalogItems) { <div class="esh-catalog-item col-md-4"> <partial name="_product" model="catalogItem" /> </div> } </div> <partial name="_pagination" for="PaginationInfo" /> } else { <div class="esh-catalog-items row"> THERE ARE NO RESULTS THAT MATCH YOUR SEARCH </div> } </div>
@{ ViewData["Title"] = "Catalog"; @model Microsoft.eShopOnContainers.WebMVC.ViewModels.CatalogViewModels.IndexViewModel } <section class="esh-catalog-hero"> <div class="container"> <img class="esh-catalog-title" src="~/images/main_banner_text.png" /> </div> </section> <section class="esh-catalog-filters"> <div class="container"> <form asp-action="Index" asp-controller="Catalog" method="post"> <label class="esh-catalog-label" data-title="brand"> <select asp-for="@Model.BrandFilterApplied" asp-items="@Model.Brands" class="esh-catalog-filter"></select> </label> <label class="esh-catalog-label" data-title="type"> <select asp-for="@Model.TypesFilterApplied" asp-items="@Model.Types" class="esh-catalog-filter"></select> </label> <input class="esh-catalog-send" type="image" src="~/images/arrow-right.svg" /> </form> </div> </section> <div class="container"> <div class="row"> <br /> @if(ViewBag.BasketInoperativeMsg != null) { <div class="alert alert-warning" role="alert"> &nbsp;@ViewBag.BasketInoperativeMsg </div> } </div> @if (Model.CatalogItems.Count() > 0) { <partial name="_pagination" for="PaginationInfo" /> <div class="esh-catalog-items row"> @foreach (var catalogItem in Model.CatalogItems) { <div class="esh-catalog-item col-md-4"> <partial name="_product" model="catalogItem"/> </div> } </div> <partial name="_pagination" for="PaginationInfo"/> } else { <div class="esh-catalog-items row"> THERE ARE NO RESULTS THAT MATCH YOUR SEARCH </div> } </div>
mit
C#
bcea41c3afffb470319bbbf58d7a7d749e59c10d
Make View a sealed, internal class. ViewResult should be used if returning an explicit representation.
WebApiContrib/WebApiContrib.Formatting.Html,WebApiContrib/WebApiContrib.Formatting.Html
src/WebApiContrib.Formatting.Html/View.cs
src/WebApiContrib.Formatting.Html/View.cs
using System; namespace WebApiContrib.Formatting.Html { /// <summary> /// Represents default implementation of <see cref="IView"/> interface. /// </summary> internal sealed class View : IView { /// <summary> /// Creates a new <see cref="View"/> instance. /// </summary> /// <param name="viewName">The view name, used to resolve the view template definition.</param> /// <param name="model">The data to be presented by the view.</param> public View(string viewName, object model) : this(viewName, model, null) { } /// <summary> /// Creates a new <see cref="View"/> instance. /// </summary> /// <param name="viewName">The view name, used to resolve the view template definition.</param> /// <param name="model">The data to be presented by the view.</param> /// <param name="modelType">Optional explicit definition of data type for <see cref="Model"/>. /// </param> /// <exception cref="ArgumentException"><paramref name="modelType"/> must be public.</exception> public View(string viewName, object model, Type modelType) { Model = model; ViewName = viewName; ModelType = modelType ?? (model != null ? model.GetType() : null); } /// <summary> /// The data to be presented by the view. /// </summary> public object Model { get; private set; } /// <summary> /// The view name, used to resolve the view template definition. /// </summary> public string ViewName { get; private set; } /// <summary> /// Optional explicit definition of data type for <see cref="Model"/>. When specified, /// this type must be public and have a type name that matches the C# and VB language /// rules for identifiers. It should not be set if the model is an anonymous type or /// a compiler-generated iterator (enumerable or enumerator) type. /// </summary> public Type ModelType { get; private set; } } }
using System; namespace WebApiContrib.Formatting.Html { /// <summary> /// Represents default implementation of <see cref="IView"/> interface. /// </summary> public class View : IView { /// <summary> /// Creates a new <see cref="View"/> instance. /// </summary> /// <param name="viewName">The view name, used to resolve the view template definition.</param> /// <param name="model">The data to be presented by the view.</param> public View(string viewName, object model) : this(viewName, model, null) { } /// <summary> /// Creates a new <see cref="View"/> instance. /// </summary> /// <param name="viewName">The view name, used to resolve the view template definition.</param> /// <param name="model">The data to be presented by the view.</param> /// <param name="modelType">Optional explicit definition of data type for <see cref="Model"/>. /// </param> /// <exception cref="ArgumentException"><paramref name="modelType"/> must be public.</exception> public View(string viewName, object model, Type modelType) { Model = model; ViewName = viewName; ModelType = modelType ?? (model != null ? model.GetType() : null); } /// <summary> /// The data to be presented by the view. /// </summary> public object Model { get; private set; } /// <summary> /// The view name, used to resolve the view template definition. /// </summary> public string ViewName { get; private set; } /// <summary> /// Optional explicit definition of data type for <see cref="Model"/>. When specified, /// this type must be public and have a type name that matches the C# and VB language /// rules for identifiers. It should not be set if the model is an anonymous type or /// a compiler-generated iterator (enumerable or enumerator) type. /// </summary> public Type ModelType { get; private set; } } }
mit
C#
54bfbef485f84b5886c10209fe9e8adaf34b7754
add stacktrace to the error message
ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing
Purchasing.Web/App_Start/VerifyIndexesRole.cs
Purchasing.Web/App_Start/VerifyIndexesRole.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using Microsoft.WindowsAzure.ServiceRuntime; using Purchasing.Web.Services; namespace Purchasing.Web.App_Start { public class VerifyIndexesRole : RoleEntryPoint { private static readonly IIndexService IndexService = new IndexService(new DbService()); public override void Run() { const string pathRoot = @"E:\sitesroot\0\Purchasing.Web\App_Data\Indexes"; IndexService.SetIndexRoot(pathRoot); var mail = new System.Net.Mail.SmtpClient("smtp.ucdavis.edu"); var message = new System.Net.Mail.MailMessage("srkirkland@ucdavis.edu", "srkirkland@ucdavis.edu", "verify indexes role notificaiton", ""); while (true) { Thread.Sleep(TimeSpan.FromMinutes(5)); try { var lastModified = IndexService.LastModified(Indexes.OrderHistory); var sinceLastModified = DateTime.Now - lastModified; message.Body = string.Format("last modified at {0}, which was {1} minutes and {2} seconds ago", lastModified, sinceLastModified.Minutes, sinceLastModified.Seconds); //recreate index if it hasn't been modified for at least 6 minutes //this would mean the update timer isn't working if (sinceLastModified > TimeSpan.FromMinutes(6)) { IndexService.CreateHistoricalOrderIndex(); } } catch (Exception ex) { message.Body = "error checking/setting index: " + ex.Message + " " + ex.StackTrace; } finally { mail.Send(message); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using Microsoft.WindowsAzure.ServiceRuntime; using Purchasing.Web.Services; namespace Purchasing.Web.App_Start { public class VerifyIndexesRole : RoleEntryPoint { private static readonly IIndexService IndexService = new IndexService(new DbService()); public override void Run() { const string pathRoot = @"E:\sitesroot\0\Purchasing.Web\App_Data\Indexes"; IndexService.SetIndexRoot(pathRoot); var mail = new System.Net.Mail.SmtpClient("smtp.ucdavis.edu"); var message = new System.Net.Mail.MailMessage("srkirkland@ucdavis.edu", "srkirkland@ucdavis.edu", "verify indexes role notificaiton", ""); while (true) { Thread.Sleep(TimeSpan.FromMinutes(5)); try { var lastModified = IndexService.LastModified(Indexes.OrderHistory); var sinceLastModified = DateTime.Now - lastModified; message.Body = string.Format("last modified at {0}, which was {1} minutes and {2} seconds ago", lastModified, sinceLastModified.Minutes, sinceLastModified.Seconds); //recreate index if it hasn't been modified for at least 6 minutes //this would mean the update timer isn't working if (sinceLastModified > TimeSpan.FromMinutes(6)) { IndexService.CreateHistoricalOrderIndex(); } } catch (Exception ex) { message.Body = "error checking/setting index: " + ex.Message; } mail.Send(message); } } } }
mit
C#
fe27f1d628ef82d07b789e814dc913e9b09be3df
delete comment
damianrusinek/classes-pas,damianrusinek/classes-pas,damianrusinek/classes-pas,damianrusinek/classes-pas,damianrusinek/classes-pas,damianrusinek/classes-pas
dns_client/dns_client.cs
dns_client/dns_client.cs
using System; using System.Linq; using System.Net; using static System.Net.Dns; namespace DnsClient { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.Error.WriteLine("Usage: run with parameter <host-name>"); Environment.Exit(1); } var hostname = args[0]; try { IPHostEntry entry = GetHostEntry(hostname); //GetHostByName method is obsolete var ip = entry.AddressList.FirstOrDefault(); Console.WriteLine($"Resolved IP address: {ip}"); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
using System; using System.Linq; using System.Net; using static System.Net.Dns; namespace DnsClient { class Program { static void Main(string[] args) { // c# 7.0 tinkering, use this version of input error handling if you want if (args.Length != 1) { Console.Error.WriteLine("Usage: run with parameter <host-name>"); Environment.Exit(1); } var hostname = args[0]; try { IPHostEntry entry = GetHostEntry(hostname); //GetHostByName method is obsolete var ip = entry.AddressList.FirstOrDefault(); Console.WriteLine($"Resolved IP address: {ip}"); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
mit
C#
d49b7350f20ce27aab8184e8b6f9ea2a70006479
Use ConfigureAwait in Venue
leddt/Stockfighter
Stockfighter/Venue.cs
Stockfighter/Venue.cs
using System.Threading.Tasks; using Stockfighter.Helpers; namespace Stockfighter { public class Venue { public string Symbol { get; private set; } public Venue(string symbol) { Symbol = symbol; } public async Task<bool> IsUp() { using (var client = new Client()) { try { var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat").ConfigureAwait(false); return response.ok; } catch { return false; } } } public async Task<Stock[]> GetStocks() { using (var client = new Client()) { var response = await client.Get<StocksResponse>($"venues/{Symbol}/stocks").ConfigureAwait(false); if (response.ok == false) throw new System.Exception($"Got ok == false while getting stocks from {Symbol}"); foreach (var stock in response.symbols) stock.Venue = Symbol; return response.symbols; } } private class Heartbeat { public bool ok { get; set; } public string venue { get; set; } } private class StocksResponse { public bool ok { get; set; } public Stock[] symbols { get; set; } } } }
using System.Threading.Tasks; using Stockfighter.Helpers; namespace Stockfighter { public class Venue { public string Symbol { get; private set; } public Venue(string symbol) { Symbol = symbol; } public async Task<bool> IsUp() { using (var client = new Client()) { try { var response = await client.Get<Heartbeat>($"venues/{Symbol}/heartbeat"); return response.ok; } catch { return false; } } } public async Task<Stock[]> GetStocks() { using (var client = new Client()) { var response = await client.Get<StocksResponse>($"venues/{Symbol}/stocks"); if (response.ok == false) throw new System.Exception($"Got ok == false while getting stocks from {Symbol}"); foreach (var stock in response.symbols) stock.Venue = Symbol; return response.symbols; } } private class Heartbeat { public bool ok { get; set; } public string venue { get; set; } } private class StocksResponse { public bool ok { get; set; } public Stock[] symbols { get; set; } } } }
mit
C#
55567d498b037dbfd9887bc231d8aff12519a15b
Add handling for missing /
Wyamio/Wyam,Wyamio/Wyam,Wyamio/Wyam
themes/Docs/Samson/Shared/_Infobar.cshtml
themes/Docs/Samson/Shared/_Infobar.cshtml
@{ string baseEditUrl = Context.String(DocsKeys.BaseEditUrl); FilePath editFilePath = Model.FilePath(Wyam.Web.WebKeys.EditFilePath); if(!string.IsNullOrWhiteSpace(baseEditUrl) && editFilePath != null) { if (!baseEditUrl[baseEditUrl.Length - 1].equals('/')) { baseEditUrl += "/"; } string editUrl = baseEditUrl + editFilePath.FullPath; <div><p><a href="@editUrl"><i class="fa fa-pencil-square" aria-hidden="true"></i> Edit Content</a></p></div> } <div id="infobar-headings"></div> }
@{ string baseEditUrl = Context.String(DocsKeys.BaseEditUrl); FilePath editFilePath = Model.FilePath(Wyam.Web.WebKeys.EditFilePath); if(!string.IsNullOrWhiteSpace(baseEditUrl) && editFilePath != null) { string editUrl = baseEditUrl + editFilePath.FullPath; <div><p><a href="@editUrl"><i class="fa fa-pencil-square" aria-hidden="true"></i> Edit Content</a></p></div> } <div id="infobar-headings"></div> }
mit
C#
288a14d79886f135edcec5060bbd0df26f2aad2c
Hide results icon on small devices
tpkelly/voting-application,tpkelly/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,Generic-Voting-Application/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application,JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application
VotingApplication/VotingApplication.Web/Views/Dashboard/MyPolls.cshtml
VotingApplication/VotingApplication.Web/Views/Dashboard/MyPolls.cshtml
<div layout="row" ng-controller="MyPollsController"> <div flex-gt-md="50" flex-md="80" flex-sm="90" offset-gt-md="25" offset-md="10" offset-sm="5"> <h1 class="md-display-3">My Polls</h1> <md-content> <loading-spinner loaded="loaded"></loading-spinner> <div ng-show="!polls || polls.length === 0 && loaded" layout layout-align="center center"> You haven't created any polls using this account. </div> <md-list ng-show="loaded"> <md-list-item ng-repeat="poll in polls" class="md-3-line" ng-switch="poll.PollType" ng-click="navigateToPoll(poll.UUID)"> <md-icon ng-switch-when="Basic" md-font-icon="fa-check" class="fa fa-2x" alt="check"></md-icon> <md-icon ng-switch-when="Multi" md-font-icon="fa-check-square-o" class="fa fa-2x" alt="square"></md-icon> <md-icon ng-switch-when="UpDown" md-font-icon="fa-thumbs-o-up" class="fa fa-2x" alt="thumbs"></md-icon> <md-icon ng-switch-when="Points" md-font-icon="fa-tasks" class="fa fa-2x" alt="tasks"></md-icon> <div class="md-list-item-text"> <h3><strong>{{ poll.Name }}</strong></h3> <h4>Created: {{ poll.CreatedDateUtc | dateFilter: 'Do MMM YYYY, HH:mm' }}</h4> <p> {{ poll.PollType }} Vote - {{ poll.ChoiceCount }} Choices - Expires: {{ poll.ExpiryDateUtc | dateFilter: 'Do MMM YYYY, HH:mm' }}</p> <md-icon hide-sm md-font-icon="fa-bar-chart" class="fa fa-2x md-secondary" ng-click="navigateToResults(poll.UUID)" aria-label="chart"></md-icon> </div> <md-divider ng-if="$index !== (polls.length-1)"></md-divider> </md-list-item> </md-list> </md-content> </div> </div>
<div layout="row" ng-controller="MyPollsController"> <div flex-gt-md="50" flex-md="80" flex-sm="90" offset-gt-md="25" offset-md="10" offset-sm="5"> <h1 class="md-display-3">My Polls</h1> <md-content> <loading-spinner loaded="loaded"></loading-spinner> <div ng-show="!polls || polls.length === 0 && loaded" layout layout-align="center center"> You haven't created any polls using this account. </div> <md-list ng-show="loaded"> <md-list-item ng-repeat="poll in polls" class="md-3-line" ng-switch="poll.PollType" ng-click="navigateToPoll(poll.UUID)"> <md-icon ng-switch-when="Basic" md-font-icon="fa-check" class="fa fa-2x" alt="check"></md-icon> <md-icon ng-switch-when="Multi" md-font-icon="fa-check-square-o" class="fa fa-2x" alt="square"></md-icon> <md-icon ng-switch-when="UpDown" md-font-icon="fa-thumbs-o-up" class="fa fa-2x" alt="thumbs"></md-icon> <md-icon ng-switch-when="Points" md-font-icon="fa-tasks" class="fa fa-2x" alt="tasks"></md-icon> <div class="md-list-item-text"> <h3><strong>{{ poll.Name }}</strong></h3> <h4>Created: {{ poll.CreatedDateUtc | dateFilter: 'Do MMM YYYY, HH:mm' }}</h4> <p> {{ poll.PollType }} Vote - {{ poll.ChoiceCount }} Choices - Expires: {{ poll.ExpiryDateUtc | dateFilter: 'Do MMM YYYY, HH:mm' }}</p> <md-icon md-font-icon="fa-bar-chart" class="fa fa-2x md-secondary" ng-click="navigateToResults(poll.UUID)" alt="bar-chart"></md-icon> </div> <md-divider ng-if="$index !== (polls.length-1)"></md-divider> </md-list-item> </md-list> </md-content> </div> </div>
apache-2.0
C#
516f06bbe5f99ca52bfa29e4ff393db941f2e941
Fix nonce calculation
LykkeCity/EthereumApiDotNetCore,LykkeCity/EthereumApiDotNetCore,LykkeCity/EthereumApiDotNetCore
src/Services/Signature/NonceCalculator.cs
src/Services/Signature/NonceCalculator.cs
using System; using System.Linq; using System.Numerics; using Nethereum.Hex.HexTypes; using Nethereum.RPC.Eth.DTOs; using Nethereum.RPC.Eth.Transactions; using Nethereum.Web3; using System.Threading.Tasks; using Nethereum.JsonRpc.Client; using Newtonsoft.Json.Linq; namespace Lykke.Service.EthereumCore.Services.Signature { public class NonceCalculator : INonceCalculator { private readonly IClient _client; private readonly EthGetTransactionCount _getTransactionCount; public NonceCalculator(Web3 web3) { _getTransactionCount = new EthGetTransactionCount(web3.Client); _client = web3.Client; } public async Task<HexBigInteger> GetNonceAsync(string fromAddress, bool checkTxPool) { if (checkTxPool) { var txPool = await _client.SendRequestAsync<JValue>(new RpcRequest($"{Guid.NewGuid()}", "parity_nextNonce", fromAddress)); if (txPool != null) { var bigInt = new HexBigInteger(txPool.Value.ToString()); return bigInt; } } return await _getTransactionCount.SendRequestAsync(fromAddress, BlockParameter.CreatePending()); } } }
using System; using System.Linq; using System.Numerics; using Nethereum.Hex.HexTypes; using Nethereum.RPC.Eth.DTOs; using Nethereum.RPC.Eth.Transactions; using Nethereum.Web3; using System.Threading.Tasks; using Nethereum.JsonRpc.Client; using Newtonsoft.Json.Linq; namespace Lykke.Service.EthereumCore.Services.Signature { public class NonceCalculator : INonceCalculator { private readonly IClient _client; private readonly EthGetTransactionCount _getTransactionCount; public NonceCalculator(Web3 web3) { _getTransactionCount = new EthGetTransactionCount(web3.Client); _client = web3.Client; } public async Task<HexBigInteger> GetNonceAsync(string fromAddress, bool checkTxPool) { if (checkTxPool) { var txPool = await _client.SendRequestAsync<JValue>(new RpcRequest($"{Guid.NewGuid()}", "parity_nextNonce", fromAddress)); if (txPool != null) { var bigInt = new HexBigInteger(txPool.Value.ToString()); return new HexBigInteger(bigInt.Value + 1); } } return await _getTransactionCount.SendRequestAsync(fromAddress, BlockParameter.CreatePending()); } } }
mit
C#
96abbe975d6c81ce8fb3eb1055f5929704cfdae3
Update version to 2.0.4.2.
askeladdk/aiedit,askeladdk/aiedit
AssemblyInfo.cs
AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // // 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("C&C AI Editor")] [assembly: AssemblyDescription("AI Editor for RA2 and TS")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Askeladd")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Askeladd")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // 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.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyFileVersionAttribute("2.0.4.2")]
using System.Reflection; using System.Runtime.CompilerServices; // // 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("C&C AI Editor")] [assembly: AssemblyDescription("AI Editor for RA2 and TS")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Askeladd")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Askeladd")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // 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.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyFileVersionAttribute("2.0.4.1")]
isc
C#
6f293f6bfcade99bcc53b33d8c2678c07c2e893c
order and add attributes for developing
mika-f/Sagitta
Source/PixivNet/Models/ApplicationInfo.cs
Source/PixivNet/Models/ApplicationInfo.cs
using Newtonsoft.Json; using Pixiv.Attributes; namespace Pixiv.Models { public class ApplicationInfo : ApiResponse { [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("latest_version")] public string LatestVersion { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("notice_exists")] public bool IsNoticeExists { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("notice_id")] public string NoticeId { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("notice_important")] public bool IsNoticeImportant { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("notice_message")] public string NoticeMessage { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("store_url")] public string StoreUrl { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("update_available")] public bool IsUpdateAvailable { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("update_required")] public bool IsUpdateRequired { get; set; } [ApiVersion] [MarkedAs("7.7.7")] [JsonProperty("update_message")] public string UpdateMessage { get; set; } } }
using Newtonsoft.Json; namespace Pixiv.Models { /// <summary> /// アプリケーション情報 /// </summary> public class ApplicationInfo : ApiResponse { /// <summary> /// リリースされている最新バージョンの番号 /// </summary> [JsonProperty("latest_version")] public string LatestVersion { get; set; } /// <summary> /// 現在使用しているクライアントに対してアップデートが必要か否か /// </summary> [JsonProperty("update_required")] public bool IsUpdateRequired { get; set; } /// <summary> /// アップデートが利用可能か /// </summary> [JsonProperty("update_available")] public bool IsUpdateAvailable { get; set; } /// <summary> /// 更新用メッセージ /// </summary> [JsonProperty("update_message")] public string UpdateMessage { get; set; } /// <summary> /// 通知があるか否か /// </summary> [JsonProperty("notice_exists")] public bool IsNoticeExists { get; set; } /// <summary> /// ストア URL /// </summary> [JsonProperty("store_url")] public string StoreUrl { get; set; } /// <summary> /// 通知 ID /// </summary> [JsonProperty("notice_id")] public string NoticeId { get; set; } /// <summary> /// 通知が重要かどうか /// </summary> [JsonProperty("notice_important")] public bool IsNoticeImportant { get; set; } /// <summary> /// 通知メッセージ /// </summary> [JsonProperty("notice_message")] public string NoticeMessage { get; set; } } }
mit
C#
676d2ab45070fe1d2ac3c784277edb20a9f6284a
Bump to 3.2.0
SnowflakePowered/michi
Michi/Properties/AssemblyInfo.cs
Michi/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("Michi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Michi")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("f9ce368c-1605-4d83-85e4-8f0b64f42a0c")] // 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("3.2.0.0")] [assembly: AssemblyFileVersion("3.2.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("Michi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Michi")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("f9ce368c-1605-4d83-85e4-8f0b64f42a0c")] // 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("3.1.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")]
mit
C#
b1a67651b4d4343bfe029cd9a9eb4406a4d88c35
Remove unnecessary async/await
Krusen/PinSharp
PinSharp/UrlEncodedHttpClient.cs
PinSharp/UrlEncodedHttpClient.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; namespace PinSharp { internal class UrlEncodedHttpClient : IHttpClient { private HttpClient Client { get; } private MediaTypeFormatter MediaTypeFormatter { get; } public UrlEncodedHttpClient(string baseAddress, string accessToken) { Client = new HttpClient(); Client.BaseAddress = new Uri(baseAddress); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); MediaTypeFormatter = new FormUrlEncodedMediaTypeFormatter(); } public Task<HttpResponseMessage> GetAsync(string requestUri) { return Client.GetAsync(requestUri); } public Task<HttpResponseMessage> PostAsync<T>(string requestUri, T value) { var content = GetFormUrlEncodedContent(value); return Client.PostAsync(requestUri, content); } public Task<HttpResponseMessage> PatchAsync<T>(string requestUri, T value) { using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri)) { request.Headers.ExpectContinue = false; request.Content = GetFormUrlEncodedContent(value); return Client.SendAsync(request); } } public Task<HttpResponseMessage> DeleteAsync(string requestUri) { return Client.DeleteAsync(requestUri); } private static FormUrlEncodedContent GetFormUrlEncodedContent(object obj) { // TODO: Add attribute to ignore property? var data = obj.GetType() .GetProperties() .Select(prop => new KeyValuePair<string, string>(prop.Name, prop.GetValue(obj, null)?.ToString())) .Where(x => x.Value != null); return new FormUrlEncodedContent(data); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; namespace PinSharp { internal class UrlEncodedHttpClient : IHttpClient { private HttpClient Client { get; } private MediaTypeFormatter MediaTypeFormatter { get; } // TODO: Don't add null properties to url encoded content (or as now - don't include null properties in key value pair) public UrlEncodedHttpClient(string baseAddress, string accessToken) { Client = new HttpClient(); Client.BaseAddress = new Uri(baseAddress); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); MediaTypeFormatter = new FormUrlEncodedMediaTypeFormatter(); } public Task<HttpResponseMessage> GetAsync(string requestUri) { return Client.GetAsync(requestUri); } public Task<HttpResponseMessage> PostAsync<T>(string requestUri, T value) { var content = GetFormUrlEncodedContent(value); return Client.PostAsync(requestUri, content); } public async Task<HttpResponseMessage> PatchAsync<T>(string requestUri, T value) { using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri)) { request.Headers.ExpectContinue = false; request.Content = GetFormUrlEncodedContent(value); return await Client.SendAsync(request); } } public Task<HttpResponseMessage> DeleteAsync(string requestUri) { return Client.DeleteAsync(requestUri); } private static FormUrlEncodedContent GetFormUrlEncodedContent(object obj) { var data = obj.GetType() .GetProperties() .Select(prop => new KeyValuePair<string, string>(prop.Name, prop.GetValue(obj, null)?.ToString())) .Where(x => x.Value != null); return new FormUrlEncodedContent(data); } } }
unlicense
C#
0486c1ba202b437f1921af2e86e1b85d42c5ef24
fix culture
klinkby/klinkby.security
Properties/CommonAssemblyInfo.cs
Properties/CommonAssemblyInfo.cs
using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("Mads Klinkby")] [assembly: AssemblyProduct("Klinkby")] [assembly: AssemblyCopyright("Copyright © Mads Breusch Klinkby 2011-2015")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)]
using System; using System.Reflection; using System.Runtime.InteropServices; #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("Mads Klinkby")] [assembly: AssemblyProduct("Klinkby")] [assembly: AssemblyCopyright("Copyright © Mads Breusch Klinkby 2011-2014")] [assembly: AssemblyCulture("en-US")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)]
mit
C#
2bd5e39fe15c759815e8ad27f6f4847876b39202
Add Color
nicogiddev/myFirstProgramCSharp
myFirstProgramCSharp/myFirstProgramCSharp/Program.cs
myFirstProgramCSharp/myFirstProgramCSharp/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myFirstProgramCSharp { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.Yellow; Console.WriteLine("Hello World !"); Console.Read(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myFirstProgramCSharp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World !"); Console.Read(); } } }
mit
C#
e94ccc44d286887d6b6ac675f45d7efc4cdf32ed
add of product code /desc
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string status { get; set; } public DateTime date_last_indexed { get; set; } //ICitations public string act_cfr { get; set; } public string program_area { get; set; } public string description_short { get; set; } public string description_long { get; set; } public DateTime end_date { get; set; } //IClassification public string district_decision { get; set; } public string district { get; set; } public DateTime inspection_end_date { get; set; } public string center { get; set; } public string project_area { get; set; } public string legal_name { get; set; } //IRefusal public string fei_number { get; set; } public string product_code { get; set; } public string product_code_description { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string status { get; set; } public DateTime date_last_indexed { get; set; } //ICitations public string act_cfr { get; set; } public string program_area { get; set; } public string description_short { get; set; } public string description_long { get; set; } public DateTime end_date { get; set; } //IClassification public string district_decision { get; set; } public string district { get; set; } public DateTime inspection_end_date { get; set; } public string center { get; set; } public string project_area { get; set; } public string legal_name { get; set; } //IRefusal public string fei_number { get; set; } } }
apache-2.0
C#
77b67a3ed6ec6dd0ae4356b852379960d3f7585f
Clarify definition of success
DasAllFolks/SharpGraphs
Graph/IGraph.cs
Graph/IGraph.cs
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents a graph. /// </summary> /// <typeparam name="V">The vertex type.</typeparam> /// <typeparam name="E">The edge type.</typeparam> public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V> { /// <summary> /// The graph's vertices. /// </summary> ISet<V> Vertices { get; } /// <summary> /// Attempts to add an edge to the graph. /// </summary> /// <param name="edge"> /// The edge. /// </param> /// <param name="allowNewVertices"> /// Iff true, add vertices in the edge which aren't yet in the graph /// to the graph's vertex set. /// </param> /// <returns> /// True if the edge was successfully added (the definition of /// "success" may vary from implementation to implementation). /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the edge contains at least one edge not in the graph, /// and allowNewVertices is set to false. /// </exception> bool TryAddEdge(E edge, bool allowNewVertices = false); bool TryRemoveEdge(E edge); } }
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents a graph. /// </summary> /// <typeparam name="V">The vertex type.</typeparam> /// <typeparam name="E">The edge type.</typeparam> public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V> { /// <summary> /// The graph's vertices. /// </summary> ISet<V> Vertices { get; } /// <summary> /// Attempts to add an edge to the graph. /// </summary> /// <param name="edge"> /// The edge. /// </param> /// <param name="allowNewVertices"> /// Iff true, add vertices in the edge which aren't yet in the graph /// to the graph's vertex set. /// </param> /// <returns> /// True iff the edge was successfully added. /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the edge contains at least one edge not in the graph, /// and allowNewVertices is set to false. /// </exception> bool TryAddEdge(E edge, bool allowNewVertices = false); } }
apache-2.0
C#
2b5b000bfb3a22e798956ec3a51e3d6920fa6479
Remove unused usings
AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit,AvaloniaUI/AvaloniaEdit
src/AvaloniaEdit/Rendering/TextViewCachedElements.cs
src/AvaloniaEdit/Rendering/TextViewCachedElements.cs
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { internal sealed class TextViewCachedElements { private Dictionary<string, TextLine> _nonPrintableCharacterTexts; public TextLine GetTextForNonPrintableCharacter(string text, TextRunProperties properties) { if (_nonPrintableCharacterTexts == null) _nonPrintableCharacterTexts = new Dictionary<string, TextLine>(); TextLine textLine; if (!_nonPrintableCharacterTexts.TryGetValue(text, out textLine)) { textLine = FormattedTextElement.PrepareText(TextFormatter.Current, text, properties); _nonPrintableCharacterTexts[text] = textLine; } return textLine; } } }
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { internal sealed class TextViewCachedElements { private Dictionary<string, TextLine> _nonPrintableCharacterTexts; public TextLine GetTextForNonPrintableCharacter(string text, TextRunProperties properties) { if (_nonPrintableCharacterTexts == null) _nonPrintableCharacterTexts = new Dictionary<string, TextLine>(); TextLine textLine; if (!_nonPrintableCharacterTexts.TryGetValue(text, out textLine)) { textLine = FormattedTextElement.PrepareText(TextFormatter.Current, text, properties); _nonPrintableCharacterTexts[text] = textLine; } return textLine; } } }
mit
C#
a0adf52659452e44203cdc3f34e9d835bb25c6e8
Revert "Allowing to use multiple instance of StartableAttribute"
clariuslabs/clide,clariuslabs/clide,clariuslabs/clide
src/Clide.Interfaces/Startable/StartableAttribute.cs
src/Clide.Interfaces/Startable/StartableAttribute.cs
using System; using System.ComponentModel.Composition; namespace Clide { /// <summary> /// Provides the metadata attriute to export a component that needs to be started /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class StartableAttribute : ExportAttribute { /// <summary> /// Creates an instance of <see cref="StartableAttribute"/> /// </summary> /// <param name="context"> /// Specifies the context when the component should be started. /// The value can be a Guid string which it will be automatically parsed into <see cref="StartableAttribute.ContextGuid"/> /// </param> /// <param name="order"> /// Specifies the order value for the startable component /// </param> public StartableAttribute(string context, double order = 1000) : base(typeof(IStartable)) { Context = context; Guid guid; if (Guid.TryParse(context, out guid)) ContextGuid = guid; } /// <summary> /// Gets the context when the component should be started /// </summary> public string Context { get; } /// <summary> /// Gets the context as a Guid if it could be parsed /// </summary> public Guid ContextGuid { get; } /// <summary> /// Gets the order value for the startable component /// </summary> public double Order { get; } } }
using System; using System.ComponentModel.Composition; namespace Clide { /// <summary> /// Provides the metadata attriute to export a component that needs to be started /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class StartableAttribute : ExportAttribute { /// <summary> /// Creates an instance of <see cref="StartableAttribute"/> /// </summary> /// <param name="context"> /// Specifies the context when the component should be started. /// The value can be a Guid string which it will be automatically parsed into <see cref="StartableAttribute.ContextGuid"/> /// </param> /// <param name="order"> /// Specifies the order value for the startable component /// </param> public StartableAttribute(string context, double order = 1000) : base(typeof(IStartable)) { Context = context; Guid guid; if (Guid.TryParse(context, out guid)) ContextGuid = guid; } /// <summary> /// Gets the context when the component should be started /// </summary> public string Context { get; } /// <summary> /// Gets the context as a Guid if it could be parsed /// </summary> public Guid ContextGuid { get; } /// <summary> /// Gets the order value for the startable component /// </summary> public double Order { get; } } }
mit
C#
0de9430661cd30292ccada345d90c83b28f652f7
Fix non-collection formatting regression w/ refactoring.
yfakariya/NLiblet,yfakariya/NLiblet
src/CoreUtilities/Text/Formatters/ObjectFormatter.cs
src/CoreUtilities/Text/Formatters/ObjectFormatter.cs
#region -- License Terms -- // // NLiblet // // Copyright (C) 2011 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Diagnostics; namespace NLiblet.Text.Formatters { /// <summary> /// <see cref="ItemFormatter"/> specialized for <see cref="Object"/>. /// </summary> internal sealed class ObjectFormatter : ItemFormatter<object> { public static readonly ObjectFormatter Instance = new ObjectFormatter(); private ObjectFormatter() { } public override void FormatTo( object item, FormattingContext context ) { Debug.WriteLine( "ObjectFormatter::FormatTo( {0} : {1}, {2} )", item, item == null ? "(unknown)" : item.GetType().FullName, context ); if ( Object.ReferenceEquals( item, null ) ) { context.Buffer.Append( CommonCustomFormatter.NullRepresentation ); return; } if ( context.IsInCollection ) { context.Buffer.Append( '\"' ); } context.Buffer.Append( item.ToString() ); if ( context.IsInCollection ) { context.Buffer.Append( '\"' ); } } } }
#region -- License Terms -- // // NLiblet // // Copyright (C) 2011 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Diagnostics; namespace NLiblet.Text.Formatters { /// <summary> /// <see cref="ItemFormatter"/> specialized for <see cref="Object"/>. /// </summary> internal sealed class ObjectFormatter : ItemFormatter<object> { public static readonly ObjectFormatter Instance = new ObjectFormatter(); private ObjectFormatter() { } public override void FormatTo( object item, FormattingContext context ) { Debug.WriteLine( "ObjectFormatter::FormatTo( {0} : {1}, {2} )", item, item == null ? "(unknown)" : item.GetType().FullName, context ); if ( Object.ReferenceEquals( item, null ) ) { context.Buffer.Append( CommonCustomFormatter.NullRepresentation ); } else { context.Buffer.Append( '\"' ).Append( item.ToString() ).Append( "\"" ); } } } }
apache-2.0
C#
3323449a7a3680adf6a14d1e2700016d53a78063
Use config from current working dir (#1622)
AntShares/AntShares
src/neo/Utility.cs
src/neo/Utility.cs
using Akka.Actor; using Akka.Event; using Microsoft.Extensions.Configuration; using Neo.Plugins; using System; using System.IO; using System.Reflection; namespace Neo { public static class Utility { internal class Logger : ReceiveActor { public Logger() { Receive<InitializeLogger>(_ => Sender.Tell(new LoggerInitialized())); Receive<LogEvent>(e => Log(e.LogSource, (LogLevel)e.LogLevel(), e.Message)); } } /// <summary> /// Load configuration with different Environment Variable /// </summary> /// <param name="config">Configuration</param> /// <returns>IConfigurationRoot</returns> public static IConfigurationRoot LoadConfig(string config) { var env = Environment.GetEnvironmentVariable("NEO_NETWORK"); var configFile = string.IsNullOrWhiteSpace(env) ? $"{config}.json" : $"{config}.{env}.json"; // Working directory var file = Path.Combine(Environment.CurrentDirectory, configFile); if (!File.Exists(file)) { // EntryPoint folder file = Path.Combine(Assembly.GetEntryAssembly().Location, configFile); if (!File.Exists(file)) { // neo.dll folder file = Path.Combine(Assembly.GetExecutingAssembly().Location, configFile); if (!File.Exists(file)) { // default config return new ConfigurationBuilder().Build(); } } } return new ConfigurationBuilder() .AddJsonFile(file, true) .Build(); } public static void Log(string source, LogLevel level, object message) { foreach (ILogPlugin plugin in Plugin.Loggers) plugin.Log(source, level, message); } } }
using Akka.Actor; using Akka.Event; using Microsoft.Extensions.Configuration; using Neo.Plugins; using System; namespace Neo { public static class Utility { internal class Logger : ReceiveActor { public Logger() { Receive<InitializeLogger>(_ => Sender.Tell(new LoggerInitialized())); Receive<LogEvent>(e => Log(e.LogSource, (LogLevel)e.LogLevel(), e.Message)); } } /// <summary> /// Load configuration with different Environment Variable /// </summary> /// <param name="config">Configuration</param> /// <returns>IConfigurationRoot</returns> public static IConfigurationRoot LoadConfig(string config) { var env = Environment.GetEnvironmentVariable("NEO_NETWORK"); var configFile = string.IsNullOrWhiteSpace(env) ? $"{config}.json" : $"{config}.{env}.json"; return new ConfigurationBuilder() .AddJsonFile(configFile, true) .Build(); } public static void Log(string source, LogLevel level, object message) { foreach (ILogPlugin plugin in Plugin.Loggers) plugin.Log(source, level, message); } } }
mit
C#
fe7191c0cbb8bf253a95fb78abbbd96224edd9e9
Increase version number
ermshiperete/BuildTasks.TextTemplating
BuildTasks.TextTemplating/Properties/AssemblyInfo.cs
BuildTasks.TextTemplating/Properties/AssemblyInfo.cs
// Copyright (c) 2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("BuildTasks.TextTemplating")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SIL International")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Eberhard Beilharz")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.3.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
// Copyright (c) 2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("BuildTasks.TextTemplating")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SIL International")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Eberhard Beilharz")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.2.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
2b67beddea156f36708098682e5cd91fd632bc0a
Implement PV in Monitor Controller
cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings
DynThings.WebPortal/Controllers/MonitorController.cs
DynThings.WebPortal/Controllers/MonitorController.cs
///////////////////////////////////////////////////////////////// // Created by : Caesar Moussalli // // TimeStamp : 31-1-2016 // // Content : Handel the Monitor Actions // // Notes : // // // ///////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using DynThings.WebPortal; using DynThings.Data.Models; using DynThings.Data.Repositories; namespace DynThings.WebPortal.Controllers { public class MonitorController : Controller { [HttpGet] public ActionResult MonitorViewsList() { List<LocationView> monitors = UnitOfWork.repoLocationViews.GetAll(); return View(monitors); } // GET: Monitor public ActionResult MonitorView(long id) { LocationView monitor = UnitOfWork.repoLocationViews.Find(id); return View(monitor); } [HttpGet] public PartialViewResult GetPVMonitorMap(int id) { LocationView monitor = UnitOfWork.repoLocationViews.Find(id); return PartialView("_MonitorViewMap", monitor); } [HttpGet] public PartialViewResult GetPVMonitorLocation(int id) { Location location = UnitOfWork.repoLocations.Find(id); return PartialView("_MonitorLocation", location); } [HttpGet] public PartialViewResult GetPVMonitorEndPointMain(Guid guid) { Endpoint endPoint = UnitOfWork.repoEndpoints.Find(guid); return PartialView("_MonitorEndPointMain", endPoint); } [HttpGet] public PartialViewResult GetPVMonitorEndPointHistory(Guid guid) { List<EndPointIO> IOs = UnitOfWork.repoEndpointIOs.GetEndpointIOs(guid, 5); return PartialView("_MonitorEndPointHistory", IOs); } } }
///////////////////////////////////////////////////////////////// // Created by : Caesar Moussalli // // TimeStamp : 31-1-2016 // // Content : Handel the Monitor Actions // // Notes : // // // ///////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using DynThings.WebPortal; using DynThings.Data.Models; using DynThings.Data.Repositories; namespace DynThings.WebPortal.Controllers { public class MonitorController : Controller { [HttpGet] public ActionResult MonitorViewsList() { List<LocationView> monitors = UnitOfWork.repoLocationViews.GetAll(); return View(monitors); } // GET: Monitor public ActionResult MonitorView(long id) { LocationView monitor = UnitOfWork.repoLocationViews.Find(id); return View(monitor); } [HttpGet] public PartialViewResult GetPVMonitorMap(int id) { LocationView monitor = UnitOfWork.repoLocationViews.Find(id); return PartialView("_MonitorViewMap", monitor); } [HttpGet] public PartialViewResult GetPVMonitorLocation(int id) { Location location = UnitOfWork.repoLocations.Find(id); return PartialView("_MonitorLocation", location); } [HttpGet] public PartialViewResult GetPVMonitorEndPointMain(Guid guid) { Endpoint endPoint = UnitOfWork.repoEndpoints.Find(guid); return PartialView("_MonitorEndPointMain", endPoint); } [HttpGet] public PartialViewResult GetPVMonitorEndPointHistory(Guid guid) { List<EndPointIO> IOs = UnitOfWork.repoEndpointIOs.GetEndpointIOs(guid, 4); return PartialView("_MonitorEndPointHistory", IOs); } } }
mit
C#
915d0afb898e56bc56e6ecd6f693296be6c29e1f
Fix problems with launching and exiting the app
ParriauxMaxime/assignement3
a/Program.cs
a/Program.cs
using System; using System.Net; namespace a { class Program { //Code is dirty, who cares, it's C#. static void Main(string[] args) { Server server = new Server(IPAddress.Any, 5000); server.Start(); Console.WriteLine("Press q to exit"); while (true) { try { if (Console.ReadKey().KeyChar == 'q') { server.Stop(); return; } } catch (Exception) { //who cares ? } } } } }
using System; using System.Net; namespace a { class Program { //Code is dirty, who cares, it's C#. static void Main(string[] args) { //IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName()); //foreach (IPAddress curAdd in heserver.AddressList) //{ Server server = new Server(IPAddress.Loopback, 5000); server.Start(); Console.WriteLine("Press q to exit"); while (true) { try { char c = (char)Console.ReadLine()[0]; if (c == 'q') { server.Stop(); break; } } catch (Exception) { //who cares ? } } //} } } }
mit
C#
231d82ada90d78b77792f2c0efaa2b77f809884a
Drop out-of-date field
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
unity/EditorPlugin/Utils/RiderScriptableSingleton.cs
unity/EditorPlugin/Utils/RiderScriptableSingleton.cs
using UnityEngine; namespace JetBrains.Rider.Unity.Editor.Utils { // no need to set cache, because otherwise new Unity process will restore the value from the file cache. //[Location("JetBrainsRiderPluginCache.txt", LocationAttribute.Location.LibraryFolder)] internal class RiderScriptableSingleton: ScriptObjectSingleton<RiderScriptableSingleton> { [SerializeField] private bool myCsprojProcessedOnce; public bool CsprojProcessedOnce { get => myCsprojProcessedOnce; set { myCsprojProcessedOnce = value; Save(true); } } } }
using UnityEngine; namespace JetBrains.Rider.Unity.Editor.Utils { // no need to set cache, because otherwise new Unity process will restore the value from the file cache. //[Location("JetBrainsRiderPluginCache.txt", LocationAttribute.Location.LibraryFolder)] internal class RiderScriptableSingleton: ScriptObjectSingleton<RiderScriptableSingleton> { [SerializeField] private bool myCsprojProcessedOnce; [SerializeField] private bool myLastPlayModeEnabled = false; public bool CsprojProcessedOnce { get => myCsprojProcessedOnce; set { myCsprojProcessedOnce = value; Save(true); } } public bool LastPlayModeEnabled { get => myLastPlayModeEnabled; set { myLastPlayModeEnabled = value; Save(true); } } } }
apache-2.0
C#
99282dbb2a43760596e68eeaf575fbff9bd221e6
Bump version to 1.0.2
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { // this is for the AssemblyVersion and AssemblyVersion attributes, which can't handle alphanumerics internal const string VersionForAssembly = "1.0.2"; // Actual real version internal const string Version = "1.0.2"; } }
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { // this is for the AssemblyVersion and AssemblyVersion attributes, which can't handle alphanumerics internal const string VersionForAssembly = "1.0.1"; // Actual real version internal const string Version = "1.0.1"; } }
mit
C#
c3350a792369347731e7ed4829f5c2dc9ae85c19
add setters to RotateAroundBy properties
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/Portable/Actions/Intervals/RotateAroundBy.cs
Bindings/Portable/Actions/Intervals/RotateAroundBy.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Urho.Actions { public class RotateAroundBy : FiniteTimeAction { public Vector3 Point { get; set; } public float DeltaX { get; set; } public float DeltaY { get; set; } public float DeltaZ { get; set; } public TransformSpace TransformSpace { get; set; } #region Constructors public RotateAroundBy(float duration, Vector3 point, float deltaX, float deltaY, float deltaZ, TransformSpace ts = TransformSpace.World) : base(duration) { Point = point; DeltaX = deltaX; DeltaY = deltaY; DeltaZ = deltaZ; TransformSpace = ts; } #endregion Constructors protected internal override ActionState StartAction(Node target) { return new RotateAroundByState(this, target); } public override FiniteTimeAction Reverse() { return new RotateAroundBy(Duration, Point, -DeltaX, -DeltaY, -DeltaZ); } } public class RotateAroundByState : FiniteTimeActionState { protected Vector3 Point; protected float DeltaX; protected float DeltaY; protected float DeltaZ; protected TransformSpace TransformSpace; float prevTime; public RotateAroundByState(RotateAroundBy action, Node target) : base(action, target) { Point = action.Point; DeltaX = action.DeltaX; DeltaY = action.DeltaY; DeltaZ = action.DeltaZ; TransformSpace = action.TransformSpace; } public override void Update(float time) { if (Target == null) return; var timeDelta = time - prevTime; Target.RotateAround(Point, new Quaternion(timeDelta * DeltaX, timeDelta * DeltaY, timeDelta * DeltaZ), TransformSpace); prevTime = time; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Urho.Actions { public class RotateAroundBy : FiniteTimeAction { #region Constructors public RotateAroundBy(float duration, Vector3 point, float deltaX, float deltaY, float deltaZ, TransformSpace ts = TransformSpace.World) : base(duration) { Point = point; DeltaX = deltaX; DeltaY = deltaY; DeltaZ = deltaZ; TransformSpace = ts; } #endregion Constructors public Vector3 Point { get; } public float DeltaX { get; } public float DeltaY { get; } public float DeltaZ { get; } public TransformSpace TransformSpace { get; } protected internal override ActionState StartAction(Node target) { return new RotateAroundByState(this, target); } public override FiniteTimeAction Reverse() { return new RotateAroundBy(Duration, Point, -DeltaX, -DeltaY, -DeltaZ); } } public class RotateAroundByState : FiniteTimeActionState { protected Vector3 Point; protected float DeltaX; protected float DeltaY; protected float DeltaZ; protected TransformSpace TransformSpace; float prevTime; public RotateAroundByState(RotateAroundBy action, Node target) : base(action, target) { Point = action.Point; DeltaX = action.DeltaX; DeltaY = action.DeltaY; DeltaZ = action.DeltaZ; TransformSpace = action.TransformSpace; } public override void Update(float time) { if (Target == null) return; var timeDelta = time - prevTime; Target.RotateAround(Point, new Quaternion(timeDelta * DeltaX, timeDelta * DeltaY, timeDelta * DeltaZ), TransformSpace); prevTime = time; } } }
mit
C#
fd43d2f982b6dea6a227681449f9d05362dc8326
Update ApplicationInsightsExceptionTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsExceptionTelemeter.cs
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsExceptionTelemeter.cs
using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.ApplicationInsights.DataContracts; namespace TIKSN.Analytics.Telemetry { public class ApplicationInsightsExceptionTelemeter : IExceptionTelemeter { [Obsolete] public async Task TrackExceptionAsync(Exception exception) => await TrackExceptionInternalAsync(exception, null).ConfigureAwait(false); [Obsolete] public Task TrackExceptionAsync(Exception exception, TelemetrySeverityLevel severityLevel) => TrackExceptionInternalAsync(exception, severityLevel); [Obsolete] private static Task TrackExceptionInternalAsync(Exception exception, TelemetrySeverityLevel? severityLevel) { try { var telemetry = new ExceptionTelemetry(exception) { SeverityLevel = ApplicationInsightsHelper.ConvertSeverityLevel(severityLevel) }; ApplicationInsightsHelper.TrackException(telemetry); } catch (Exception ex) { Debug.WriteLine(ex); } return Task.FromResult<object>(null); } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.ApplicationInsights.DataContracts; namespace TIKSN.Analytics.Telemetry { public class ApplicationInsightsExceptionTelemeter : IExceptionTelemeter { public async Task TrackException(Exception exception) => await this.TrackExceptionInternal(exception, null); public Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel) => this.TrackExceptionInternal(exception, severityLevel); private Task TrackExceptionInternal(Exception exception, TelemetrySeverityLevel? severityLevel) { try { var telemetry = new ExceptionTelemetry(exception); telemetry.SeverityLevel = ApplicationInsightsHelper.ConvertSeverityLevel(severityLevel); ApplicationInsightsHelper.TrackException(telemetry); } catch (Exception ex) { Debug.WriteLine(ex); } return Task.FromResult<object>(null); } } }
mit
C#
6631f0de1958755724c8f5c375b544e79def2ec6
add CommentMarkdownHeading
smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,peppy/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu
osu.Game/Overlays/Comments/CommentMarkdownContainer.cs
osu.Game/Overlays/Comments/CommentMarkdownContainer.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 Markdig.Syntax; using Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Comments { public class CommentMarkdownContainer : OsuMarkdownContainer { public override MarkdownTextFlowContainer CreateTextFlow() => new CommentMarkdownTextFlowContainer(); protected override MarkdownHeading CreateHeading(HeadingBlock headingBlock) => new CommentMarkdownHeading(headingBlock); private class CommentMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { // Don't render image in comment for now protected override void AddImage(LinkInline linkInline) { } } private class CommentMarkdownHeading : OsuMarkdownHeading { public CommentMarkdownHeading(HeadingBlock headingBlock) : base(headingBlock) { } protected override float GetFontSizeByLevel(int level) { var defaultFontSize = base.GetFontSizeByLevel(6); switch (level) { case 1: return 1.2f * defaultFontSize; case 2: return 1.1f * defaultFontSize; default: return defaultFontSize; } } } } }
// 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 Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Comments { public class CommentMarkdownContainer : OsuMarkdownContainer { public override MarkdownTextFlowContainer CreateTextFlow() => new CommentMarkdownTextFlowContainer(); private class CommentMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { // Don't render image in comment for now protected override void AddImage(LinkInline linkInline) { } } } }
mit
C#
6c4586876aa913947babf3e87b64508b7f6e0d18
Revert "Added revision to version"
MatthiasKainer/DotNetRules.Events,MatthiasKainer/DotNetRules.Events,MatthiasKainer/DotNetRules.Events
Sources/DotNetRules.Events/Properties/AssemblyInfo.cs
Sources/DotNetRules.Events/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("DotNetRules.Events")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Matthias Kainer")] [assembly: AssemblyProduct("DotNetRules.Events")] [assembly: AssemblyCopyright("Copyright © Matthias Kainer 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("be6fc86a-1db6-4076-b3c7-1e33ee1ef0b4")] // 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.*")]
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("DotNetRules.Events")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Matthias Kainer")] [assembly: AssemblyProduct("DotNetRules.Events")] [assembly: AssemblyCopyright("Copyright © Matthias Kainer 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("be6fc86a-1db6-4076-b3c7-1e33ee1ef0b4")] // 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.*.*")]
mit
C#
fdca5b8bb9f25c8edec115fd63ad3a7da5116290
Fix NullReferenceException
setchi/NoteEditor,setchi/NotesEditor
Assets/Scripts/NotesEditor/CanvasEvents.cs
Assets/Scripts/NotesEditor/CanvasEvents.cs
using UniRx; using UniRx.Triggers; using UnityEngine; public class CanvasEvents : MonoBehaviour { public Subject<Vector3> VerticalLineOnMouseDownObservable = new Subject<Vector3>(); public Subject<Vector3> ScrollPadOnMouseEnterObservable = new Subject<Vector3>(); public Subject<Vector3> ScrollPadOnMouseDownObservable = new Subject<Vector3>(); public Subject<Vector3> ScrollPadOnMouseExitObservable = new Subject<Vector3>(); public Subject<float> MouseScrollWheelObservable = new Subject<float>(); void Awake() { this.UpdateAsObservable() .Select(_ => Input.GetAxis("Mouse ScrollWheel")) .Where(delta => delta != 0) .Subscribe(MouseScrollWheelObservable.OnNext); } public void ScrollPadOnMouseDown() { ScrollPadOnMouseDownObservable.OnNext(Input.mousePosition); } public void ScrollPadOnMouseEnter() { ScrollPadOnMouseEnterObservable.OnNext(Input.mousePosition); } public void ScrollPadOnMouseExit() { ScrollPadOnMouseExitObservable.OnNext(Input.mousePosition); } public void VerticalLineOnMouseDown() { VerticalLineOnMouseDownObservable.OnNext(Input.mousePosition); } }
using UniRx; using UniRx.Triggers; using UnityEngine; public class CanvasEvents : MonoBehaviour { public Subject<Vector3> VerticalLineOnMouseDownObservable = new Subject<Vector3>(); public Subject<Vector3> ScrollPadOnMouseEnterObservable = new Subject<Vector3>(); public Subject<Vector3> ScrollPadOnMouseDownObservable = new Subject<Vector3>(); public Subject<Vector3> ScrollPadOnMouseExitObservable = new Subject<Vector3>(); public IObservable<float> MouseScrollWheelObservable; void Awake() { MouseScrollWheelObservable = this.UpdateAsObservable() .Select(_ => Input.GetAxis("Mouse ScrollWheel")) .Where(delta => delta != 0); } public void ScrollPadOnMouseDown() { ScrollPadOnMouseDownObservable.OnNext(Input.mousePosition); } public void ScrollPadOnMouseEnter() { ScrollPadOnMouseEnterObservable.OnNext(Input.mousePosition); } public void ScrollPadOnMouseExit() { ScrollPadOnMouseExitObservable.OnNext(Input.mousePosition); } public void VerticalLineOnMouseDown() { VerticalLineOnMouseDownObservable.OnNext(Input.mousePosition); } }
mit
C#
07f85790f1f49ebf6edffefa1e8cb3ae26096dfe
Remove warning on Location, override GetHashcode()
Curdflappers/UltimateTicTacToe
Assets/Resources/Scripts/Location.cs
Assets/Resources/Scripts/Location.cs
 public class Location { int row, col; public int Row { get { return row; } } public int Col { get { return col; } } public Location(int r, int c) { row = r; col = c; } public override bool Equals(object obj) { if(obj is Location) { Location other = (Location)obj; return Row == other.Row && Col == other.Col; } return false; } public override int GetHashCode() { return base.GetHashCode(); } }
public class Location { int row, col; public int Row { get { return row; } } public int Col { get { return col; } } public Location(int r, int c) { row = r; col = c; } public override bool Equals(object obj) { if(obj is Location) { Location other = (Location)obj; return Row == other.Row && Col == other.Col; } return false; } }
mit
C#
002b1721d8da891e097663c17e97b74bc1aaa107
update dependency nuget.commandline to v6.1.0
FantasticFiasco/mvvm-dialogs
build/build.cake
build/build.cake
#tool nuget:?package=NuGet.CommandLine&version=6.1.0 #load utils.cake ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // VARIABLES ////////////////////////////////////////////////////////////////////// var solution = new FilePath("./../MvvmDialogs.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Clean all files") .Does(() => { DeleteFiles("./../**/*.nupkg"); CleanDirectories("./../**/bin"); CleanDirectories("./../**/obj"); }); Task("Restore") .Description("Restore NuGet packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Build") .Description("Build the solution") .IsDependentOn("Restore") .Does(() => { MSBuild( solution, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2022, Configuration = configuration, MaxCpuCount = 0, // Enable parallel build }); }); Task("Pack") .Description("Create NuGet package") .IsDependentOn("Build") .Does(() => { var versionPrefix = GetVersionPrefix("./../Directory.Build.props"); var versionSuffix = GetVersionSuffix("./../Directory.Build.props"); var isTag = EnvironmentVariable("APPVEYOR_REPO_TAG"); // Unless this is a tag, this is a pre-release if (isTag != "true") { var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT"); versionSuffix = $"sha-{sha}"; } NuGetPack( "./../MvvmDialogs.nuspec", new NuGetPackSettings { Version = versionPrefix, Suffix = versionSuffix, Symbols = true, ArgumentCustomization = args => args.Append("-SymbolPackageFormat snupkg") }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Pack"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
#tool nuget:?package=NuGet.CommandLine&version=6.0.0 #load utils.cake ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // VARIABLES ////////////////////////////////////////////////////////////////////// var solution = new FilePath("./../MvvmDialogs.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Clean all files") .Does(() => { DeleteFiles("./../**/*.nupkg"); CleanDirectories("./../**/bin"); CleanDirectories("./../**/obj"); }); Task("Restore") .Description("Restore NuGet packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Build") .Description("Build the solution") .IsDependentOn("Restore") .Does(() => { MSBuild( solution, new MSBuildSettings { ToolVersion = MSBuildToolVersion.VS2022, Configuration = configuration, MaxCpuCount = 0, // Enable parallel build }); }); Task("Pack") .Description("Create NuGet package") .IsDependentOn("Build") .Does(() => { var versionPrefix = GetVersionPrefix("./../Directory.Build.props"); var versionSuffix = GetVersionSuffix("./../Directory.Build.props"); var isTag = EnvironmentVariable("APPVEYOR_REPO_TAG"); // Unless this is a tag, this is a pre-release if (isTag != "true") { var sha = EnvironmentVariable("APPVEYOR_REPO_COMMIT"); versionSuffix = $"sha-{sha}"; } NuGetPack( "./../MvvmDialogs.nuspec", new NuGetPackSettings { Version = versionPrefix, Suffix = versionSuffix, Symbols = true, ArgumentCustomization = args => args.Append("-SymbolPackageFormat snupkg") }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Pack"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
apache-2.0
C#
08e5de11b7426a4ee330313936f30e725f816651
Update HttpPoller.cs
keith-hall/Extensions,keith-hall/Extensions
src/HttpPoller.cs
src/HttpPoller.cs
using System; using System.Net; using System.Reactive.Linq; namespace HallLibrary.Extensions { public static class HttpPoller { public struct ResponseDetails { public WebHeaderCollection Headers; public string Text; } /// <summary> /// Poll a <paramref name="url"/> at the specified <paramref name="frequency"/> and create an observable that will update every time the content recieved changes. /// </summary> /// <param name="url">The url to poll.</param> /// <param name="frequency">The frequency to poll at.</param> /// <param name="createWebClient">An optional function to create a WebClient instance, for overriding timeouts, request headers etc.</param> /// <returns>An observable containing the response headers and content of the specified url.</returns> public static IObservable<ResponseDetails> PollURL(string url, TimeSpan frequency, Func<WebClient> createWebClient = null) { createWebClient = createWebClient ?? (() => new WebClient()); Func<ResponseDetails> download = () => { var wc = createWebClient(); return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders }; }; return Observable.Interval(frequency) .Select(l => download()) .StartWith(download()) .DistinctUntilChanged(wc => wc.Text).Publish().RefCount(); } } }
using System; using System.Net; using System.Reactive.Linq; namespace HallLibrary.Extensions { public static class HttpPoller { public struct ResponseDetails { public WebHeaderCollection Headers; public string Text; } public static IObservable<ResponseDetails> PollURL(string url, TimeSpan frequency, Func<WebClient> createWebClient = null) { createWebClient = createWebClient ?? (() => new WebClient()); Func<ResponseDetails> download = () => { var wc = createWebClient(); return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders }; }; return Observable.Interval(frequency) .Select(l => download()) .StartWith(download()) .DistinctUntilChanged(wc => wc.Text).Publish().RefCount(); } } }
apache-2.0
C#
8040c91956d62f6a5153ead77f0e1bbacaa51df6
Update index.cshtml
Aleksandrovskaya/apmathclouddif
site/index.cshtml
site/index.cshtml
@{ double t_0 = 0; double t_end = 150; double step = 0.1; int N = Convert.ToInt32((t_end-t_0)/step) + 1; String data = ""; bool show_chart = false; if (IsPost){ show_chart = true; var number = Request["text1"]; double xd = number.AsInt(); double t = 0; double x1 = 0; double x2 = 0; double x3 = 0; double currentx1 = 0; double currentx2 = 0; double currentx3 = 0; for (int i=0; i < N; ++i){ t = t_0 + step * i; currentx1 = x1 + step* (-0.1252*x1 + -0.004637*(x2-xd)+-0.002198*x3); currentx2 = x2 + step*x1 ; currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd)); x1 = currentx1; x2 = currentx2; x3 = currentx3; data += "[" +t+"," + x2+"]"; if( i < N - 1){ data += ","; } } } } <html> <head> <meta charset="utf-8"> <title>MathBox</title> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Time', 'pitch'], @data ]); var options = { title: 'pitch', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <form action="" method="post" align="center"> <p><label for="text1">Input Angle</label><br> <input type="text" name="text1" /></p> <p><input type="submit" value=" Show " /></p> </form> @if (show_chart) { <div id="curve_chart" style="width: 900px; height: 500px"></div> } else { <p></p> } </body> </html>
@{ double t_0 = 0; double t_end = 150; double step = 0.1; int N = Convert.ToInt32((t_end-t_0)/step) + 1; String data = ""; bool show_chart = false; if (IsPost){ show_chart = true; var number = Request["text1"]; double xd = number.AsInt(); double t = 0; double x1 = 0; double x2 = 0; double x3 = 0; double currentx1 = 0; double currentx2 = 0; double currentx3 = 0; for (int i=0; i < N; ++i){ t = t_0 + step * i; currentx1 = x1 + step* (-0.1252*x1 + -0.004637*(x2-xd)+-0.002198*x3); currentx2 = x2 + step*x1 ; currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd)); x1 = currentx1; x2 = currentx2; x3 = currentx3; data += "[" +t+"," + x2+"]"; if( i < N - 1){ data += ","; } } } } <html> <head> <meta charset="utf-8"> <title>MathBox</title> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Time', 'pitch'], @data ]); var options = { title: 'pitch', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <form action="" method="post"> <p><label for="text1">Input Angle</label><br> <input type="text" name="text1" /></p> <p><input type="submit" value=" Show " /></p> </form> @if (show_chart) { <div id="curve_chart" style="width: 900px; height: 500px"></div> } else { <p></p> } </body> </html>
mit
C#
07194f785eb59dcec514b1dbfa23a822667cc535
change color scheme
takenet/lime-csharp
src/Lime.Client.TestConsole/Converters/DataOperationToBrushConverter.cs
src/Lime.Client.TestConsole/Converters/DataOperationToBrushConverter.cs
using Lime.Protocol.Network; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Media; namespace Lime.Client.TestConsole.Converters { public class DataOperationToBrushConverter : IMultiValueConverter { private readonly SolidColorBrush LightDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#424242")); private readonly SolidColorBrush NormalDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#212121")); #region IValueConverter Members public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //First value is Direction property //Second value is IsDarkMode property if (values[0] is DataOperation && ((DataOperation)values[0]) == DataOperation.Receive) { if (values[1] is Style) { return NormalDarkMode; } return new SolidColorBrush(Colors.LightGray); } if (values[1] is Style) { return LightDarkMode; } return new SolidColorBrush(Colors.White); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
using Lime.Protocol.Network; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Media; namespace Lime.Client.TestConsole.Converters { public class DataOperationToBrushConverter : IMultiValueConverter { private readonly SolidColorBrush LightDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#1e1e1e")); private readonly SolidColorBrush NormalDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#252526")); #region IValueConverter Members public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //First value is Direction property //Second value is IsDarkMode property if (values[0] is DataOperation && ((DataOperation)values[0]) == DataOperation.Receive) { if (values[1] is Style) { return NormalDarkMode; } return new SolidColorBrush(Colors.LightGray); } if (values[1] is Style) { return LightDarkMode; } return new SolidColorBrush(Colors.White); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
apache-2.0
C#
284e8d55216db65c6b0e9fc795eb127789a29cce
Update HttpPoller.cs
keith-hall/Extensions,keith-hall/Extensions
src/HttpPoller.cs
src/HttpPoller.cs
using System; using System.Net; using System.Reactive.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains static methods useful for polling a REST/HTTP server's resources. /// </summary> public static class HttpPoller { /// <summary> /// Contains the response headers and plain text content from a web request, or details of the Exception that occurred as a result of the request. /// </summary> public struct ResponseDetails { public WebHeaderCollection Headers; public string Text; public WebException Exception; } /// <summary> /// Poll a <paramref name="url"/> at the specified <paramref name="frequency"/> and create an observable that will update every time the content recieved changes. /// </summary> /// <param name="url">The url to poll.</param> /// <param name="frequency">The frequency to poll at.</param> /// <param name="createWebClient">An optional function to create a WebClient instance, for overriding timeouts, request headers etc.</param> /// <returns>An observable containing the response headers and content of the specified url, or details of any exceptions that occurred.</returns> /// <exception cref="ArgumentNullException"><paramref name="url" /> or <paramref name="frequency" /> are <c>null</c>.</exception> public static IObservable<ResponseDetails> PollURL(string url, TimeSpan frequency, Func<WebClient> createWebClient = null) { createWebClient = createWebClient ?? (() => new WebClient()); Func<ResponseDetails> download = () => { try { var wc = createWebClient(); return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders }; } catch (WebException ex) { return new ResponseDetails { Exception = ex }; } }; return Observable.Interval(frequency) .Select(l => download()) .StartWith(download()) .DistinctUntilChanged(wc => wc.Text).Publish().RefCount(); } } }
using System; using System.Net; using System.Reactive.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains static methods useful for polling a REST/HTTP server's resources. /// </summary> public static class HttpPoller { /// <summary> /// Contains the response headers and plain text content from a web request. /// </summary> public struct ResponseDetails { public WebHeaderCollection Headers; public string Text; } /// <summary> /// Poll a <paramref name="url"/> at the specified <paramref name="frequency"/> and create an observable that will update every time the content recieved changes. /// </summary> /// <param name="url">The url to poll.</param> /// <param name="frequency">The frequency to poll at.</param> /// <param name="createWebClient">An optional function to create a WebClient instance, for overriding timeouts, request headers etc.</param> /// <returns>An observable containing the response headers and content of the specified url.</returns> /// <exception cref="ArgumentNullException"><paramref name="url" /> or <paramref name="frequency" /> are <c>null</c>.</exception> /// <exception cref="WebException">A problem occurs polling the specified <paramref name="url"/>.</exception> public static IObservable<ResponseDetails> PollURL(string url, TimeSpan frequency, Func<WebClient> createWebClient = null) { createWebClient = createWebClient ?? (() => new WebClient()); Func<ResponseDetails> download = () => { var wc = createWebClient(); return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders }; }; return Observable.Interval(frequency) .Select(l => download()) .StartWith(download()) .DistinctUntilChanged(wc => wc.Text).Publish().RefCount(); } } }
apache-2.0
C#
624c4c7bd50fe0edb2c063aa766aebc600846c1a
Fix for missing toolsVersion
pvcbuild/pvc-msbuild
src/PvcMSBuild.cs
src/PvcMSBuild.cs
using Microsoft.Build.Evaluation; using Microsoft.Build.Utilities; using PvcCore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; namespace PvcPlugins { public class PvcMSBuild : PvcPlugin { private readonly string buildTarget = null; private readonly string configurationName = null; private readonly bool enableParallelism = false; private readonly string toolsVersion = null; public PvcMSBuild( string buildTarget = "Build", string configurationName = "Debug", bool enableParallelism = false, string toolsVersion = "12.0") { this.buildTarget = buildTarget; this.configurationName = configurationName; this.enableParallelism = enableParallelism; this.toolsVersion = toolsVersion; } public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams) { var projectSolutionStreams = inputStreams.Where(x => Regex.IsMatch(x.StreamName, @"\.(.*proj|sln)$")); var msBuildPath = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", this.toolsVersion, DotNetFrameworkArchitecture.Current); foreach (var projectSolutionStream in projectSolutionStreams) { var workingDirectory = Path.GetDirectoryName(projectSolutionStream.StreamName); var args = new [] { "/target:" + this.buildTarget, "/property:Configuration=" + this.configurationName, "/verbosity:minimal", this.enableParallelism ? "" : "/m" }; var resultStreams = PvcUtil.StreamProcessExecution(msBuildPath, workingDirectory, args); // TODO - Implement plugin artifact generation to make this information available for logging in other plugins // blocking read until end new StreamReader(resultStreams.Item1).ReadToEnd(); } return inputStreams.Except(projectSolutionStreams); } } }
using Microsoft.Build.Evaluation; using Microsoft.Build.Utilities; using PvcCore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; namespace PvcPlugins { public class PvcMSBuild : PvcPlugin { private readonly string buildTarget = null; private readonly string configurationName = null; private readonly bool enableParallelism = false; private readonly string toolsVersion = null; public PvcMSBuild( string buildTarget = "Build", string configurationName = "Debug", bool enableParallelism = false, string toolsVersion = "12.0") { this.buildTarget = buildTarget; this.configurationName = configurationName; this.enableParallelism = enableParallelism; } public override IEnumerable<PvcStream> Execute(IEnumerable<PvcStream> inputStreams) { var projectSolutionStreams = inputStreams.Where(x => Regex.IsMatch(x.StreamName, @"\.(.*proj|sln)$")); var msBuildPath = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", this.toolsVersion, DotNetFrameworkArchitecture.Current); foreach (var projectSolutionStream in projectSolutionStreams) { var workingDirectory = Path.GetDirectoryName(projectSolutionStream.StreamName); var args = new [] { "/target:" + this.buildTarget, "/property:Configuration=" + this.configurationName, "/verbosity:minimal", this.enableParallelism ? "" : "/m" }; var resultStreams = PvcUtil.StreamProcessExecution(msBuildPath, workingDirectory, args); // TODO - Implement plugin artifact generation to make this information available for logging in other plugins // blocking read until end new StreamReader(resultStreams.Item1).ReadToEnd(); } return inputStreams.Except(projectSolutionStreams); } } }
mit
C#
b98f655eca1b80c9926b0ba11cb19708443a2ece
Add unit test for complex types.
alastairs/BobTheBuilder,fffej/BobTheBuilder
BobTheBuilder.Tests/BuildFacts.cs
BobTheBuilder.Tests/BuildFacts.cs
using System; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace BobTheBuilder.Tests { public class BuildFacts { [Fact] public void CreateADynamicInstanceOfTheRequestedType() { var sut = A.BuilderFor<SampleType>(); var result = sut.Build(); Assert.IsAssignableFrom<dynamic>(result); Assert.IsAssignableFrom<SampleType>(result); } [Theory, AutoData] public void SetStringStateByName(string expected) { var sut = A.BuilderFor<SampleType>(); sut.WithStringProperty(expected); SampleType result = sut.Build(); Assert.Equal(expected, result.StringProperty); } [Theory, AutoData] public void SetIntStateByName(int expected) { var sut = A.BuilderFor<SampleType>(); sut.WithIntProperty(expected); SampleType result = sut.Build(); Assert.Equal(expected, result.IntProperty); } [Theory, AutoData] public void SetComplexStateByName(Exception expected) { var sut = A.BuilderFor<SampleType>(); sut.WithComplexProperty(expected); SampleType result = sut.Build(); Assert.Equal(expected, result.ComplexProperty); } } }
using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace BobTheBuilder.Tests { public class BuildFacts { [Fact] public void CreateADynamicInstanceOfTheRequestedType() { var sut = A.BuilderFor<SampleType>(); var result = sut.Build(); Assert.IsAssignableFrom<dynamic>(result); Assert.IsAssignableFrom<SampleType>(result); } [Theory, AutoData] public void SetStringStateByName(string expected) { var sut = A.BuilderFor<SampleType>(); sut.WithStringProperty(expected); SampleType result = sut.Build(); Assert.Equal(expected, result.StringProperty); } [Theory, AutoData] public void SetIntStateByName(int expected) { var sut = A.BuilderFor<SampleType>(); sut.WithIntProperty(expected); SampleType result = sut.Build(); Assert.Equal(expected, result.IntProperty); } } }
apache-2.0
C#
c28adfcbf1e3b3cb1afa9a5b0940156f05c75a7b
Add additional script languages which use the arabic shaper
SixLabors/Fonts
src/SixLabors.Fonts/Tables/AdvancedTypographic/Shapers/ShaperFactory.cs
src/SixLabors.Fonts/Tables/AdvancedTypographic/Shapers/ShaperFactory.cs
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using SixLabors.Fonts.Unicode; namespace SixLabors.Fonts.Tables.AdvancedTypographic.Shapers { internal static class ShaperFactory { /// <summary> /// Creates a Shaper based on the given script language. /// </summary> /// <param name="script">The script language.</param> /// <returns>A shaper for the given script.</returns> public static BaseShaper Create(Script script) { switch (script) { case Script.Arabic: case Script.Mongolian: case Script.Syriac: case Script.Nko: case Script.PhagsPa: case Script.Mandaic: case Script.Manichaean: case Script.PsalterPahlavi: return new ArabicShaper(); default: return new DefaultShaper(); } } } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using SixLabors.Fonts.Unicode; namespace SixLabors.Fonts.Tables.AdvancedTypographic.Shapers { internal static class ShaperFactory { /// <summary> /// Creates a Shaper based on the given script language. /// </summary> /// <param name="script">The script language.</param> /// <returns>A shaper for the given script.</returns> public static BaseShaper Create(Script script) { switch (script) { case Script.Arabic: return new ArabicShaper(); default: return new DefaultShaper(); } } } }
apache-2.0
C#
019160398ae26aa3a48ffefb6ae03f8d2ed6bfb7
Fix a bug: When clean up disused images, the DefaultThumbnail.jpg could be removed by mistake if all books have their own images.
allenlooplee/Lbookshelf
Lbookshelf/ViewModels/SettingsFileSystemViewModel.cs
Lbookshelf/ViewModels/SettingsFileSystemViewModel.cs
using Lbookshelf.Business; using Microsoft.Expression.Interactivity.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using System.Configuration; using Lbookshelf.Utils; using Lbookshelf.Models; using Lapps.Utils; using Lapps.Utils.Collections; namespace Lbookshelf.ViewModels { public class SettingsFileSystemViewModel : ObservableObject { public SettingsFileSystemViewModel() { CleanCommand = new ActionCommand( () => { var used = BookManager.Instance.Books.Select(b => Path.Combine(Environment.CurrentDirectory, b.Thumbnail)); var cached = Directory .GetFiles(Path.Combine(Environment.CurrentDirectory, "Images")) .Where(p => Path.GetFileName(p) != "DefaultThumbnail.jpg"); var disused = cached.Except(used).ToArray(); if (disused.Length > 0) { disused.ForEach(p => File.Delete(p)); DialogService.ShowDialog(String.Format("{0} disused thumbnails were removed.", disused.Length)); } else { DialogService.ShowDialog("All thumbnails are in use."); } }); } public string RootDirectory { get { return StorageManager.Instance.RootDirectory; } set { StorageManager.Instance.RootDirectory = value; SettingManager.Default.RootDirectory = StorageManager.Instance.RootDirectory; SettingManager.Default.Save(); } } public ICommand CleanCommand { get; private set; } } }
using Lbookshelf.Business; using Microsoft.Expression.Interactivity.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using System.Configuration; using Lbookshelf.Utils; using Lbookshelf.Models; using Lapps.Utils; using Lapps.Utils.Collections; namespace Lbookshelf.ViewModels { public class SettingsFileSystemViewModel : ObservableObject { public SettingsFileSystemViewModel() { CleanCommand = new ActionCommand( () => { var used = BookManager.Instance.Books.Select(b => Path.Combine(Environment.CurrentDirectory, b.Thumbnail)); var cached = Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "Images")); var disused = cached.Except(used).ToArray(); if (disused.Length > 0) { disused.ForEach(p => File.Delete(p)); DialogService.ShowDialog(String.Format("{0} disused thumbnails were removed.", disused.Length)); } else { DialogService.ShowDialog("All thumbnails are in use."); } }); } public string RootDirectory { get { return StorageManager.Instance.RootDirectory; } set { StorageManager.Instance.RootDirectory = value; SettingManager.Default.RootDirectory = StorageManager.Instance.RootDirectory; SettingManager.Default.Save(); } } public ICommand CleanCommand { get; private set; } } }
mit
C#
80400ceb031a9e46004c46388cb64a65fadf6770
fix IgnoreFromJava attribute on ThreadPoolExecutor
dot42/api
Java/Util/Concurrent/ThreadPoolExecutor.cs
Java/Util/Concurrent/ThreadPoolExecutor.cs
// Copyright (C) 2014 dot42 // // Original filename: ThreadPoolExecutor.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 System; using Dot42; namespace Java.Util.Concurrent { [ApiEnhancementIgnoreMethods("Execute", "Remove")] partial class ThreadPoolExecutor { [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class AbortPolicy { } [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class CallerRunsPolicy { } [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class DiscardOldestPolicy { } [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class DiscardPolicy { } /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Ljava/lang/Runnable;)V", AccessFlags = 1, IgnoreFromJava = true)] public void Execute(Action action) /* MethodBuilder.Create */ { } } }
// Copyright (C) 2014 dot42 // // Original filename: ThreadPoolExecutor.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 System; using Dot42; namespace Java.Util.Concurrent { [ApiEnhancementIgnoreMethods("Execute", "Remove")] partial class ThreadPoolExecutor { [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class AbortPolicy { } [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class CallerRunsPolicy { } [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class DiscardOldestPolicy { } [ApiEnhancementIgnoreMethods("RejectedExecution")] partial class DiscardPolicy { } /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Ljava/lang/Runnable;)V", AccessFlags = 1)] public void Execute(Action action) /* MethodBuilder.Create */ { } } }
apache-2.0
C#
85a6a284623bd69fe161ced83d9b402eb6afa0ce
return value of ToConsole() method
xappido/ConsoleUtils.Net
ConsoleUtils.Net/OutputExtensions.cs
ConsoleUtils.Net/OutputExtensions.cs
using System; namespace ConsoleUtils.Net { public static class OutputExtensions { public static string ToConsole(this string output, ConsoleColor color = ConsoleColor.Gray, bool asLine = true) { var prevColor = Console.ForegroundColor; Console.ForegroundColor = color; if (asLine) { Console.WriteLine(output); } else { Console.Write(output); } Console.ForegroundColor = prevColor; return output; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleUtils.Net { public static class OutputExtensions { public static void ToConsole(this string output, ConsoleColor color = ConsoleColor.Gray, bool asLine = true) { var prevColor = Console.ForegroundColor; Console.ForegroundColor = color; if (asLine) { Console.WriteLine(output); } else { Console.Write(output); } Console.ForegroundColor = prevColor; } } }
mit
C#
94fad1b9bf7257a7de75ceb3b53515327a0bbb5c
Update StructuredLoggerCheckerUtil.cs
bartdesmet/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,dotnet/roslyn,dotnet/roslyn,dotnet/roslyn
src/Tools/BuildBoss/StructuredLoggerCheckerUtil.cs
src/Tools/BuildBoss/StructuredLoggerCheckerUtil.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. #nullable disable using System; using System.IO; using System.Linq; using Microsoft.Build.Logging.StructuredLogger; namespace BuildBoss { /// <summary> /// This type invokes the analyzer here: /// /// https://github.com/KirillOsenkov/MSBuildStructuredLog/blob/master/src/StructuredLogger/Analyzers/DoubleWritesAnalyzer.cs /// /// </summary> internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil { private readonly string _logFilePath; internal StructuredLoggerCheckerUtil(string logFilePath) { _logFilePath = logFilePath; } public bool Check(TextWriter textWriter) { try { var build = Serialization.Read(_logFilePath); var doubleWrites = DoubleWritesAnalyzer.GetDoubleWrites(build).ToArray(); if (doubleWrites.Any()) { foreach (var doubleWrite in doubleWrites) { // Issue https://github.com/dotnet/roslyn/issues/62372 if (Path.GetFileName(doubleWrite.Key) == "Microsoft.VisualStudio.Text.Internal.dll") { continue; } textWriter.WriteLine($"Multiple writes to {doubleWrite.Key}"); foreach (var source in doubleWrite.Value) { textWriter.WriteLine($"\t{source}"); } textWriter.WriteLine(); } return false; } return true; } catch (Exception ex) { textWriter.WriteLine($"Error processing binary log file: {ex.Message}"); return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using Microsoft.Build.Logging.StructuredLogger; namespace BuildBoss { /// <summary> /// This type invokes the analyzer here: /// /// https://github.com/KirillOsenkov/MSBuildStructuredLog/blob/master/src/StructuredLogger/Analyzers/DoubleWritesAnalyzer.cs /// /// </summary> internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil { private readonly string _logFilePath; internal StructuredLoggerCheckerUtil(string logFilePath) { _logFilePath = logFilePath; } public bool Check(TextWriter textWriter) { try { var build = Serialization.Read(_logFilePath); var doubleWrites = DoubleWritesAnalyzer.GetDoubleWrites(build).ToArray(); if (doubleWrites.Any()) { foreach (var doubleWrite in doubleWrites) { textWriter.WriteLine($"Multiple writes to {doubleWrite.Key}"); foreach (var source in doubleWrite.Value) { textWriter.WriteLine($"\t{source}"); } textWriter.WriteLine(); } return false; } return true; } catch (Exception ex) { textWriter.WriteLine($"Error processing binary log file: {ex.Message}"); return false; } } } }
mit
C#
dc14cc14cf7b37097785a327fb24603e332b7dd9
Create server side API for single multiple answer question
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
mit
C#
6e21c36ef373b14f7bd882f5de78861aa1ee4f7c
Update server side API for single multiple answer question
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } }
mit
C#
037f58920736d2133b63d205284da1dc418ebe18
remove the gateway from the building
YangEricLiu/Pop,YangEricLiu/Pop
src/BL/API/DataContract/BuildingDto.cs
src/BL/API/DataContract/BuildingDto.cs
using System; using System.Runtime.Serialization; namespace SE.DSP.Pop.BL.API.DataContract { [DataContract] public class BuildingDto { [DataMember] public long? HierarchyId { get; set; } [DataMember] public string Name { get; set; } [DataMember] public long IndustryId { get; set; } [DataMember] public decimal BuildingArea { get; set; } [DataMember] public DateTime FinishingDate { get; set; } [DataMember] public LogoDto Logo { get; set; } [DataMember] public BuildingLocationDto Location { get; set; } [DataMember] public HierarchyAdministratorDto[] Administrators { get; set; } } }
using System; using System.Runtime.Serialization; namespace SE.DSP.Pop.BL.API.DataContract { [DataContract] public class BuildingDto { [DataMember] public long? HierarchyId { get; set; } [DataMember] public string Name { get; set; } [DataMember] public long IndustryId { get; set; } [DataMember] public decimal BuildingArea { get; set; } [DataMember] public DateTime FinishingDate { get; set; } [DataMember] public LogoDto Logo { get; set; } [DataMember] public BuildingLocationDto Location { get; set; } [DataMember] public HierarchyAdministratorDto[] Administrators { get; set; } [DataMember] public GatewayDto[] Gateways { get; set; } } }
apache-2.0
C#
0c66b50fb3e2907d99443266863be44ce4e56c1e
fix IsSerializable in DN
MehdyKarimpour/extensions,AlejandroCano/extensions,signumsoftware/framework,signumsoftware/framework,MehdyKarimpour/extensions,AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/extensions
Signum.Entities.Extensions/Basics/PropertyRouteDN.cs
Signum.Entities.Extensions/Basics/PropertyRouteDN.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Utilities; using System.Reflection; using System.Linq.Expressions; namespace Signum.Entities.Basics { [Serializable, EntityKind(EntityKind.SystemString, EntityData.Master)] public class PropertyRouteDN : IdentifiableEntity { public PropertyRouteDN() { } [field: Ignore] PropertyRoute route; public PropertyRoute Route { get { return route; } set { route = value; } } [NotNullable, SqlDbType(Size = 100)] string path; [StringLengthValidator(AllowNulls = false, Min = 1, Max = 100)] public string Path { get { return path; } set { SetToStr(ref path, value, () => Path); } } TypeDN type; [NotNullValidator] public TypeDN Type { get { return type; } set { Set(ref type, value, () => Type); } } static readonly Expression<Func<PropertyRouteDN, string>> ToStringExpression = e => e.path; public override string ToString() { return ToStringExpression.Evaluate(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Utilities; using System.Reflection; using System.Linq.Expressions; namespace Signum.Entities.Basics { [EntityKind(EntityKind.SystemString, EntityData.Master)] public class PropertyRouteDN : IdentifiableEntity { public PropertyRouteDN() { } [field: Ignore] PropertyRoute route; public PropertyRoute Route { get { return route; } set { route = value; } } [NotNullable, SqlDbType(Size = 100)] string path; [StringLengthValidator(AllowNulls = false, Min = 1, Max = 100)] public string Path { get { return path; } set { SetToStr(ref path, value, () => Path); } } TypeDN type; [NotNullValidator] public TypeDN Type { get { return type; } set { Set(ref type, value, () => Type); } } static readonly Expression<Func<PropertyRouteDN, string>> ToStringExpression = e => e.path; public override string ToString() { return ToStringExpression.Evaluate(this); } } }
mit
C#
eb91c9ca1de192be6e3df3661238c49266c56a67
更新Demo,避免在某些特殊情况下MessageHandler日志记录过程异常
JeffreySu/WxOpen,JeffreySu/WxOpen
src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/MessageHandlers/WxOpenMessageHandler.Message.cs
src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/MessageHandlers/WxOpenMessageHandler.Message.cs
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2018 Senparc 文件名:MessageHandler.Event.cs 文件功能描述:微信请求的集中处理方法:Message相关 创建标识:Senparc - 20170106 ----------------------------------------------------------------*/ using Senparc.CO2NET.Extensions; using Senparc.CO2NET.Trace; using Senparc.NeuChar.Entities; using Senparc.Weixin.WxOpen.Entities; namespace Senparc.Weixin.WxOpen.MessageHandlers { public abstract partial class WxOpenMessageHandler<TC> { #region 接收消息方法 /// <summary> /// 默认返回消息(当任何OnXX消息没有被重写,都将自动返回此默认消息) /// </summary> public abstract IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage); //{ // 例如可以这样实现: // var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); // responseMessage.Content = "您发送的消息类型暂未被识别。"; // return responseMessage; //} /// <summary> /// 文字类型请求 /// </summary> public virtual IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { return DefaultResponseMessage(requestMessage); } /// <summary> /// 图片类型请求 /// </summary> public virtual IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage) { return DefaultResponseMessage(requestMessage); } #endregion } }
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2018 Senparc 文件名:MessageHandler.Event.cs 文件功能描述:微信请求的集中处理方法:Message相关 创建标识:Senparc - 20170106 ----------------------------------------------------------------*/ using Senparc.NeuChar.Entities; using Senparc.Weixin.WxOpen.Entities; namespace Senparc.Weixin.WxOpen.MessageHandlers { public abstract partial class WxOpenMessageHandler<TC> { #region 接收消息方法 /// <summary> /// 默认返回消息(当任何OnXX消息没有被重写,都将自动返回此默认消息) /// </summary> public abstract IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage); //{ // 例如可以这样实现: // var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); // responseMessage.Content = "您发送的消息类型暂未被识别。"; // return responseMessage; //} /// <summary> /// 文字类型请求 /// </summary> public virtual IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { return DefaultResponseMessage(requestMessage); } /// <summary> /// 图片类型请求 /// </summary> public virtual IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage) { return DefaultResponseMessage(requestMessage); } #endregion } }
apache-2.0
C#
dca96e519b975162bec46762864676401465ea21
Allow bind interface to be customized.
Silvenga/MailTrace,Silvenga/MailTrace,Silvenga/MailTrace
src/MailTrace.Host.Selfhost/Program.cs
src/MailTrace.Host.Selfhost/Program.cs
namespace MailTrace.Host.Selfhost { using System; using System.Linq; using MailTrace.Data.Postgresql; using MailTrace.Host.Data; using Microsoft.Owin.Hosting; internal static class Program { private static void Main(string[] args) { var baseAddress = args.FirstOrDefault() ?? "http://localhost:9900"; Startup.PostConfigureKernel += kernel => { kernel.Bind<TraceContext>().To<PostgresqlTraceContext>(); }; Console.WriteLine("Running Migration..."); var context = new PostgresqlTraceContext(); context.Migrate(); using (WebApp.Start<Startup>(baseAddress)) { Console.WriteLine("Ready."); Console.ReadLine(); } } } }
namespace MailTrace.Host.Selfhost { using System; using MailTrace.Data.Postgresql; using MailTrace.Host; using MailTrace.Host.Data; using Microsoft.Owin.Hosting; internal static class Program { private static void Main(string[] args) { const string baseAddress = "http://localhost:9900/"; Startup.PostConfigureKernel += kernel => { kernel.Bind<TraceContext>().To<PostgresqlTraceContext>(); }; Console.WriteLine("Running Migration..."); var context = new PostgresqlTraceContext(); context.Migrate(); using (WebApp.Start<Startup>(baseAddress)) { Console.WriteLine("Ready."); Console.ReadLine(); } } } }
mit
C#
e04c7c5b91f39221bbf8c11f31e984ef2a9a50d3
Bump Spatialite too, 1.0.1
Smartrak/TileSharp,Smartrak/TileSharp
TileSharp.Data.Spatialite/Properties/AssemblyInfo.cs
TileSharp.Data.Spatialite/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("TileSharp.Data.Spatialite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TileSharp.Data.Spatialite")] [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("68c788fe-dd23-499b-bdd2-4281c29dbb01")] // 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.0")] [assembly: AssemblyFileVersion("1.0.1.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("TileSharp.Data.Spatialite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TileSharp.Data.Spatialite")] [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("68c788fe-dd23-499b-bdd2-4281c29dbb01")] // 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")]
bsd-2-clause
C#
a1156a328e5346fb8b0a63a1b3e9808de33f3009
undo inappropriate recapitalization by sergey
smoothdeveloper/SimpleScene,RealRui/SimpleScene,jeske/SimpleScene
SimpleScene/Cameras/SSCameraThirdPerson.cs
SimpleScene/Cameras/SSCameraThirdPerson.cs
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using OpenTK; namespace SimpleScene { public class SSCameraThirdPerson : SSCamera { public SSObject FollowTarget; public float followDistance = 10.0f; public float minFollowDistance = 0.5f; public float maxFollowDistance = 500.0f; public Vector3 basePos; public SSCameraThirdPerson (SSObject followTarget) : base() { this.FollowTarget = followTarget; } public SSCameraThirdPerson() : base() { } public SSCameraThirdPerson (Vector3 origin) : base() { this.basePos = origin; } public override void Update(float fElapsedMS) { Vector3 targetPos = basePos; // FPS follow the target if (this.FollowTarget != null) { targetPos = this.FollowTarget.Pos; } followDistance = OpenTKHelper.Clamp(followDistance,minFollowDistance,maxFollowDistance); // one way to have a third person camera, is to position ourselves // relative to our target object, and our current camera-direction // TODO: why are positive follow distances producing the correct orientation? // it feels like something is inverted this.Pos = targetPos + (this.Dir * followDistance); // Console.WriteLine("Camera Up {0} / Dir {1} / Right {2}",this.Up,this.Dir,this.Right); // Console.WriteLine("Camera Pos = {0}",this.Pos); base.Update(fElapsedMS); } } }
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using OpenTK; namespace SimpleScene { public class SSCameraThirdPerson : SSCamera { public SSObject FollowTarget; public float FollowDistance = 10.0f; public float minFollowDistance = 0.5f; public float maxFollowDistance = 500.0f; public Vector3 BasePos; public SSCameraThirdPerson (SSObject followTarget) : base() { this.FollowTarget = followTarget; } public SSCameraThirdPerson() : base() { } public SSCameraThirdPerson (Vector3 origin) : base() { this.BasePos = origin; } public override void Update(float fElapsedMS) { Vector3 targetPos = BasePos; // FPS follow the target if (this.FollowTarget != null) { targetPos = this.FollowTarget.Pos; } FollowDistance = OpenTKHelper.Clamp(FollowDistance,minFollowDistance,maxFollowDistance); // one way to have a third person camera, is to position ourselves // relative to our target object, and our current camera-direction // TODO: why are positive follow distances producing the correct orientation? // it feels like something is inverted this.Pos = targetPos + (this.Dir * FollowDistance); // Console.WriteLine("Camera Up {0} / Dir {1} / Right {2}",this.Up,this.Dir,this.Right); // Console.WriteLine("Camera Pos = {0}",this.Pos); base.Update(fElapsedMS); } } }
apache-2.0
C#
f9e2de33fbe54fc639c2de8017183b689c4bd665
update email type enum to allow for flags
bolorundurowb/vCardLib
vCardLib/Enums/EmailType.cs
vCardLib/Enums/EmailType.cs
using System; namespace vCardLib.Enums { /// <summary> /// Various email address types in a vCard /// </summary> [Flags] public enum EmailType { None = 0, Work = 1, Internet = 2, Home = 4, AOL = 8, Applelink = 16, IBMMail = 32 } }
namespace vCardLib.Enums { /// <summary> /// Various email address types in a vCard /// </summary> public enum EmailType { Work, Internet, Home, AOL, Applelink, IBMMail, None } }
mit
C#
caa19029e36262f61bb9bdc6d4403b2b1815937d
remove moq
guitarrapc/AWSLambdaCSharpIntroduction
AWSLambdaCSharpIntroduction/SlackSlashCommandWebhook/SlackSlashCommandWebhook.Tests/FunctionTest.cs
AWSLambdaCSharpIntroduction/SlackSlashCommandWebhook/SlackSlashCommandWebhook.Tests/FunctionTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Newtonsoft.Json; using SlackSlashCommandWebhook; namespace SlackSlashCommandWebhook.Tests { public class FunctionTest { [Fact] public void SlashCommandTest() { // Invoke the lambda function and confirm the string was upper cased. var function = new Function(); var context = new TestLambdaContext(); var input = @"{ ""body"": ""token=XXXXXXXXXXXXXXXXXXXXXX&team_id=1234&team_domain=hogemoge&channel_id=1234&channel_name=hogemoge&user_id=hogemoge&user_name=hogemoge&command=%2Fnow&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2123%2F456%2F789"" }"; var command = JsonConvert.DeserializeObject<SlackSlashCommand>(input); var response = function.FunctionHandlerAsync(command, context).Result; Assert.Equal("in_channel", response.ResponseType); Assert.Equal("Hello from Lambda .NET Core.", response.Text); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Moq; using Newtonsoft.Json; using SlackSlashCommandWebhook; namespace SlackSlashCommandWebhook.Tests { public class FunctionTest { [Fact] public void SlashCommandTest() { // Invoke the lambda function and confirm the string was upper cased. var function = new Function(); var context = new TestLambdaContext(); var input = @"{ ""body"": ""token=XXXXXXXXXXXXXXXXXXXXXX&team_id=1234&team_domain=hogemoge&channel_id=1234&channel_name=hogemoge&user_id=hogemoge&user_name=hogemoge&command=%2Fnow&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2123%2F456%2F789"" }"; var command = JsonConvert.DeserializeObject<SlackSlashCommand>(input); var response = function.FunctionHandlerAsync(command, context).Result; Assert.Equal("in_channel", response.ResponseType); Assert.Equal("Hello from Lambda .NET Core.", response.Text); } } }
mit
C#
34d62183c36870965d89b13d9640b58eb3a51d65
Fix autoAck when BasicGet throws exception
EasyNetQ/EasyNetQ,micdenny/EasyNetQ
Source/EasyNetQ.Hosepipe/QueueRetrieval.cs
Source/EasyNetQ.Hosepipe/QueueRetrieval.cs
using System; using System.Collections.Generic; using EasyNetQ.Consumer; using RabbitMQ.Client; using RabbitMQ.Client.Exceptions; namespace EasyNetQ.Hosepipe; public interface IQueueRetrieval { IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters); } public class QueueRetrieval : IQueueRetrieval { private readonly IErrorMessageSerializer errorMessageSerializer; public QueueRetrieval(IErrorMessageSerializer errorMessageSerializer) { this.errorMessageSerializer = errorMessageSerializer; } public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters) { using var connection = HosepipeConnection.FromParameters(parameters); using var channel = connection.CreateModel(); try { channel.QueueDeclarePassive(parameters.QueueName); } catch (OperationInterruptedException exception) { Console.WriteLine(exception.Message); yield break; } var count = 0; while (count++ < parameters.NumberOfMessagesToRetrieve) { BasicGetResult basicGetResult; try { basicGetResult = channel.BasicGet(parameters.QueueName, false); if (basicGetResult == null) break; // no more messages on the queue if (parameters.Purge) { channel.BasicAck(basicGetResult.DeliveryTag, false); } } catch (Exception exception) { Console.WriteLine(exception.Message); throw; } var properties = new MessageProperties(); properties.CopyFrom(basicGetResult.BasicProperties); var info = new MessageReceivedInfo( "hosepipe", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, parameters.QueueName ); yield return new HosepipeMessage(errorMessageSerializer.Serialize(basicGetResult.Body.ToArray()), properties, info); } } }
using System; using System.Collections.Generic; using EasyNetQ.Consumer; using RabbitMQ.Client.Exceptions; namespace EasyNetQ.Hosepipe; public interface IQueueRetrieval { IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters); } public class QueueRetrieval : IQueueRetrieval { private readonly IErrorMessageSerializer errorMessageSerializer; public QueueRetrieval(IErrorMessageSerializer errorMessageSerializer) { this.errorMessageSerializer = errorMessageSerializer; } public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters) { using var connection = HosepipeConnection.FromParameters(parameters); using var channel = connection.CreateModel(); try { channel.QueueDeclarePassive(parameters.QueueName); } catch (OperationInterruptedException exception) { Console.WriteLine(exception.Message); yield break; } var count = 0; while (count++ < parameters.NumberOfMessagesToRetrieve) { var basicGetResult = channel.BasicGet(parameters.QueueName, parameters.Purge); if (basicGetResult == null) break; // no more messages on the queue var properties = new MessageProperties(); properties.CopyFrom(basicGetResult.BasicProperties); var info = new MessageReceivedInfo( "hosepipe", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, parameters.QueueName ); yield return new HosepipeMessage(errorMessageSerializer.Serialize(basicGetResult.Body.ToArray()), properties, info); } } }
mit
C#
5f144409951a29f9df8bd1f3a8373d39d8135b06
Increase dll version
GAnatoliy/ViewModelLoader
ViewModelLoader/Properties/AssemblyInfo.cs
ViewModelLoader/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("ViewModelLoader")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ViewModelLoader")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("26173ffd-2a06-4dee-941d-fd3164cf4054")] // 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")]
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("ViewModelLoader")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ViewModelLoader")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("26173ffd-2a06-4dee-941d-fd3164cf4054")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
4307704e6d8f6b4c8a781a936cd2725e148a7954
Switch to auto assembly numbering
amweiss/vigilant-cupcake
VigilantCupcake/Properties/AssemblyInfo.cs
VigilantCupcake/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Resources; 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("VigilantCupcake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("VigilantCupcake")] [assembly: AssemblyProduct("VigilantCupcake")] [assembly: AssemblyCopyright("Copyright © VigilantCupcake 2015")] [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("354605ff-ffd4-4825-81e6-a9781e1a0368")] // 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: NeutralResourcesLanguageAttribute("en-US")]
using System; using System.Reflection; using System.Resources; 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("VigilantCupcake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("VigilantCupcake")] [assembly: AssemblyProduct("VigilantCupcake")] [assembly: AssemblyCopyright("Copyright © VigilantCupcake 2015")] [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("354605ff-ffd4-4825-81e6-a9781e1a0368")] // 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.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
mit
C#
776ffbcbdcb6eaa8e32f989a7527bc8a201362dc
Add documentation for alpha format.
SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,jkoritzinsky/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia
src/Avalonia.Visuals/Platform/AlphaFormat.cs
src/Avalonia.Visuals/Platform/AlphaFormat.cs
namespace Avalonia.Platform { /// <summary> /// Describes how to interpret the alpha component of a pixel. /// </summary> public enum AlphaFormat { /// <summary> /// All pixels have their alpha premultiplied in their color components. /// </summary> Premul, /// <summary> /// All pixels have their color components stored without any regard to the alpha. e.g. this is the default configuration for PNG images. /// </summary> Unpremul, /// <summary> /// All pixels are stored as opaque. /// </summary> Opaque } }
namespace Avalonia.Platform { public enum AlphaFormat { Premul, Unpremul, Opaque } }
mit
C#
2e73af68a2ce966882c8247cd3629520e0e29684
Update Startup.Auth.Salesforce.cs
wadewegner/Salesforce.Owin.Security.Provider,wadewegner/Salesforce.Owin.Security.Provider,wadewegner/Salesforce.Owin.Security.Provider
src/Web/App_Start/Startup.Auth.Salesforce.cs
src/Web/App_Start/Startup.Auth.Salesforce.cs
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Web; using Owin; using Salesforce.Owin.Security.Provider; namespace Web { public partial class Startup { public void ConfigureSalesforce(IAppBuilder app) { app.UseSalesforceAuthentication(new SalesforceAuthenticationOptions() { Endpoints = new SalesforceAuthenticationOptions. SalesforceAuthenticationEndpoints { AuthorizationEndpoint = "https://login.salesforce.com/services/oauth2/authorize", TokenEndpoint = "https://login.salesforce.com/services/oauth2/token", }, ClientId = "YOUR_CLIENT_ID", ClientSecret = "YOUR_CLIENT_SECRET", Provider = new SalesforceAuthenticationProvider() { // TODO: 1. Add this to temporarily store the access token OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("urn:tokens:salesforce:accesstoken", context.AccessToken)); context.Identity.AddClaim(new Claim("urn:tokens:salesforce:refreshtoken", context.RefreshToken)); } } }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Web; using Owin; using Salesforce.Owin.Security.Provider; namespace Web { public partial class Startup { public void ConfigureSalesforce(IAppBuilder app) { app.UseSalesforceAuthentication(new SalesforceAuthenticationOptions() { Endpoints = new SalesforceAuthenticationOptions. SalesforceAuthenticationEndpoints { AuthorizationEndpoint = "https://login.salesforce.com/services/oauth2/authorize", TokenEndpoint = "https://login.salesforce.com/services/oauth2/token", }, ClientId = "3MVG9JZ_r.QzrS7izXVWrETc3vyjzE2_4D8cVFZMzoNiravzQUQAasuoDynfkqc5yJvlfE7shOtkQm4FeZJjg", ClientSecret = "7476749690614642061", Provider = new SalesforceAuthenticationProvider() { // TODO: 1. Add this to temporarily store the access token OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("urn:tokens:salesforce:accesstoken", context.AccessToken)); context.Identity.AddClaim(new Claim("urn:tokens:salesforce:refreshtoken", context.RefreshToken)); } } }); } } }
apache-2.0
C#
9e33face791c92f4281f5bd74a6f1735aa6b08d0
Add test for authorization requirement in TraktUserCustomListItemsRemoveRequest
henrikfroehling/TraktApiSharp
Source/Tests/TraktApiSharp.Tests/Experimental/Requests/Users/OAuth/TraktUserCustomListItemsRemoveRequestTests.cs
Source/Tests/TraktApiSharp.Tests/Experimental/Requests/Users/OAuth/TraktUserCustomListItemsRemoveRequestTests.cs
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Users.OAuth; using TraktApiSharp.Objects.Post.Users.CustomListItems; using TraktApiSharp.Objects.Post.Users.CustomListItems.Responses; using TraktApiSharp.Requests; [TestClass] public class TraktUserCustomListItemsRemoveRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListItemsRemoveRequestIsNotAbstract() { typeof(TraktUserCustomListItemsRemoveRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListItemsRemoveRequestIsSealed() { typeof(TraktUserCustomListItemsRemoveRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListItemsRemoveRequestIsSubclassOfATraktUsersPostByIdRequest() { typeof(TraktUserCustomListItemsRemoveRequest).IsSubclassOf(typeof(ATraktUsersPostByIdRequest<TraktUserCustomListItemsRemovePostResponse, TraktUserCustomListItemsPost>)).Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListItemsRemoveRequestHasAuthorizationRequired() { var request = new TraktUserCustomListItemsRemoveRequest(null); request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required); } } }
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Users.OAuth; using TraktApiSharp.Objects.Post.Users.CustomListItems; using TraktApiSharp.Objects.Post.Users.CustomListItems.Responses; [TestClass] public class TraktUserCustomListItemsRemoveRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListItemsRemoveRequestIsNotAbstract() { typeof(TraktUserCustomListItemsRemoveRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListItemsRemoveRequestIsSealed() { typeof(TraktUserCustomListItemsRemoveRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Users")] public void TestTraktUserCustomListItemsRemoveRequestIsSubclassOfATraktUsersPostByIdRequest() { typeof(TraktUserCustomListItemsRemoveRequest).IsSubclassOf(typeof(ATraktUsersPostByIdRequest<TraktUserCustomListItemsRemovePostResponse, TraktUserCustomListItemsPost>)).Should().BeTrue(); } } }
mit
C#
cb23202a308041d4f0dcdf95bc466ab548c695c6
Revert "Change controller action to debug Kudu issue .."
ShamsulAmry/Malaysia-GST-Checker
Amry.Gst.Web/Controllers/HomeController.cs
Amry.Gst.Web/Controllers/HomeController.cs
using System.Web.Mvc; using Amry.Gst.Properties; using WebMarkupMin.Mvc.ActionFilters; namespace Amry.Gst.Web.Controllers { public class HomeController : Controller { const int OneWeek = 604800; const int OneYear = 31536000; [Route, MinifyHtml, OutputCache(Duration = OneWeek)] public ActionResult Index() { return View(); } [Route("about"), MinifyHtml, OutputCache(Duration = OneYear)] public ActionResult About() { return View(); } [Route("api"), MinifyHtml, OutputCache(Duration = OneYear)] public ActionResult Api() { return View(); } [Route("ver")] public ActionResult Version() { return Content(AssemblyInfoConstants.Version, "text/plain"); } } }
using System.Web.Mvc; using Amry.Gst.Properties; using WebMarkupMin.Mvc.ActionFilters; namespace Amry.Gst.Web.Controllers { public class HomeController : Controller { const int OneWeek = 604800; const int OneYear = 31536000; [Route, MinifyHtml, OutputCache(Duration = OneWeek)] public ActionResult Index() { return View(); } [Route("about"), MinifyHtml, OutputCache(Duration = OneYear)] public ActionResult About() { return View(); } [Route("api"), MinifyHtml, OutputCache(Duration = OneYear)] public ActionResult Api() { return View(); } [Route("ver")] public ActionResult Version() { return Content("Version: " + AssemblyInfoConstants.Version, "text/plain"); } } }
mit
C#
820ce9e8455feb15c8114457f82cf9fa9cf74461
Fix uploading files with uppercase extensions
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
Core/Handling/General/FileDialogHandler.cs
Core/Handling/General/FileDialogHandler.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using CefSharp; namespace TweetDuck.Core.Handling.General{ sealed class FileDialogHandler : IDialogHandler{ public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback){ CefFileDialogMode dialogType = mode & CefFileDialogMode.TypeMask; if (dialogType == CefFileDialogMode.Open || dialogType == CefFileDialogMode.OpenMultiple){ string allFilters = string.Join(";", acceptFilters.Select(filter => "*"+filter)); using(OpenFileDialog dialog = new OpenFileDialog{ AutoUpgradeEnabled = true, DereferenceLinks = true, Multiselect = dialogType == CefFileDialogMode.OpenMultiple, Title = "Open Files", Filter = $"All Supported Formats ({allFilters})|{allFilters}|All Files (*.*)|*.*" }){ if (dialog.ShowDialog() == DialogResult.OK){ string ext = Path.GetExtension(dialog.FileName); callback.Continue(acceptFilters.FindIndex(filter => filter.Equals(ext, StringComparison.OrdinalIgnoreCase)), dialog.FileNames.ToList()); } else{ callback.Cancel(); } callback.Dispose(); } return true; } else{ callback.Dispose(); return false; } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using CefSharp; namespace TweetDuck.Core.Handling.General{ sealed class FileDialogHandler : IDialogHandler{ public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback){ CefFileDialogMode dialogType = mode & CefFileDialogMode.TypeMask; if (dialogType == CefFileDialogMode.Open || dialogType == CefFileDialogMode.OpenMultiple){ string allFilters = string.Join(";", acceptFilters.Select(filter => "*"+filter)); using(OpenFileDialog dialog = new OpenFileDialog{ AutoUpgradeEnabled = true, DereferenceLinks = true, Multiselect = dialogType == CefFileDialogMode.OpenMultiple, Title = "Open Files", Filter = $"All Supported Formats ({allFilters})|{allFilters}|All Files (*.*)|*.*" }){ if (dialog.ShowDialog() == DialogResult.OK){ callback.Continue(acceptFilters.FindIndex(filter => filter == Path.GetExtension(dialog.FileName)), dialog.FileNames.ToList()); } else{ callback.Cancel(); } callback.Dispose(); } return true; } else{ callback.Dispose(); return false; } } } }
mit
C#
5c1211df65d2662184743eb5306c81ef8af6bb81
Use 'container' instead of 'container-fluid'.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
MitternachtWeb/Views/Shared/_Layout.cshtml
MitternachtWeb/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] | MitternachtWeb</title> <link rel="stylesheet" href="~/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">MitternachtWeb</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> </li> @if(ViewBag.DiscordUser != null) { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="GuildList" asp-action="Index">Serverliste</a> </li> @if(ViewBag.DiscordUser.BotPagePermissions.HasFlag(BotLevelPermission.ReadBotConfig)) { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="BotConfig" asp-action="Index">BotConfig</a> </li> } <li class="nav-item"> <a class="nav-link text-dark" asp-area="Analysis" asp-controller="Analysis" asp-action="Index">Analysen</a> </li> } </ul> </div> <partial name="_NavbarLogin" /> </div> </nav> </header> <div class="container-fluid"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2020 - MitternachtWeb </div> </footer> <script src="~/js/jquery.min.js"></script> <script src="~/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @RenderSection("Scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] | MitternachtWeb</title> <link rel="stylesheet" href="~/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">MitternachtWeb</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> </li> @if(ViewBag.DiscordUser != null) { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="GuildList" asp-action="Index">Serverliste</a> </li> @if(ViewBag.DiscordUser.BotPagePermissions.HasFlag(BotLevelPermission.ReadBotConfig)) { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="BotConfig" asp-action="Index">BotConfig</a> </li> } <li class="nav-item"> <a class="nav-link text-dark" asp-area="Analysis" asp-controller="Analysis" asp-action="Index">Analysen</a> </li> } </ul> </div> <partial name="_NavbarLogin" /> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2020 - MitternachtWeb </div> </footer> <script src="~/js/jquery.min.js"></script> <script src="~/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @RenderSection("Scripts", required: false) </body> </html>
mit
C#
e1b1e2561de2abaa3c738a6d00777924778ae4a3
mark EmptyPosition as sealed
acple/ParsecSharp
ParsecSharp/Data/Internal/EmptyPosition.cs
ParsecSharp/Data/Internal/EmptyPosition.cs
namespace ParsecSharp.Internal { public sealed 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 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"; } }
mit
C#
13dc9f0a4c2f0ba14fecb6245ed36908fcccf032
Configure the FolderPicker
minidfx/BulkRename
Solution/App/Services/OpenFolderService.cs
Solution/App/Services/OpenFolderService.cs
using System; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Pickers; using App.Services.Contracts; namespace App.Services { public class OpenFolderService : IOpenFolderService { public async Task<StorageFolder> PromptAsync() { var folderPicker = new FolderPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.Desktop, FileTypeFilter = {"."} }; return await folderPicker.PickSingleFolderAsync(); } } }
using System; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Pickers; using App.Services.Contracts; namespace App.Services { public class OpenFolderService : IOpenFolderService { public async Task<StorageFolder> PromptAsync() { var folderPicker = new FolderPicker(); return await folderPicker.PickSingleFolderAsync(); } } }
mit
C#
1d2e5ed065a4cf5c40bcff35e2ff7e2c635c238e
Expand docs to match
KirillOsenkov/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,physhi/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,aelij/roslyn,eriawan/roslyn,physhi/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,dotnet/roslyn,tmat/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,mavasani/roslyn,wvdd007/roslyn,gafter/roslyn,brettfo/roslyn,weltkante/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,gafter/roslyn,panopticoncentral/roslyn,diryboy/roslyn,tmat/roslyn,mavasani/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,KirillOsenkov/roslyn,brettfo/roslyn,physhi/roslyn,AlekseyTs/roslyn,sharwell/roslyn,panopticoncentral/roslyn,weltkante/roslyn,brettfo/roslyn,tannergooding/roslyn,sharwell/roslyn,heejaechang/roslyn,diryboy/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,diryboy/roslyn,sharwell/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,tmat/roslyn,aelij/roslyn,eriawan/roslyn,heejaechang/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,aelij/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn
src/Features/LanguageServer/Protocol/Handler/ExportLspMethodAttribute.cs
src/Features/LanguageServer/Protocol/Handler/ExportLspMethodAttribute.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. #nullable enable using System; using System.Composition; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Defines an attribute for LSP request handlers to map to LSP methods. /// </summary> [AttributeUsage(AttributeTargets.Class), MetadataAttribute] internal class ExportLspMethodAttribute : ExportAttribute, IRequestHandlerMetadata { public string MethodName { get; } public string? LanguageName { get; } /// <summary> /// Whether or not handling this method results in changes to the current solution state. /// Mutating requests will block all subsequent requests from starting until after they have /// completed and mutations have been applied. See <see cref="RequestExecutionQueue"/>. /// </summary> public bool MutatesSolutionState { get; } public ExportLspMethodAttribute(string methodName, string? languageName = null, bool mutatesSolutionState = false) : base(typeof(IRequestHandler)) { if (string.IsNullOrEmpty(methodName)) { throw new ArgumentException(nameof(methodName)); } MethodName = methodName; LanguageName = languageName; MutatesSolutionState = mutatesSolutionState; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Composition; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Defines an attribute for LSP request handlers to map to LSP methods. /// </summary> [AttributeUsage(AttributeTargets.Class), MetadataAttribute] internal class ExportLspMethodAttribute : ExportAttribute, IRequestHandlerMetadata { public string MethodName { get; } public string? LanguageName { get; } /// <summary> /// Whether or not the specified request needs to mutate the solution. Mutating requests will block non-mutating requests from starting. /// </summary> public bool MutatesSolutionState { get; } public ExportLspMethodAttribute(string methodName, string? languageName = null, bool mutatesSolutionState = false) : base(typeof(IRequestHandler)) { if (string.IsNullOrEmpty(methodName)) { throw new ArgumentException(nameof(methodName)); } MethodName = methodName; LanguageName = languageName; MutatesSolutionState = mutatesSolutionState; } } }
mit
C#
38e27743c4e986ac47a037c2b1f6abf5852e27ae
fix syntax error, html title
mperdeck/jsnlog.SimpleWorkingDemoGenerator,mperdeck/jsnlog.SimpleWorkingDemoGenerator,mperdeck/jsnlog.SimpleWorkingDemoGenerator
TemplateFiles/Base/Views/Home/Index.cshtml
TemplateFiles/Base/Views/Home/Index.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>{{Project}}</title> @Html.Raw(JSNLog.JavascriptLogging.Configure()) </head> <body> <h1>{{Project}}</h1> <p> Log messages are sent to server the moment this page is opened. </p> <script type="text/ecmascript"> window.onerror = function (errorMsg, url, lineNumber, column, errorObj) { // Send object with all data to server side log, using severity fatal, // from logger "onerrorLogger" JL("onerrorLogger").fatalException({ "msg": "Exception!", "errorMsg": errorMsg, "url": url, "line number": lineNumber, "column": column }, errorObj); // Tell browser to run its own error handler as well return false; } // Log with every severity JL("jsLogger").trace("trace client log message"); JL("jsLogger").debug("debug client log message"); JL("jsLogger").info("info client log message"); JL("jsLogger").warn({ msg: 'warn client log message - logging object', x: 5, y: 88 }); JL("jsLogger").error(function() { return "error client log message - returned by function"; }); JL("jsLogger").fatal("fatal client log message"); // Log caught exception try { // ReferenceError: xyz is not defined xyz; } catch (e) { // Log the exception JL().fatalException("Something went wrong!", e); } // ReferenceError: xyz2 is not defined. Should be caught by onerror handler. xyz2; </script> <div> </div> </body> </html>
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>EmptySerilog</title> @Html.Raw(JSNLog.JavascriptLogging.Configure()) </head> <body> <h1>{{Project}}</h1> <p> Log messages are sent to server the moment this page is opened. </p> <script type="text/ecmascript"> window.onerror = function (errorMsg, url, lineNumber, column, errorObj) { // Send object with all data to server side log, using severity fatal, // from logger "onerrorLogger" JL("onerrorLogger").fatalException({ "msg": "Exception!", "errorMsg": errorMsg, "url": url, "line number": lineNumber, "column": column }, errorObj); // Tell browser to run its own error handler as well return false; } // Log with every severity JL("jsLogger").trace("trace client log message"); JL("jsLogger").debug("debug client log message"); JL("jsLogger").info("info client log message"); JL("jsLogger").warn({ msg: 'warn client log message - logging object', x: 5, y: 88 }); JL("jsLogger").error(function() { return "error client log message - returned by function"; }); JL("jsLogger").fatal("fatal client log message"); // Log caught exception try { ... // ReferenceError: xyz is not defined xyz; ... } catch (e) { // Log the exception JL().fatalException("Something went wrong!", e); } // ReferenceError: xyz2 is not defined. Should be caught by onerror handler. xyz2; </script> <div> </div> </body> </html>
mit
C#
b522d80c8f237e26b17735b4ec13ed1020f8ef0f
Update PowerShellModule.cs
tiksn/TIKSN-Framework
TIKSN.Core/PowerShell/PowerShellModule.cs
TIKSN.Core/PowerShell/PowerShellModule.cs
using Autofac; namespace TIKSN.PowerShell { public class PowerShellModule : Module { protected override void Load(ContainerBuilder builder) { base.Load(builder); _ = builder.RegisterType<CurrentCommandContext>().As<ICurrentCommandStore>().As<ICurrentCommandProvider>() .InstancePerLifetimeScope(); } } }
using Autofac; namespace TIKSN.PowerShell { public class PowerShellModule : Module { protected override void Load(ContainerBuilder builder) { base.Load(builder); builder.RegisterType<CurrentCommandContext>().As<ICurrentCommandStore>().As<ICurrentCommandProvider>() .InstancePerLifetimeScope(); } } }
mit
C#
512bbb471283fa63e98f33a6e22c0c77413e6cbb
bump version
GeertvanHorrik/MethodTimer,Fody/MethodTimer
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("MethodTimer")] [assembly: AssemblyProduct("MethodTimer")] [assembly: AssemblyVersion("1.15.8")] [assembly: AssemblyFileVersion("1.15.8")]
using System.Reflection; [assembly: AssemblyTitle("MethodTimer")] [assembly: AssemblyProduct("MethodTimer")] [assembly: AssemblyVersion("1.15.7")] [assembly: AssemblyFileVersion("1.15.7")]
mit
C#
e4633dbcf7ded8af8864055f5300c691eb22a0bb
Remove useless case clause
xavierfoucrier/gmail-notifier,xavierfoucrier/gmail-notifier
code/Program.cs
code/Program.cs
using System; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Windows.Forms; using notifier.Languages; using notifier.Properties; namespace notifier { static class Program { #region #attributes /// <summary> /// Mutex associated to the application instance /// </summary> static Mutex Mutex = new Mutex(true, "gmailnotifier-115e363ecbfefd771e55c6874680bc0a"); #endregion #region #methods [STAThread] static void Main(string[] args) { // initialize the configuration file with setup installer settings if (args.Length == 3 && args[0] == "install") { // language application setting switch (args[1]) { default: case "en": Settings.Default.Language = "English"; break; case "fr": Settings.Default.Language = "Français"; break; case "de": Settings.Default.Language = "Deutsch"; break; } // start with Windows setting Settings.Default.RunAtWindowsStartup = args[2] == "auto"; // commit changes to the configuration file Settings.Default.Save(); return; } // initialize the interface with the specified culture, depending on the user settings switch (Settings.Default.Language) { default: CultureInfo.CurrentUICulture = new CultureInfo("en-US"); break; case "Français": CultureInfo.CurrentUICulture = new CultureInfo("fr-FR"); break; case "Deutsch": CultureInfo.CurrentUICulture = new CultureInfo("de-DE"); break; } // check if there is an instance running if (!Mutex.WaitOne(TimeSpan.Zero, true)) { MessageBox.Show(Translation.mutexError, Translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // set some default properties Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // set the process priority to "low" Process process = Process.GetCurrentProcess(); process.PriorityClass = ProcessPriorityClass.BelowNormal; // run the main window Application.Run(new Main()); // release the mutex instance Mutex.ReleaseMutex(); } #endregion #region #accessors #endregion } }
using System; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Windows.Forms; using notifier.Languages; using notifier.Properties; namespace notifier { static class Program { #region #attributes /// <summary> /// Mutex associated to the application instance /// </summary> static Mutex Mutex = new Mutex(true, "gmailnotifier-115e363ecbfefd771e55c6874680bc0a"); #endregion #region #methods [STAThread] static void Main(string[] args) { // initialize the configuration file with setup installer settings if (args.Length == 3 && args[0] == "install") { // language application setting switch (args[1]) { default: case "en": Settings.Default.Language = "English"; break; case "fr": Settings.Default.Language = "Français"; break; case "de": Settings.Default.Language = "Deutsch"; break; } // start with Windows setting Settings.Default.RunAtWindowsStartup = args[2] == "auto"; // commit changes to the configuration file Settings.Default.Save(); return; } // initialize the interface with the specified culture, depending on the user settings switch (Settings.Default.Language) { default: case "English": CultureInfo.CurrentUICulture = new CultureInfo("en-US"); break; case "Français": CultureInfo.CurrentUICulture = new CultureInfo("fr-FR"); break; case "Deutsch": CultureInfo.CurrentUICulture = new CultureInfo("de-DE"); break; } // check if there is an instance running if (!Mutex.WaitOne(TimeSpan.Zero, true)) { MessageBox.Show(Translation.mutexError, Translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // set some default properties Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // set the process priority to "low" Process process = Process.GetCurrentProcess(); process.PriorityClass = ProcessPriorityClass.BelowNormal; // run the main window Application.Run(new Main()); // release the mutex instance Mutex.ReleaseMutex(); } #endregion #region #accessors #endregion } }
mit
C#
7f38dca1abe2a14c183f81b931cd63a550214865
Correct builder path - .Net Framework folder starts from "v"
AndreyZM/Bridge,AndreyZM/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge
Translator/Translator/Translator.Build.cs
Translator/Translator/Translator.Build.cs
using System; using System.Diagnostics; namespace Bridge.Translator { public partial class Translator { protected static readonly char ps = System.IO.Path.DirectorySeparatorChar; protected virtual string GetBuilderPath() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: return Environment.GetEnvironmentVariable("windir") + ps + "Microsoft.NET" + ps + "Framework" + ps + "v" + this.MSBuildVersion + ps + "msbuild"; default: throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform); } } protected virtual string GetBuilderArguments() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: return String.Format(" \"{0}\" /t:Rebuild /p:Configuation={1}", Location, this.Configuration); default: throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform); } } protected virtual void BuildAssembly() { var info = new ProcessStartInfo() { FileName = this.GetBuilderPath(), Arguments = this.GetBuilderArguments(), UseShellExecute = true }; info.WindowStyle = ProcessWindowStyle.Hidden; using (var p = Process.Start(info)) { p.WaitForExit(); if (p.ExitCode != 0) { Bridge.Translator.Exception.Throw("Compilation was not successful, exit code - " + p.ExitCode); } } } } }
using System; using System.Diagnostics; namespace Bridge.Translator { public partial class Translator { protected static readonly char ps = System.IO.Path.DirectorySeparatorChar; protected virtual string GetBuilderPath() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: return Environment.GetEnvironmentVariable("windir") + ps + "Microsoft.NET" + ps + "Framework" + ps + this.MSBuildVersion + ps + "msbuild"; default: throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform); } } protected virtual string GetBuilderArguments() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: return String.Format(" \"{0}\" /t:Rebuild /p:Configuation={1}", Location, this.Configuration); default: throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform); } } protected virtual void BuildAssembly() { var info = new ProcessStartInfo() { FileName = this.GetBuilderPath(), Arguments = this.GetBuilderArguments() }; info.WindowStyle = ProcessWindowStyle.Hidden; using (var p = Process.Start(info)) { p.WaitForExit(); if (p.ExitCode != 0) { Bridge.Translator.Exception.Throw("Compilation was not successful, exit code - " + p.ExitCode); } } } } }
apache-2.0
C#
dc7ec68b7d062a0791b215e558a10f3936111127
Rewrite Problem: WordInPlural
DannyBerova/Exercises-Programming-Fundamentals-Extended-May-2017
ConditionalStatementsAndLoopsExercises/05.WordInPlural/05.WordInPlural.cs
ConditionalStatementsAndLoopsExercises/05.WordInPlural/05.WordInPlural.cs
 namespace _05.WordInPlural { using System; public class Program { public static void Main() { string input = Console.ReadLine(); if (input.EndsWith("o") || input.EndsWith("ch") || input.EndsWith("s") || input.EndsWith("sh") || input.EndsWith("x") || input.EndsWith("z")) { Console.WriteLine(input + "es"); } else if (input.EndsWith("y")) { input = input.Remove(input.Length - 1); Console.WriteLine(input + "ies"); } else { Console.WriteLine(input + "s"); } } } }
 namespace _05.WordInPlural { using System; public class Program { public static void Main() { string input = Console.ReadLine(); if (input.EndsWith("o")) { Console.WriteLine(input + "es"); } else if (input.EndsWith("ch")) { Console.WriteLine(input + "es"); } else if (input.EndsWith("s")) { Console.WriteLine(input + "es"); } else if (input.EndsWith("sh")) { Console.WriteLine(input + "es"); } else if (input.EndsWith("x")) { Console.WriteLine(input + "es"); } else if (input.EndsWith("z")) { Console.WriteLine(input + "es"); } else if (input.EndsWith("y")) { input = input.Remove(input.Length - 1); Console.WriteLine(input + "ies"); } else { Console.WriteLine(input + "s"); } } } }
mit
C#
ba345892043b87225d5daea9478e1c1c34c4dca9
add optional activity description to UiState() for failure reporting
mvbalaw/FluentBrowserAutomation
src/FluentBrowserAutomation/Extensions/IPageWrapper.cs
src/FluentBrowserAutomation/Extensions/IPageWrapper.cs
using System; // ReSharper disable once CheckNamespace namespace FluentBrowserAutomation { public interface IPageWrapper { IBrowserContext BrowserContext { get; } } public static class IPageWrapperExtensions { public static T UiState<T>(this T pageWrapper, params Action<IBrowserContext>[] funcs) where T : IPageWrapper { return UiState(pageWrapper, null, funcs); } public static T UiState<T>(this T pageWrapper, string activityDescription = null, params Action<IBrowserContext>[] funcs) where T : IPageWrapper { for (var index = 0; index < funcs.Length; index++) { var func = funcs[index]; var func1 = func; pageWrapper.BrowserContext.WaitUntil(x => { func1(pageWrapper.BrowserContext); return true; }, errorMessage: "UiState action " + (index + 1) + " of " + (activityDescription??funcs.Length.ToString()) + " failed."); } return pageWrapper; } } }
using System; // ReSharper disable once CheckNamespace namespace FluentBrowserAutomation { public interface IPageWrapper { IBrowserContext BrowserContext { get; } } public static class IPageWrapperExtensions { public static T UiState<T>(this T pageWrapper, params Action<IBrowserContext>[] funcs) where T : IPageWrapper { for (var index = 0; index < funcs.Length; index++) { var func = funcs[index]; var func1 = func; pageWrapper.BrowserContext.WaitUntil(x => { func1(pageWrapper.BrowserContext); return true; }, errorMessage:"UiState action " + (index + 1) + " of " + funcs.Length + " failed."); } return pageWrapper; } } }
mit
C#
70aa5eedf71b7d54b8bcef50ad26007cac9678f7
Fix issue #172 UserTypeConvention does not apply to nullable types
oceanho/fluent-nhibernate,HermanSchoenfeld/fluent-nhibernate,chester89/fluent-nhibernate,chester89/fluent-nhibernate,lingxyd/fluent-nhibernate,owerkop/fluent-nhibernate,chester89/fluent-nhibernate,hzhgis/ss,lingxyd/fluent-nhibernate,owerkop/fluent-nhibernate,narnau/fluent-nhibernate,HermanSchoenfeld/fluent-nhibernate,bogdan7/nhibernate,hzhgis/ss,narnau/fluent-nhibernate,bogdan7/nhibernate,hzhgis/ss,bogdan7/nhibernate,oceanho/fluent-nhibernate
src/FluentNHibernate/Conventions/UserTypeConvention.cs
src/FluentNHibernate/Conventions/UserTypeConvention.cs
using System; using FluentNHibernate.Conventions.AcceptanceCriteria; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Conventions.Inspections; using NHibernate.UserTypes; namespace FluentNHibernate.Conventions { /// <summary> /// Base class for user type conventions. Create a subclass of this to automatically /// map all properties that the user type can be used against. Override Accept or /// Apply to alter the behavior. /// </summary> /// <typeparam name="TUserType">IUserType implementation</typeparam> public abstract class UserTypeConvention<TUserType> : IUserTypeConvention where TUserType : IUserType, new() { public virtual void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { var userType = Activator.CreateInstance<TUserType>(); var returnedType = userType.ReturnedType; if (returnedType.IsValueType) { var nullableReturnedType = typeof(Nullable<>).MakeGenericType(returnedType); criteria.Expect(x => x.Type == returnedType || x.Type == nullableReturnedType); } else criteria.Expect(x => x.Type == returnedType); } public virtual void Apply(IPropertyInstance instance) { instance.CustomType<TUserType>(); } } }
using System; using FluentNHibernate.Conventions.AcceptanceCriteria; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Conventions.Inspections; using NHibernate.UserTypes; namespace FluentNHibernate.Conventions { /// <summary> /// Base class for user type conventions. Create a subclass of this to automatically /// map all properties that the user type can be used against. Override Accept or /// Apply to alter the behavior. /// </summary> /// <typeparam name="TUserType">IUserType implementation</typeparam> public abstract class UserTypeConvention<TUserType> : IUserTypeConvention where TUserType : IUserType, new() { public virtual void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { var userType = Activator.CreateInstance<TUserType>(); criteria.Expect(x => x.Type == userType.ReturnedType); } public virtual void Apply(IPropertyInstance instance) { instance.CustomType<TUserType>(); } } }
bsd-3-clause
C#