commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
d7a9c5fd410e370f89e83ef1bd3475a418ffe4ed
osu.Game/Overlays/Settings/Sections/DebugSettings/MemorySettings.cs
osu.Game/Overlays/Settings/Sections/DebugSettings/MemorySettings.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Platform; using osu.Game.Database; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class MemorySettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.MemoryHeader; [BackgroundDependencyLoader] private void load(GameHost host, RealmContextFactory realmFactory) { Children = new Drawable[] { new SettingsButton { Text = DebugSettingsStrings.ClearAllCaches, Action = host.Collect }, new SettingsButton { Text = DebugSettingsStrings.CompactRealm, Action = () => { // Blocking operations implicitly causes a Compact(). using (realmFactory.BlockAllOperations()) { } } }, }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Framework.Platform; using osu.Game.Database; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.DebugSettings { public class MemorySettings : SettingsSubsection { protected override LocalisableString Header => DebugSettingsStrings.MemoryHeader; [BackgroundDependencyLoader] private void load(GameHost host, RealmContextFactory realmFactory) { SettingsButton blockAction; SettingsButton unblockAction; Children = new Drawable[] { new SettingsButton { Text = DebugSettingsStrings.ClearAllCaches, Action = host.Collect }, new SettingsButton { Text = DebugSettingsStrings.CompactRealm, Action = () => { // Blocking operations implicitly causes a Compact(). using (realmFactory.BlockAllOperations()) { } } }, blockAction = new SettingsButton { Text = "Block realm", }, unblockAction = new SettingsButton { Text = "Unblock realm", }, }; blockAction.Action = () => { var blocking = realmFactory.BlockAllOperations(); blockAction.Enabled.Value = false; // As a safety measure, unblock after 10 seconds. // This is to handle the case where a dev may block, but then something on the update thread // accesses realm and blocks for eternity. Task.Factory.StartNew(() => { Thread.Sleep(10000); unblock(); }); unblockAction.Action = unblock; void unblock() { blocking?.Dispose(); blocking = null; Scheduler.Add(() => { blockAction.Enabled.Value = true; unblockAction.Action = null; }); } }; } } }
Add settings buttons to allow temporarily blocking realm access
Add settings buttons to allow temporarily blocking realm access
C#
mit
peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu
60f922ce1b67f434d6d6afbeaa68fa52866283a4
src/Nest/Domain/Settings/SynonymTokenFilter.cs
src/Nest/Domain/Settings/SynonymTokenFilter.cs
using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } [JsonProperty("ignore_case", NullValueHandling = NullValueHandling.Ignore)] public bool? IgnoreCase { get; set; } [JsonProperty("expand", NullValueHandling = NullValueHandling.Ignore)] public bool? Expand { get; set; } } }
Add ignore_case and expand properties to synonym filter
Add ignore_case and expand properties to synonym filter
C#
apache-2.0
UdiBen/elasticsearch-net,geofeedia/elasticsearch-net,azubanov/elasticsearch-net,joehmchan/elasticsearch-net,alanprot/elasticsearch-net,abibell/elasticsearch-net,junlapong/elasticsearch-net,jonyadamit/elasticsearch-net,ststeiger/elasticsearch-net,faisal00813/elasticsearch-net,adam-mccoy/elasticsearch-net,LeoYao/elasticsearch-net,tkirill/elasticsearch-net,joehmchan/elasticsearch-net,NickCraver/NEST,NickCraver/NEST,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,jonyadamit/elasticsearch-net,LeoYao/elasticsearch-net,RossLieberman/NEST,DavidSSL/elasticsearch-net,starckgates/elasticsearch-net,elastic/elasticsearch-net,jonyadamit/elasticsearch-net,amyzheng424/elasticsearch-net,gayancc/elasticsearch-net,adam-mccoy/elasticsearch-net,mac2000/elasticsearch-net,robrich/elasticsearch-net,alanprot/elasticsearch-net,ststeiger/elasticsearch-net,robrich/elasticsearch-net,NickCraver/NEST,Grastveit/NEST,faisal00813/elasticsearch-net,abibell/elasticsearch-net,starckgates/elasticsearch-net,CSGOpenSource/elasticsearch-net,robertlyson/elasticsearch-net,UdiBen/elasticsearch-net,starckgates/elasticsearch-net,UdiBen/elasticsearch-net,tkirill/elasticsearch-net,SeanKilleen/elasticsearch-net,mac2000/elasticsearch-net,SeanKilleen/elasticsearch-net,ststeiger/elasticsearch-net,LeoYao/elasticsearch-net,TheFireCookie/elasticsearch-net,KodrAus/elasticsearch-net,junlapong/elasticsearch-net,alanprot/elasticsearch-net,CSGOpenSource/elasticsearch-net,robertlyson/elasticsearch-net,wawrzyn/elasticsearch-net,abibell/elasticsearch-net,RossLieberman/NEST,robertlyson/elasticsearch-net,gayancc/elasticsearch-net,joehmchan/elasticsearch-net,faisal00813/elasticsearch-net,alanprot/elasticsearch-net,DavidSSL/elasticsearch-net,cstlaurent/elasticsearch-net,mac2000/elasticsearch-net,wawrzyn/elasticsearch-net,DavidSSL/elasticsearch-net,KodrAus/elasticsearch-net,wawrzyn/elasticsearch-net,cstlaurent/elasticsearch-net,SeanKilleen/elasticsearch-net,Grastveit/NEST,amyzheng424/elasticsearch-net,TheFireCookie/elasticsearch-net,tkirill/elasticsearch-net,geofeedia/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,amyzheng424/elasticsearch-net,robrich/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,Grastveit/NEST,junlapong/elasticsearch-net,geofeedia/elasticsearch-net,elastic/elasticsearch-net,cstlaurent/elasticsearch-net,KodrAus/elasticsearch-net,gayancc/elasticsearch-net
a947ad6755ae34fb114d94129b46525170abd33e
Assets/HexMap/HexMap.cs
Assets/HexMap/HexMap.cs
/* Copyright (c) 2016 Kevin Fischer * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the license was not distributed with this file, * You can obtain one at https://opensource.org/licenses/MIT. */ using UnityEngine; using System.Collections.Generic; using System.Collections.ObjectModel; namespace HexMapEngine { public class HexMap : ScriptableObject { List<HexData> _hexData; public ReadOnlyCollection<HexData> HexData { get { return _hexData.AsReadOnly(); } } Dictionary<Hex, HexData> _map; public void SetHexData(List<HexData> hexData) { _hexData = hexData; _map = new Dictionary<Hex, HexData>(); foreach (HexData data in hexData) { _map.Add(data.position, data); } } public HexData Get(Hex position) { HexData result; _map.TryGetValue(position, out result); return result; } } }
/* Copyright (c) 2016 Kevin Fischer * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the license was not distributed with this file, * You can obtain one at https://opensource.org/licenses/MIT. */ using UnityEngine; using System.Collections.Generic; using System.Collections.ObjectModel; namespace HexMapEngine { public class HexMap : ScriptableObject { List<HexData> _hexData = new List<HexData>(); public ReadOnlyCollection<HexData> HexData { get { return _hexData.AsReadOnly(); } } Dictionary<Hex, HexData> _map; public void SetHexData(List<HexData> hexData) { _hexData = hexData; _map = new Dictionary<Hex, HexData>(); foreach (HexData data in hexData) { _map.Add(data.position, data); } } public HexData Get(Hex position) { HexData result; _map.TryGetValue(position, out result); return result; } } }
Fix missing object reference error.
Fix missing object reference error.
C#
mit
DerTraveler/unity-hex-map
e426c0fa04d5a6ab8fe94a554202c752e3b2e83b
WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs
WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { IsBusy = true; try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
Set IsBusy immediately, so there is no chance to run the command more than once.
Set IsBusy immediately, so there is no chance to run the command more than once.
C#
mit
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
767f2900f9faeff247d48a4b4a96c91a846b339a
samples/SignalRSamples/ObservableExtensions.cs
samples/SignalRSamples/ObservableExtensions.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reactive.Linq; using System.Threading.Channels; namespace SignalRSamples { public static class ObservableExtensions { public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable) { // This sample shows adapting an observable to a ChannelReader without // back pressure, if the connection is slower than the producer, memory will // start to increase. // If the channel is unbounded, TryWrite will return false and effectively // drop items. // The other alternative is to use a bounded channel, and when the limit is reached // block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended var channel = Channel.CreateUnbounded<T>(); var disposable = observable.Subscribe( value => channel.Writer.TryWrite(value), error => channel.Writer.TryComplete(error), () => channel.Writer.TryComplete()); // Complete the subscription on the reader completing channel.Reader.Completion.ContinueWith(task => disposable.Dispose()); return channel.Reader; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reactive.Linq; using System.Threading.Channels; namespace SignalRSamples { public static class ObservableExtensions { public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable, int? maxBufferSize = null) { // This sample shows adapting an observable to a ChannelReader without // back pressure, if the connection is slower than the producer, memory will // start to increase. // If the channel is bounded, TryWrite will return false and effectively // drop items. // The other alternative is to use a bounded channel, and when the limit is reached // block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended and isn't shown here. var channel = maxBufferSize != null ? Channel.CreateBounded<T>(maxBufferSize.Value) : Channel.CreateUnbounded<T>(); var disposable = observable.Subscribe( value => channel.Writer.TryWrite(value), error => channel.Writer.TryComplete(error), () => channel.Writer.TryComplete()); // Complete the subscription on the reader completing channel.Reader.Completion.ContinueWith(task => disposable.Dispose()); return channel.Reader; } } }
Add support for creating a bounded channel in helper
Add support for creating a bounded channel in helper
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
5a74e8dd400131b40f3fcda7eb2e4eb5e43203b5
src/Totem/Runtime/Timeline/ITimeline.cs
src/Totem/Runtime/Timeline/ITimeline.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Totem.Runtime.Timeline { /// <summary> /// Describes a series of domain events /// </summary> public interface ITimeline : IFluent { void Append(TimelinePosition cause, IReadOnlyList<Event> events); Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Totem.Runtime.Timeline { /// <summary> /// Describes a series of domain events /// </summary> public interface ITimeline : IFluent { void Append(TimelinePosition cause, Many<Event> events); void AppendLater(DateTime when, Many<Event> events); Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow; } }
Add scheduling of events to occur later on the timeline
Add scheduling of events to occur later on the timeline
C#
mit
bwatts/Totem,bwatts/Totem
43d2cdbe1d757d39b486f717b52258f0953e2b89
Espera/GlobalAssemblyInfo.cs
Espera/GlobalAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyProduct("Espera")] [assembly: AssemblyCopyright("Copyright © 2013 Dennis Daume")] [assembly: AssemblyVersion("1.7.0.6")] [assembly: AssemblyFileVersion("1.7.0.6")]
using System.Reflection; [assembly: AssemblyProduct("Espera")] [assembly: AssemblyCopyright("Copyright © 2013 Dennis Daume")] [assembly: AssemblyVersion("1.7.6")] [assembly: AssemblyFileVersion("1.7.6")] [assembly: AssemblyInformationalVersion("1.7.6")]
Fix assembly version for Shimmer
Fix assembly version for Shimmer
C#
mit
flagbug/Espera,punker76/Espera
9967bb85ea6f6425a14863c1fafc8c29b4696ec6
src/SFA.DAS.EmployerAccounts.Web/Controllers/ErrorController.cs
src/SFA.DAS.EmployerAccounts.Web/Controllers/ErrorController.cs
using System.Net; using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.Controllers { public class ErrorController : Controller { [Route("accessdenied")] public ActionResult AccessDenied() { Response.StatusCode = (int)HttpStatusCode.Forbidden; return View(); } [Route("error")] public ActionResult Error() { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return View(); } [Route("notfound")] public ActionResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } } }
using System.Net; using System.Web.Mvc; using SFA.DAS.Authentication; using SFA.DAS.EmployerAccounts.Interfaces; using SFA.DAS.EmployerAccounts.Web.ViewModels; namespace SFA.DAS.EmployerAccounts.Web.Controllers { public class ErrorController : BaseController { public ErrorController( IAuthenticationService owinWrapper, IMultiVariantTestingService multiVariantTestingService, ICookieStorageService<FlashMessageViewModel> flashMessage) : base(owinWrapper, multiVariantTestingService, flashMessage) { } [Route("accessdenied")] public ActionResult AccessDenied() { Response.StatusCode = (int)HttpStatusCode.Forbidden; return View(); } [Route("error")] public ActionResult Error() { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return View(); } [Route("notfound")] public ActionResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } } }
Add base class to error controller so that it can find Base SupportUserBanner child action
Add base class to error controller so that it can find Base SupportUserBanner child action
C#
mit
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
266f7ad13e9ffa5e08c88517feaec32c831ff4f2
Repository/SignInActivity.cs
Repository/SignInActivity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; using Repository.Internal; using static Repository.Internal.Verify; namespace Repository { [Activity(Label = "Sign In")] public class SignInActivity : Activity { private sealed class LoginSuccessListener : WebViewClient { private readonly string _callbackUrl; internal LoginSuccessListener(string callbackUrl) { _callbackUrl = NotNull(callbackUrl); } public override void OnPageFinished(WebView view, string url) { if (url.StartsWith(_callbackUrl, StringComparison.Ordinal)) { // TODO: Start some activity? } } } private WebView _signInWebView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.SignIn); _signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView); var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url)); _signInWebView.LoadUrl(url); var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl)); _signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; using Repository.Internal; using static Repository.Internal.Verify; namespace Repository { [Activity(Label = "Sign In")] public class SignInActivity : Activity { private sealed class LoginSuccessListener : WebViewClient { private readonly string _callbackUrl; internal LoginSuccessListener(string callbackUrl) { _callbackUrl = NotNull(callbackUrl); } public override void OnPageFinished(WebView view, string url) { if (url.StartsWith(_callbackUrl, StringComparison.Ordinal)) { // TODO: Start some activity? } } } private WebView _signInWebView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.SignIn); _signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView); // GitHub needs JS enabled to un-grey the authorization button _signInWebView.Settings.JavaScriptEnabled = true; var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url)); _signInWebView.LoadUrl(url); var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl)); _signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl)); } } }
Enable JS in the browser so the user can authorize the app
[SignIn] Enable JS in the browser so the user can authorize the app
C#
mit
jamesqo/Repository,jamesqo/Repository,jamesqo/Repository
a967a89aaa2cf5a8cbe191dcfb0aa4f78b5d8549
SlackAPI/Response.cs
SlackAPI/Response.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public abstract class Response { /// <summary> /// Should always be checked before trying to process a response. /// </summary> public bool ok; /// <summary> /// if ok is false, then this is the reason-code /// </summary> public string error; public void AssertOk() { if (!(ok)) throw new InvalidOperationException(string.Format("An error occurred: {0}", this.error)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public abstract class Response { /// <summary> /// Should always be checked before trying to process a response. /// </summary> public bool ok; /// <summary> /// if ok is false, then this is the reason-code /// </summary> public string error; public string needed; public string provided; public void AssertOk() { if (!(ok)) throw new InvalidOperationException(string.Format("An error occurred: {0}", this.error)); } } }
Add the attribute needed, provided
Add the attribute needed, provided Some time when we have a connection failure, the error message need some information, ex: missing_scope So we need to know what are the "needed" scope to add them. with provided we can see what are the permission that we already provided to app.
C#
mit
Inumedia/SlackAPI
67477a20a004c97d795e203f745acb2d7999214e
Assets/CloudBread/API/OAuth/OAuth2Setting.cs
Assets/CloudBread/API/OAuth/OAuth2Setting.cs
using System; using UnityEngine; namespace CloudBread.OAuth { public class OAuth2Setting : ScriptableObject { static bool _useFacebook; static public string FaceBookRedirectAddress; static bool _useGooglePlay; public static string GooglePlayRedirectAddress; static bool _useKaKao; public static string KakaoRedirectAddress; public OAuth2Setting () { } } }
using System; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEditor; namespace CloudBread.OAuth { public class OAuth2Setting : ScriptableObject { private const string SettingAssetName = "CBOAuth2Setting"; private const string SettingsPath = "CloudBread/Resources"; private const string SettingsAssetExtension = ".asset"; // Facebook private bool _useFacebook = false; static public bool UseFacebook { get { return Instance._useFacebook; } set { Instance._useFacebook = value; } } private string _facebookRedirectAddress = ".auth/login/facebook"; static public string FacebookRedirectAddress { get { return Instance._facebookRedirectAddress; } set { Instance._facebookRedirectAddress = value; } } // GoogePlay public bool _useGooglePlay = false; static public bool UseGooglePlay { get { return instance._useGooglePlay; } set { Instance._useGooglePlay = value; } } public string _googleRedirectAddress = "aaaa"; static public string GoogleRedirectAddress { get { return instance._googleRedirectAddress; } set { Instance._googleRedirectAddress = value; } } // KaKao private bool _useKaKao = false; public bool UseKaKao { get { return Instance._useKaKao; } set { Instance._useKaKao = value; } } public static string KakaoRedirectAddress; private static OAuth2Setting instance = null; public static OAuth2Setting Instance { get { if (instance == null) { instance = Resources.Load(SettingAssetName) as OAuth2Setting; if (instance == null) { // If not found, autocreate the asset object. instance = ScriptableObject.CreateInstance<OAuth2Setting>(); #if UNITY_EDITOR string properPath = Path.Combine(Application.dataPath, SettingsPath); if (!Directory.Exists(properPath)) { Directory.CreateDirectory(properPath); } string fullPath = Path.Combine( Path.Combine("Assets", SettingsPath), SettingAssetName + SettingsAssetExtension); AssetDatabase.CreateAsset(instance, fullPath); #endif } } return instance; } } } }
Update Setting Values for OAuth2 setting
Update Setting Values for OAuth2 setting
C#
mit
CloudBreadProject/CloudBread-Unity-SDK
3669e5f4de6ef9a43ca45e071e8c6a513d4111f9
src/Glimpse.Common/Internal/Serialization/TimeSpanConverter.cs
src/Glimpse.Common/Internal/Serialization/TimeSpanConverter.cs
using System; using Newtonsoft.Json; namespace Glimpse.Internal { public class TimeSpanConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = 0.0; var convertedNullable = value as TimeSpan?; if (convertedNullable.HasValue) { result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2); } writer.WriteRawValue(result.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value; } public override bool CanConvert(Type objectType) { return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?); } } }
using System; using System.Globalization; using Newtonsoft.Json; namespace Glimpse.Internal { public class TimeSpanConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = 0.0; var convertedNullable = value as TimeSpan?; if (convertedNullable.HasValue) { result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2); } writer.WriteRawValue(result.ToString(CultureInfo.InvariantCulture)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value; } public override bool CanConvert(Type objectType) { return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?); } } }
Fix invalid JSON caused by localized decimal mark
Fix invalid JSON caused by localized decimal mark Using InvariantCulture to convert the double to string to generate a dot instead of a comma.
C#
mit
zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype
d403c72fcf934da32d1db5d287a54406df512881
Digirati.IIIF/Model/Types/Collection.cs
Digirati.IIIF/Model/Types/Collection.cs
using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Collection : IIIFPresentationBase { [JsonProperty(Order = 100, PropertyName = "collections")] public Collection[] Collections { get; set; } [JsonProperty(Order = 101, PropertyName = "manifests")] public Manifest[] Manifests { get; set; } public override string Type { get { return "sc:Collection"; } } } }
using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Collection : IIIFPresentationBase { [JsonProperty(Order = 100, PropertyName = "collections")] public Collection[] Collections { get; set; } [JsonProperty(Order = 101, PropertyName = "manifests")] public Manifest[] Manifests { get; set; } [JsonProperty(Order = 111, PropertyName = "members")] public IIIFPresentationBase[] Members { get; set; } public override string Type { get { return "sc:Collection"; } } } }
Add members property to collection
Add members property to collection
C#
mit
digirati-co-uk/iiif-model
612dfe57fdabf3f6a99f3ce0a7a2e073e908ed70
MadCat/NutPackerLib/OriginalNameAttribute.cs
MadCat/NutPackerLib/OriginalNameAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NutPackerLib { public class OriginalNameAttribute : Attribute { public string Name { get; private set; } public OriginalNameAttribute(string name) { Name = name; } } }
using System; namespace NutPackerLib { /// <summary> /// Original name of something. /// </summary> public class OriginalNameAttribute : Attribute { public string Name { get; private set; } public OriginalNameAttribute(string name) { Name = name; } } }
Remove unnecessary using's, add comment
Remove unnecessary using's, add comment
C#
mit
EasyPeasyLemonSqueezy/MadCat
088342a3198645996377e571233f144cb1fa2774
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.13.0")] [assembly: AssemblyFileVersion("0.13.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.14.0")] [assembly: AssemblyFileVersion("0.14.0")]
Increase project version number to 0.14.0
Increase project version number to 0.14.0
C#
apache-2.0
atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata
4daeca013588066a09d7fb6ecf8a2300d1dd9533
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.15.0")] [assembly: AssemblyFileVersion("0.15.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.16.0")] [assembly: AssemblyFileVersion("0.16.0")]
Increase project version to 0.16.0
Increase project version to 0.16.0
C#
apache-2.0
atata-framework/atata-sample-app-tests
00b17402814209cc0f54abd211ec051a92f1cbd4
PaletteInsightAgentService/Service.cs
PaletteInsightAgentService/Service.cs
using Topshelf; namespace PaletteInsightAgentService { /// <summary> /// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us. /// </summary> internal class PaletteInsightAgentService { // Service name & description. private const string ServiceName = "PaletteInsightAgent"; private const string ServiceDisplayname = "PaletteInsightAgent"; private const string ServiceDescription = "Tableau Server performance monitor"; // Service recovery attempt timings, in minutes. private const int RecoveryFirstAttempt = 0; private const int RecoverySecondAttempt = 1; private const int RecoveryThirdAttempt = 5; // Service recovery reset period, in days. private const int RecoveryResetPeriod = 1; /// <summary> /// Main entry point for the service layer. /// </summary> public static void Main() { // configure service parameters HostFactory.Run(hostConfigurator => { hostConfigurator.SetServiceName(ServiceName); hostConfigurator.SetDescription(ServiceDescription); hostConfigurator.SetDisplayName(ServiceDisplayname); hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper()); hostConfigurator.RunAsLocalSystem(); hostConfigurator.StartAutomaticallyDelayed(); hostConfigurator.UseNLog(); hostConfigurator.EnableServiceRecovery(r => { r.RestartService(RecoveryFirstAttempt); r.RestartService(RecoverySecondAttempt); r.RestartService(RecoveryThirdAttempt); r.OnCrashOnly(); r.SetResetPeriod(RecoveryResetPeriod); }); }); } } }
using Topshelf; namespace PaletteInsightAgentService { /// <summary> /// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us. /// </summary> internal class PaletteInsightAgentService { // Service name & description. private const string ServiceName = "PaletteInsightAgent"; private const string ServiceDisplayname = "Palette Insight Agent"; private const string ServiceDescription = "Tableau Server performance monitor"; // Service recovery attempt timings, in minutes. private const int RecoveryFirstAttempt = 0; private const int RecoverySecondAttempt = 1; private const int RecoveryThirdAttempt = 5; // Service recovery reset period, in days. private const int RecoveryResetPeriod = 1; /// <summary> /// Main entry point for the service layer. /// </summary> public static void Main() { // configure service parameters HostFactory.Run(hostConfigurator => { hostConfigurator.SetServiceName(ServiceName); hostConfigurator.SetDescription(ServiceDescription); hostConfigurator.SetDisplayName(ServiceDisplayname); hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper()); hostConfigurator.RunAsLocalSystem(); hostConfigurator.StartAutomaticallyDelayed(); hostConfigurator.UseNLog(); hostConfigurator.EnableServiceRecovery(r => { r.RestartService(RecoveryFirstAttempt); r.RestartService(RecoverySecondAttempt); r.RestartService(RecoveryThirdAttempt); r.OnCrashOnly(); r.SetResetPeriod(RecoveryResetPeriod); }); }); } } }
Add spaces into displayed Palette Insight Agent service name
Add spaces into displayed Palette Insight Agent service name
C#
mit
palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent
a6da86e32d1d4a7f74dd4ccbed654943cef8ffba
Source/DTMF.Website/Logic/TeamCity.cs
Source/DTMF.Website/Logic/TeamCity.cs
using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //remove prefix and suffixes from app names so same app can go to multiple places appName = appName.Replace(".Production", ""); appName = appName.Replace(".Development", ""); appName = appName.Replace(".Staging", ""); appName = appName.Replace(".Test", ""); //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.Contains(appName))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }
using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //remove prefix and suffixes from app names so same app can go to multiple places appName = appName.Replace(".Production", ""); appName = appName.Replace(".Development", ""); appName = appName.Replace(".Staging", ""); appName = appName.Replace(".Test", ""); //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.ToLower().Contains(appName.ToLower()))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }
Fix for buildtypeid case mismatch
Fix for buildtypeid case mismatch
C#
mit
ericdc1/DTMF,ericdc1/DTMF,ericdc1/DTMF
a140440196eda89710e44f18b5d884b07476e260
src/Microsoft.AspNet.Mvc.Razor.Host.VSRC1/Properties/AssemblyInfo.cs
src/Microsoft.AspNet.Mvc.Razor.Host.VSRC1/Properties/AssemblyInfo.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")]
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyProduct("Microsoft ASP.NET Core")]
Add `AssemblyCompany`, `AssemblyCopyright` and `AssemblyProduct` attributes to the assembly.
Add `AssemblyCompany`, `AssemblyCopyright` and `AssemblyProduct` attributes to the assembly.
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
620e503371b4a31974fd438e18e45fc623b823bb
ChamberLib/MathHelper.cs
ChamberLib/MathHelper.cs
using System; namespace ChamberLib { public static class MathHelper { public static int RoundToInt(this float x) { return (int)Math.Round(x); } public static float ToRadians(this float degrees) { return degrees * 0.01745329251994f; // pi / 180 } public static float ToDegrees( this float radians) { return radians * 57.2957795130823f; // 180 / pi } public static float Clamp(this float value, float min, float max) { return Math.Max(Math.Min(value, max), min); } } }
using System; namespace ChamberLib { public static class MathHelper { public static int RoundToInt(this float x) { return (int)Math.Round(x); } public static float ToRadians(this float degrees) { return degrees * 0.01745329251994f; // pi / 180 } public static float ToDegrees( this float radians) { return radians * 57.2957795130823f; // 180 / pi } public static float Clamp(this float value, float min, float max) { if (value > max) return max; if (value < min) return min; return value; } } }
Replace Xna's Clamp method with our own.
Replace Xna's Clamp method with our own.
C#
lgpl-2.1
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
a9142409d646957a48c651af3d2923cf44a90a00
zap/main.cs
zap/main.cs
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2009, mEthLab Interactive //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Package overrides to initialize the mod. package Zap { function displayHelp() { Parent::displayHelp(); } function parseArgs() { Parent::parseArgs(); } function onStart() { Parent::onStart(); echo("\n--------- Initializing MOD: Zap ---------"); exec("./server.cs"); } function onExit() { Parent::onExit(); } }; // package Zap activatePackage(Zap);
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2009, mEthLab Interactive //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Package overrides to initialize the mod. package Zap { function displayHelp() { Parent::displayHelp(); } function parseArgs() { Parent::parseArgs(); } function onStart() { echo("\n--------- Initializing MOD: Zap ---------"); exec("./server.cs"); Parent::onStart(); } function onExit() { Parent::onExit(); } }; // package Zap activatePackage(Zap);
Fix Zap mod dedicated server.
Fix Zap mod dedicated server.
C#
lgpl-2.1
fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game
9f7874c78d40a7e27aaeeaaa1787c0f5d987d51f
src/AppHarbor.Tests/AutoCommandDataAttribute.cs
src/AppHarbor.Tests/AutoCommandDataAttribute.cs
using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using Ploeh.AutoFixture.Xunit; namespace AppHarbor.Tests { public class AutoCommandDataAttribute : AutoDataAttribute { public AutoCommandDataAttribute() : base(new Fixture().Customize(new AutoMoqCustomization())) { } } }
using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoMoq; using Ploeh.AutoFixture.Xunit; namespace AppHarbor.Tests { public class AutoCommandDataAttribute : AutoDataAttribute { public AutoCommandDataAttribute() : base(new Fixture().Customize(new DomainCustomization())) { } } }
Use DomainCustomization rather than AutoMoqCustomization directly
Use DomainCustomization rather than AutoMoqCustomization directly
C#
mit
appharbor/appharbor-cli
2976cd1ce4aef0eef6ae17591ec6434dd9d0a013
Gu.Wpf.UiAutomation/AutomationElements/Thumb.cs
Gu.Wpf.UiAutomation/AutomationElements/Thumb.cs
namespace Gu.Wpf.UiAutomation { using System.Windows.Automation; public class Thumb : UiElement { public Thumb(AutomationElement automationElement) : base(automationElement) { } public TransformPattern TransformPattern => this.AutomationElement.TransformPattern(); /// <summary> /// Moves the slider horizontally. /// </summary> /// <param name="distance">+ for right, - for left.</param> public void SlideHorizontally(int distance) { Mouse.DragHorizontally(MouseButton.Left, this.Bounds.Center(), distance); } /// <summary> /// Moves the slider vertically. /// </summary> /// <param name="distance">+ for down, - for up.</param> public void SlideVertically(int distance) { Mouse.DragVertically(MouseButton.Left, this.Bounds.Center(), distance); } } }
namespace Gu.Wpf.UiAutomation { using System.Windows; using System.Windows.Automation; public class Thumb : UiElement { private const int DragSpeed = 500; public Thumb(AutomationElement automationElement) : base(automationElement) { } public TransformPattern TransformPattern => this.AutomationElement.TransformPattern(); /// <summary> /// Moves the slider horizontally. /// </summary> /// <param name="distance">+ for right, - for left.</param> public void SlideHorizontally(int distance) { var cp = this.GetClickablePoint(); Mouse.Drag(MouseButton.Left, cp, cp + new Vector(distance, 0), DragSpeed); Wait.UntilInputIsProcessed(); } /// <summary> /// Moves the slider vertically. /// </summary> /// <param name="distance">+ for down, - for up.</param> public void SlideVertically(int distance) { var cp = this.GetClickablePoint(); Mouse.Drag(MouseButton.Left, cp, cp + new Vector(0, distance), DragSpeed); Wait.UntilInputIsProcessed(); } } }
Fix SliderTest.SlideHorizontally on Win 10
Fix SliderTest.SlideHorizontally on Win 10 Fix #55
C#
mit
JohanLarsson/Gu.Wpf.UiAutomation
fd0cd2c948e95eb25d24930f22c65e7a59c385e0
resharper/resharper-yaml/src/Psi/YamlProjectFileLanguageService.cs
resharper/resharper-yaml/src/Psi/YamlProjectFileLanguageService.cs
using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.Settings; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Resources; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.Text; using JetBrains.UI.Icons; namespace JetBrains.ReSharper.Plugins.Yaml.Psi { [ProjectFileType(typeof(YamlProjectFileType))] public class YamlProjectFileLanguageService : ProjectFileLanguageService { private readonly YamlSupport myYamlSupport; public YamlProjectFileLanguageService(YamlSupport yamlSupport) : base(YamlProjectFileType.Instance) { myYamlSupport = yamlSupport; } public override ILexerFactory GetMixedLexerFactory(ISolution solution, IBuffer buffer, IPsiSourceFile sourceFile = null) { var languageService = YamlLanguage.Instance.LanguageService(); return languageService?.GetPrimaryLexerFactory(); } protected override PsiLanguageType PsiLanguageType { get { var yamlLanguage = (PsiLanguageType) YamlLanguage.Instance ?? UnknownLanguage.Instance; return myYamlSupport.IsParsingEnabled.Value ? yamlLanguage : UnknownLanguage.Instance; } } // TODO: Proper icon! public override IconId Icon => PsiCSharpThemedIcons.Csharp.Id; } }
using JetBrains.Application.UI.Icons.Special.ThemedIcons; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; using JetBrains.ReSharper.Plugins.Yaml.Settings; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.Text; using JetBrains.UI.Icons; namespace JetBrains.ReSharper.Plugins.Yaml.Psi { [ProjectFileType(typeof(YamlProjectFileType))] public class YamlProjectFileLanguageService : ProjectFileLanguageService { private readonly YamlSupport myYamlSupport; public YamlProjectFileLanguageService(YamlSupport yamlSupport) : base(YamlProjectFileType.Instance) { myYamlSupport = yamlSupport; } public override ILexerFactory GetMixedLexerFactory(ISolution solution, IBuffer buffer, IPsiSourceFile sourceFile = null) { var languageService = YamlLanguage.Instance.LanguageService(); return languageService?.GetPrimaryLexerFactory(); } protected override PsiLanguageType PsiLanguageType { get { var yamlLanguage = (PsiLanguageType) YamlLanguage.Instance ?? UnknownLanguage.Instance; return myYamlSupport.IsParsingEnabled.Value ? yamlLanguage : UnknownLanguage.Instance; } } // TODO: Proper icon! public override IconId Icon => SpecialThemedIcons.Placeholder.Id; } }
Use less confusing placeholder icon for YAML
Use less confusing placeholder icon for YAML
C#
apache-2.0
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
71c603072906823028642dda66f9f0a0afdc76d5
src/PowerShellEditorServices.Protocol/LanguageServer/Definition.cs
src/PowerShellEditorServices.Protocol/LanguageServer/Definition.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class DefinitionRequest { public static readonly RequestType<TextDocumentPosition, Location[], object, object> Type = RequestType<TextDocumentPosition, Location[], object, object>.Create("textDocument/definition"); } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class DefinitionRequest { public static readonly RequestType<TextDocumentPosition, Location[], object, TextDocumentRegistrationOptions> Type = RequestType<TextDocumentPosition, Location[], object, TextDocumentRegistrationOptions>.Create("textDocument/definition"); } }
Add registration options for definition request
Add registration options for definition request
C#
mit
PowerShell/PowerShellEditorServices
883dee3a84f3a72d9576e4489902849abe4df2ee
Website/Migrations/201304030226233_CuratedFeedPackageUniqueness.cs
Website/Migrations/201304030226233_CuratedFeedPackageUniqueness.cs
namespace NuGetGallery.Migrations { using System.Data.Entity.Migrations; public partial class CuratedFeedPackageUniqueness : DbMigration { public override void Up() { // ADD uniqueness constraint - as an Index, since it seems reasonable to look up curated package entries by their feed + registration CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration"); } public override void Down() { // REMOVE uniqueness constraint DropIndex("CuratedPackages", "IX_CuratedPackage_CuratedFeedAndPackageRegistration"); } } }
namespace NuGetGallery.Migrations { using System.Data.Entity.Migrations; public partial class CuratedFeedPackageUniqueness : DbMigration { public override void Up() { // ADD uniqueness constraint - as an Index, since it seems reasonable to look up curated package entries by their feed + registration CreateIndex("CuratedPackages", new[] { "CuratedFeedKey", "PackageRegistrationKey" }, unique: true, name: "IX_CuratedFeed_PackageRegistration"); } public override void Down() { // REMOVE uniqueness constraint DropIndex("CuratedPackages", "IX_CuratedFeed_PackageRegistration"); } } }
Fix having the wrong Index name in migration CuratedFeedPackageUniqueness.Down()
Fix having the wrong Index name in migration CuratedFeedPackageUniqueness.Down()
C#
apache-2.0
KuduApps/NuGetGallery,KuduApps/NuGetGallery,grenade/NuGetGallery_download-count-patch,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,JetBrains/ReSharperGallery,projectkudu/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,JetBrains/ReSharperGallery,skbkontur/NuGetGallery,ScottShingler/NuGetGallery,KuduApps/NuGetGallery,mtian/SiteExtensionGallery,projectkudu/SiteExtensionGallery,skbkontur/NuGetGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,KuduApps/NuGetGallery,skbkontur/NuGetGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,projectkudu/SiteExtensionGallery,ScottShingler/NuGetGallery
236e55a107ad752b837841d7696ace5ff479a2dd
Mongo.Migration/Migrations/Locators/TypeMigrationDependencyLocator.cs
Mongo.Migration/Migrations/Locators/TypeMigrationDependencyLocator.cs
using System; using System.Linq; using System.Reflection; using Mongo.Migration.Extensions; using Mongo.Migration.Migrations.Adapters; namespace Mongo.Migration.Migrations.Locators { internal class TypeMigrationDependencyLocator<TMigrationType> : MigrationLocator<TMigrationType> where TMigrationType: class, IMigration { private readonly IContainerProvider _containerProvider; public TypeMigrationDependencyLocator(IContainerProvider containerProvider) { _containerProvider = containerProvider; } public override void Locate() { var migrationTypes = (from assembly in Assemblies from type in assembly.GetTypes() where typeof(TMigrationType).IsAssignableFrom(type) && !type.IsAbstract select type).Distinct(); Migrations = migrationTypes.Select(GetMigrationInstance).ToMigrationDictionary(); } private TMigrationType GetMigrationInstance(Type type) { ConstructorInfo constructor = type.GetConstructors()[0]; if(constructor != null) { object[] args = constructor .GetParameters() .Select(o => o.ParameterType) .Select(o => _containerProvider.GetInstance(o)) .ToArray(); return Activator.CreateInstance(type, args) as TMigrationType; } return Activator.CreateInstance(type) as TMigrationType; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Mongo.Migration.Extensions; using Mongo.Migration.Migrations.Adapters; namespace Mongo.Migration.Migrations.Locators { internal class TypeMigrationDependencyLocator<TMigrationType> : MigrationLocator<TMigrationType> where TMigrationType: class, IMigration { private class TypeComparer : IEqualityComparer<Type> { public bool Equals(Type x, Type y) { return x.AssemblyQualifiedName == y.AssemblyQualifiedName; } public int GetHashCode(Type obj) { return obj.AssemblyQualifiedName.GetHashCode(); } } private readonly IContainerProvider _containerProvider; public TypeMigrationDependencyLocator(IContainerProvider containerProvider) { _containerProvider = containerProvider; } public override void Locate() { var migrationTypes = (from assembly in Assemblies from type in assembly.GetTypes() where typeof(TMigrationType).IsAssignableFrom(type) && !type.IsAbstract select type).Distinct(new TypeComparer()); Migrations = migrationTypes.Select(GetMigrationInstance).ToMigrationDictionary(); } private TMigrationType GetMigrationInstance(Type type) { ConstructorInfo constructor = type.GetConstructors()[0]; if(constructor != null) { object[] args = constructor .GetParameters() .Select(o => o.ParameterType) .Select(o => _containerProvider.GetInstance(o)) .ToArray(); return Activator.CreateInstance(type, args) as TMigrationType; } return Activator.CreateInstance(type) as TMigrationType; } } }
Add an implementation IEqualityComparer<Type> to ensure the .Distinct call in the Locate() method works as expected.
Add an implementation IEqualityComparer<Type> to ensure the .Distinct call in the Locate() method works as expected.
C#
mit
SRoddis/Mongo.Migration
58e535ead38d00cf32154b020d3da4572d856e12
OpenStardriveServer/Domain/Systems/Propulsion/Engines/EnginesState.cs
OpenStardriveServer/Domain/Systems/Propulsion/Engines/EnginesState.cs
using System; using OpenStardriveServer.Domain.Systems.Standard; namespace OpenStardriveServer.Domain.Systems.Propulsion.Engines; public record EnginesState : StandardSystemBaseState { public int CurrentSpeed { get; init; } public EngineSpeedConfig SpeedConfig { get; init; } public int CurrentHeat { get; init; } public EngineHeatConfig HeatConfig { get; init; } public SpeedPowerRequirement[] SpeedPowerRequirements = Array.Empty<SpeedPowerRequirement>(); } public record EngineSpeedConfig { public int MaxSpeed { get; init; } public int CruisingSpeed { get; init; } } public record EngineHeatConfig { public int PoweredHeat { get; init; } public int CruisingHeat { get; init; } public int MaxHeat { get; init; } public int MinutesAtMaxSpeed { get; init; } public int MinutesToCoolDown { get; init; } } public record SpeedPowerRequirement { public int Speed { get; init; } public int PowerNeeded { get; init; } }
using System; using OpenStardriveServer.Domain.Systems.Standard; namespace OpenStardriveServer.Domain.Systems.Propulsion.Engines; public record EnginesState : StandardSystemBaseState { public int CurrentSpeed { get; init; } public EngineSpeedConfig SpeedConfig { get; init; } public int CurrentHeat { get; init; } public EngineHeatConfig HeatConfig { get; init; } public SpeedPowerRequirement[] SpeedPowerRequirements { get; init; } = Array.Empty<SpeedPowerRequirement>(); } public record EngineSpeedConfig { public int MaxSpeed { get; init; } public int CruisingSpeed { get; init; } } public record EngineHeatConfig { public int PoweredHeat { get; init; } public int CruisingHeat { get; init; } public int MaxHeat { get; init; } public int MinutesAtMaxSpeed { get; init; } public int MinutesToCoolDown { get; init; } } public record SpeedPowerRequirement { public int Speed { get; init; } public int PowerNeeded { get; init; } }
Fix bug where prop was not serialized
Fix bug where prop was not serialized
C#
apache-2.0
openstardrive/server,openstardrive/server,openstardrive/server
c84d05076a30141278c23d99f9286c2c8e7c4b53
src/Locking/DistributedAppLockException.cs
src/Locking/DistributedAppLockException.cs
using System; namespace RapidCore.Locking { public class DistributedAppLockException : Exception { public DistributedAppLockException() { } public DistributedAppLockException(string message) : base(message) { } public DistributedAppLockException(string message, Exception inner) : base(message, inner) { } public DistributedAppLockExceptionReason Reason { get; set; } } }
using System; namespace RapidCore.Locking { public class DistributedAppLockException : Exception { public DistributedAppLockException() { } public DistributedAppLockException(string message) : base(message) { } public DistributedAppLockException(string message, DistributedAppLockExceptionReason reason) : base(message) { Reason = reason; } public DistributedAppLockException(string message, Exception inner) : base(message, inner) { } public DistributedAppLockException(string message, Exception inner, DistributedAppLockExceptionReason reason) : base(message, inner) { Reason = reason; } public DistributedAppLockExceptionReason Reason { get; set; } } }
Add overloads to exception to take in the Reason
Add overloads to exception to take in the Reason
C#
mit
rapidcore/rapidcore,rapidcore/rapidcore
afd4740c609eafd48ab4cd6a539db47a3ba3778e
Assets/HoloToolkit/Utilities/Scripts/Extensions/CameraExtensions.cs
Assets/HoloToolkit/Utilities/Scripts/Extensions/CameraExtensions.cs
using UnityEngine; namespace HoloToolkit.Unity { public static class CameraExtensions { /// <summary> /// Get the horizontal FOV from the stereo camera /// </summary> /// <returns></returns> public static float GetHorizontalFieldOfViewRadians(this Camera camera) { float horizontalFovRadians = 2 * Mathf.Atan(Mathf.Tan((camera.fieldOfView * Mathf.Deg2Rad) / 2) * camera.aspect); return horizontalFovRadians; } /// <summary> /// Returns if a point will be rendered on the screen in either eye /// </summary> /// <param name="position"></param> /// <returns></returns> public static bool IsInFOV(this Camera camera, Vector3 position) { float verticalFovHalf = camera.fieldOfView / 2; float horizontalFovHalf = camera.GetHorizontalFieldOfViewRadians() * Mathf.Rad2Deg / 2; Vector3 deltaPos = position - camera.transform.position; Vector3 headDeltaPos = MathUtils.TransformDirectionFromTo(null, camera.transform, deltaPos).normalized; float yaw = Mathf.Asin(headDeltaPos.x) * Mathf.Rad2Deg; float pitch = Mathf.Asin(headDeltaPos.y) * Mathf.Rad2Deg; return (Mathf.Abs(yaw) < horizontalFovHalf && Mathf.Abs(pitch) < verticalFovHalf); } } }
using UnityEngine; namespace HoloToolkit.Unity { public static class CameraExtensions { /// <summary> /// Get the horizontal FOV from the stereo camera /// </summary> /// <returns></returns> public static float GetHorizontalFieldOfViewRadians(this Camera camera) { float horizontalFovRadians = 2f * Mathf.Atan(Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad * 0.5f) * camera.aspect); return horizontalFovRadians; } /// <summary> /// Returns if a point will be rendered on the screen in either eye /// </summary> /// <param name="position"></param> /// <returns></returns> public static bool IsInFOV(this Camera camera, Vector3 position) { float verticalFovHalf = camera.fieldOfView * 0.5f; float horizontalFovHalf = camera.GetHorizontalFieldOfViewRadians() * Mathf.Rad2Deg * 0.5f; Vector3 deltaPos = position - camera.transform.position; Vector3 headDeltaPos = MathUtils.TransformDirectionFromTo(null, camera.transform, deltaPos).normalized; float yaw = Mathf.Asin(headDeltaPos.x) * Mathf.Rad2Deg; float pitch = Mathf.Asin(headDeltaPos.y) * Mathf.Rad2Deg; return (Mathf.Abs(yaw) < horizontalFovHalf && Mathf.Abs(pitch) < verticalFovHalf); } } }
Use floats across the camera calculations /2 > 0.5f
Use floats across the camera calculations /2 > 0.5f
C#
mit
paseb/HoloToolkit-Unity,HoloFan/HoloToolkit-Unity,ForrestTrepte/HoloToolkit-Unity,out-of-pixel/HoloToolkit-Unity,NeerajW/HoloToolkit-Unity,willcong/HoloToolkit-Unity,HattMarris1/HoloToolkit-Unity,dbastienMS/HoloToolkit-Unity,paseb/MixedRealityToolkit-Unity
10c9b3d971757d12f265e18fcf6c86c4c9d959e4
compiler/middleend/ir/ParseResult.cs
compiler/middleend/ir/ParseResult.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace compiler.middleend.ir { class ParseResult { public Operand Operand { get; set; } public List<Instruction> Instructions { get; set; } public Dictionary<SsaVariable, Instruction> VarTable { get; set; } public ParseResult() { Operand = null; Instructions = null; VarTable = new Dictionary<SsaVariable, Instruction>(); } public ParseResult(Dictionary<SsaVariable, Instruction> symTble ) { Operand = null; Instructions = null; VarTable = new Dictionary<SsaVariable, Instruction>(symTble); } public ParseResult(Operand pOperand, List<Instruction> pInstructions, Dictionary<SsaVariable, Instruction> pSymTble) { Operand = pOperand; Instructions = new List<Instruction>(pInstructions); VarTable = new Dictionary<SsaVariable, Instruction>(pSymTble); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace compiler.middleend.ir { class ParseResult { public Operand Operand { get; set; } public List<Instruction> Instructions { get; set; } public Dictionary<int, SsaVariable> VarTable { get; set; } public ParseResult() { Operand = null; Instructions = null; VarTable = new Dictionary<int, SsaVariable>(); } public ParseResult(Dictionary<int, SsaVariable> symTble ) { Operand = null; Instructions = null; VarTable = new Dictionary<int, SsaVariable>(symTble); } public ParseResult(Operand pOperand, List<Instruction> pInstructions, Dictionary<int, SsaVariable> pSymTble) { Operand = pOperand; Instructions = new List<Instruction>(pInstructions); VarTable = new Dictionary<int, SsaVariable>(pSymTble); } } }
Fix Dictionary type to be more useful
Fix Dictionary type to be more useful
C#
mit
ilovepi/Compiler,ilovepi/Compiler
abffd8293bec00982d72d40cd986a950d13122fe
CSharp/SimpleOrderRouting.Journey1/ExecutionState.cs
CSharp/SimpleOrderRouting.Journey1/ExecutionState.cs
namespace SimpleOrderRouting.Journey1 { public class ExecutionState { public ExecutionState(InvestorInstruction investorInstruction) { this.Quantity = investorInstruction.Quantity; this.Price = investorInstruction.Price; this.Way = investorInstruction.Way; this.AllowPartialExecution = investorInstruction.AllowPartialExecution; } public int Quantity { get; set; } public decimal Price { get; set; } public Way Way { get; set; } public bool AllowPartialExecution { get; set; } { this.Quantity -= quantity; } } }
namespace SimpleOrderRouting.Journey1 { public class ExecutionState { public ExecutionState(InvestorInstruction investorInstruction) { this.Quantity = investorInstruction.Quantity; this.Price = investorInstruction.Price; this.Way = investorInstruction.Way; this.AllowPartialExecution = investorInstruction.AllowPartialExecution; } public int Quantity { get; set; } public decimal Price { get; set; } public Way Way { get; set; } public bool AllowPartialExecution { get; set; } public void Executed(int quantity) { this.Quantity -= quantity; } } }
Fix fat-finger made before the previous commit
Fix fat-finger made before the previous commit
C#
apache-2.0
Lunch-box/SimpleOrderRouting
984f9a550bdbcc5e6c293fa62244b22dc605582f
Assets/Scripts/SpecialPowers/PowerRandom.cs
Assets/Scripts/SpecialPowers/PowerRandom.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PowerRandom : BaseSpecialPower { [SerializeField] private List<BaseSpecialPower> powers; private BaseSpecialPower activePower = null; protected override void Start() { base.Start(); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; } protected override void Activate() { StartCoroutine(WaitForDestroy()); } protected override void Update() { if(activePower.mana > 0) { base.Update(); } } IEnumerator WaitForDestroy() { yield return null; while(activePower.coolDownTimer > 0) { yield return null; } float currentMana = activePower.mana; DestroyImmediate(activePower.gameObject); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; yield return null; activePower.mana = currentMana; yield return null; EventDispatcher.DispatchEvent(Events.SPECIAL_POWER_USED, activePower); //to activate the UI } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PowerRandom : BaseSpecialPower { [SerializeField] private List<BaseSpecialPower> powers; private BaseSpecialPower activePower = null; protected override void Start() { base.Start(); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; } protected override void Activate() { if(activePower.coolDownTimer <= 0) StartCoroutine(WaitForDestroy()); } protected override void Update() { if(activePower.mana > 0) { base.Update(); } } IEnumerator WaitForDestroy() { yield return null; while(activePower.coolDownTimer > 0) { yield return null; } float currentMana = activePower.mana; Debug.Log(currentMana); DestroyImmediate(activePower.gameObject); activePower = Instantiate(powers[Random.Range(0, powers.Count)], transform.parent, false) as BaseSpecialPower; yield return null; activePower.mana = currentMana; yield return null; EventDispatcher.DispatchEvent(Events.SPECIAL_POWER_USED, activePower); //to activate the UI } }
Fix random power use when cooldown
Fix random power use when cooldown
C#
mit
solfen/Rogue_Cadet
afb15950afb313a4f26bfdbb39d0666f6500485d
Dasher.Schemata/Schema.cs
Dasher.Schemata/Schema.cs
using System.Collections.Generic; using System.Xml.Linq; using JetBrains.Annotations; namespace Dasher.Schemata { public interface IWriteSchema { /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IWriteSchema CopyTo(SchemaCollection collection); } public interface IReadSchema { bool CanReadFrom(IWriteSchema writeSchema, bool strict); /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IReadSchema CopyTo(SchemaCollection collection); } public abstract class Schema { internal abstract IEnumerable<Schema> Children { get; } public override bool Equals(object obj) { var other = obj as Schema; return other != null && Equals(other); } public abstract bool Equals(Schema other); public override int GetHashCode() => ComputeHashCode(); protected abstract int ComputeHashCode(); } /// <summary>For complex, union and enum.</summary> public abstract class ByRefSchema : Schema { [CanBeNull] internal string Id { get; set; } internal abstract XElement ToXml(); public override string ToString() => Id; } /// <summary>For primitive, nullable, list, dictionary, tuple, empty.</summary> public abstract class ByValueSchema : Schema { internal abstract string MarkupValue { get; } public override string ToString() => MarkupValue; } }
using System.Collections.Generic; using System.Xml.Linq; using JetBrains.Annotations; namespace Dasher.Schemata { public interface IWriteSchema { /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IWriteSchema CopyTo(SchemaCollection collection); } public interface IReadSchema { bool CanReadFrom(IWriteSchema writeSchema, bool strict); /// <summary> /// Creates a deep copy of this schema within <paramref name="collection"/>. /// </summary> /// <param name="collection"></param> /// <returns></returns> IReadSchema CopyTo(SchemaCollection collection); } public abstract class Schema { internal abstract IEnumerable<Schema> Children { get; } public override bool Equals(object obj) { var other = obj as Schema; return other != null && Equals(other); } public abstract bool Equals(Schema other); public override int GetHashCode() => ComputeHashCode(); protected abstract int ComputeHashCode(); } /// <summary>For complex, union and enum.</summary> public abstract class ByRefSchema : Schema { [CanBeNull] internal string Id { get; set; } internal abstract XElement ToXml(); public override string ToString() => Id ?? GetType().Name; } /// <summary>For primitive, nullable, list, dictionary, tuple, empty.</summary> public abstract class ByValueSchema : Schema { internal abstract string MarkupValue { get; } public override string ToString() => MarkupValue; } }
Improve ToString when Id is null
Improve ToString when Id is null
C#
apache-2.0
drewnoakes/dasher
740a6d9bb52fd9ea8894de60df87f585a91db7d8
MobileDeviceDetector/Rules/Conditions/UserAgentCondition.cs
MobileDeviceDetector/Rules/Conditions/UserAgentCondition.cs
namespace Sitecore.SharedSource.MobileDeviceDetector.Rules.Conditions { using System; using System.Web; using Sitecore.Diagnostics; using Sitecore.Rules; using Sitecore.Rules.Conditions; /// <summary> /// UserAgentCondition /// </summary> /// <typeparam name="T"></typeparam> public class UserAgentCondition<T> : StringOperatorCondition<T> where T : RuleContext { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> public string Value { get; set; } /// <summary> /// Executes the specified rule context. /// </summary> /// <param name="ruleContext">The rule context.</param> /// <returns>Returns value indicating whether Device UserAgent matches Value or not</returns> protected override bool Execute(T ruleContext) { Assert.ArgumentNotNull(ruleContext, "ruleContext"); string str = this.Value ?? string.Empty; var userAgent = HttpContext.Current.Request.UserAgent; if (!string.IsNullOrEmpty(userAgent)) { return userAgent.IndexOf(str, StringComparison.OrdinalIgnoreCase) >= 0; } return false; } } }
namespace Sitecore.SharedSource.MobileDeviceDetector.Rules.Conditions { using System; using System.Web; using Sitecore.Diagnostics; using Sitecore.Rules; using Sitecore.Rules.Conditions; /// <summary> /// UserAgentCondition /// </summary> /// <typeparam name="T"></typeparam> public class UserAgentCondition<T> : StringOperatorCondition<T> where T : RuleContext { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> public string Value { get; set; } /// <summary> /// Executes the specified rule context. /// </summary> /// <param name="ruleContext">The rule context.</param> /// <returns>Returns value indicating whether Device UserAgent matches Value or not</returns> protected override bool Execute(T ruleContext) { Assert.ArgumentNotNull(ruleContext, "ruleContext"); string str = this.Value ?? string.Empty; var userAgent = HttpContext.Current.Request.UserAgent; if (!string.IsNullOrEmpty(userAgent)) { return Compare(str, userAgent); } return false; } } }
Support full range of comparison operators instead of IndexOf
Support full range of comparison operators instead of IndexOf
C#
mit
adoprog/Sitecore-Mobile-Device-Detector
57b0821e19d6d54ca7c83e7ffb74f43605846e8b
Core/Utils/WindowsUtils.cs
Core/Utils/WindowsUtils.cs
using System.Diagnostics; using System.IO; using System.Security.AccessControl; using System.Security.Principal; namespace TweetDck.Core.Utils{ static class WindowsUtils{ public static bool CheckFolderPermission(string path, FileSystemRights right){ try{ AuthorizationRuleCollection collection = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(NTAccount)); foreach(FileSystemAccessRule rule in collection){ if ((rule.FileSystemRights & right) == right){ return true; } } return false; } catch{ return false; } } public static Process StartProcess(string file, string arguments, bool runElevated){ ProcessStartInfo processInfo = new ProcessStartInfo{ FileName = file, Arguments = arguments }; if (runElevated){ processInfo.Verb = "runas"; } return Process.Start(processInfo); } } }
using System.Diagnostics; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; namespace TweetDck.Core.Utils{ static class WindowsUtils{ public static bool CheckFolderPermission(string path, FileSystemRights right){ try{ AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(SecurityIdentifier)); WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (identity.Groups == null){ return false; } bool accessAllow = false, accessDeny = false; foreach(FileSystemAccessRule rule in rules.Cast<FileSystemAccessRule>().Where(rule => identity.Groups.Contains(rule.IdentityReference) && (right & rule.FileSystemRights) == right)){ switch(rule.AccessControlType){ case AccessControlType.Allow: accessAllow = true; break; case AccessControlType.Deny: accessDeny = true; break; } } return accessAllow && !accessDeny; } catch{ return false; } } public static Process StartProcess(string file, string arguments, bool runElevated){ ProcessStartInfo processInfo = new ProcessStartInfo{ FileName = file, Arguments = arguments }; if (runElevated){ processInfo.Verb = "runas"; } return Process.Start(processInfo); } } }
Revert "Rewrite folder write permission check to hopefully make it more reliable"
Revert "Rewrite folder write permission check to hopefully make it more reliable" This reverts commit 1f9db3bda6a457f019c301208e9fa3bf4f5197fb.
C#
mit
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
39cfe75b9c2857f54b67fbb2aee1971bdece8cd3
Mollie.Api/Models/Connect/AppPermissions.cs
Mollie.Api/Models/Connect/AppPermissions.cs
namespace Mollie.Api.Models.Connect { public static class AppPermissions { public const string PaymentsRead = "payments.read"; public const string PaymentsWrite = "payments.write"; public const string RefundsRead = "refunds.read"; public const string RefundsWrite = "refunds.write"; public const string CustomersRead = "customers.read"; public const string CustomersWrite = "customers.write"; public const string MandatesRead = "mandates.read"; public const string MandatesWrite = "mandates.write"; public const string SubscriptionsRead = "subscriptions.read"; public const string SubscriptionsWrite = "subscriptions.write"; public const string ProfilesRead = "profiles.read"; public const string ProfilesWrite = "profiles.write"; public const string InvoicesRead = "invoices.read"; public const string OrdersRead = "orders.read"; public const string OrdersWrite = "orders.write"; public const string ShipmentsRead = "shipments.read"; public const string ShipmentsWrite = "shipments.write"; public const string OrganizationRead = "organizations.read"; public const string OrganizationWrite = "organizations.write"; public const string OnboardingRead = "onboarding.write"; public const string OnboardingWrite = "onboarding.write"; } }
namespace Mollie.Api.Models.Connect { public static class AppPermissions { public const string PaymentsRead = "payments.read"; public const string PaymentsWrite = "payments.write"; public const string RefundsRead = "refunds.read"; public const string RefundsWrite = "refunds.write"; public const string CustomersRead = "customers.read"; public const string CustomersWrite = "customers.write"; public const string MandatesRead = "mandates.read"; public const string MandatesWrite = "mandates.write"; public const string SubscriptionsRead = "subscriptions.read"; public const string SubscriptionsWrite = "subscriptions.write"; public const string ProfilesRead = "profiles.read"; public const string ProfilesWrite = "profiles.write"; public const string InvoicesRead = "invoices.read"; public const string OrdersRead = "orders.read"; public const string OrdersWrite = "orders.write"; public const string ShipmentsRead = "shipments.read"; public const string ShipmentsWrite = "shipments.write"; public const string OrganizationRead = "organizations.read"; public const string OrganizationWrite = "organizations.write"; public const string OnboardingRead = "onboarding.read"; public const string OnboardingWrite = "onboarding.write"; public const string SettlementsRead = "settlements.read"; } }
Fix typo in OnboardingRead and add SettlementsRead
Fix typo in OnboardingRead and add SettlementsRead
C#
mit
Viincenttt/MollieApi,Viincenttt/MollieApi
c420f373a5ddc8050a2d3f419282feb2c41326fa
Solutions/Endjin.Cancelable.Demo/Program.cs
Solutions/Endjin.Cancelable.Demo/Program.cs
namespace Endjin.Cancelable.Demo { #region Using Directives using System; using System.Threading; using System.Threading.Tasks; using Endjin.Contracts; using Endjin.Core.Composition; using Endjin.Core.Container; #endregion public class Program { public static void Main(string[] args) { ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait(); var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>(); var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045"; cancelable.CreateToken(cancellationToken); cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait(); Console.WriteLine("Press Any Key to Exit!"); Console.ReadKey(); } private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken) { int counter = 0; while (!cancellationToken.IsCancellationRequested) { Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T")); await Task.Delay(TimeSpan.FromSeconds(1)); counter++; if (counter == 15) { Console.WriteLine("Long Running Process Ran to Completion!"); break; } } if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Long Running Process was Cancelled!"); } } } }
namespace Endjin.Cancelable.Demo { #region Using Directives using System; using System.Threading; using System.Threading.Tasks; using Endjin.Contracts; using Endjin.Core.Composition; using Endjin.Core.Container; #endregion public class Program { public static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("Ensure you are running the Azure Storage Emulator!"); Console.ResetColor(); ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait(); var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>(); var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045"; cancelable.CreateToken(cancellationToken); cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait(); Console.WriteLine("Press Any Key to Exit!"); Console.ReadKey(); } private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken) { int counter = 0; while (!cancellationToken.IsCancellationRequested) { Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T")); await Task.Delay(TimeSpan.FromSeconds(1)); counter++; if (counter == 15) { Console.WriteLine("Long Running Process Ran to Completion!"); break; } } if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Long Running Process was Cancelled!"); } } } }
Add warning message to ensure user is running the Azure Emulator
Add warning message to ensure user is running the Azure Emulator
C#
mit
endjin/Endjin.Cancelable,endjin/Endjin.Cancelable
d131cf24f0be5eb9c79c7eaa7e390b78a9303b7c
ExtensionSample/Program.cs
ExtensionSample/Program.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; using System.Net.Mail; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions; using Microsoft.Azure.WebJobs.Host; using OutgoingHttpRequestWebJobsExtension; namespace ExtensionsSample { public static class Program { public static void Main(string[] args) { var config = new JobHostConfiguration(); config.UseDevelopmentSettings(); config.UseOutgoingHttpRequests(); var host = new JobHost(config); var method = typeof(Program).GetMethod("MyCoolMethod"); host.Call(method); } public static void MyCoolMethod( [OutgoingHttpRequest(@"http://requestb.in/19xvbmc1")] TextWriter writer) { writer.Write("Test sring sent to OutgoingHttpRequest!"); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using Microsoft.Azure.WebJobs; using OutgoingHttpRequestWebJobsExtension; namespace ExtensionsSample { public static class Program { public static void Main(string[] args) { string inputString = args.Length > 0 ? args[0] : "Some test string"; var config = new JobHostConfiguration(); config.UseDevelopmentSettings(); config.UseOutgoingHttpRequests(); var host = new JobHost(config); var method = typeof(Program).GetMethod("MyCoolMethod"); host.Call(method, new Dictionary<string, object> { {"input", inputString } }); } public static void MyCoolMethod( string input, [OutgoingHttpRequest(@"http://requestb.in/19xvbmc1")] TextWriter writer, TextWriter logger) { logger.Write(input); writer.Write(input); } } }
Add input param. logger and get test string from cmd line
Add input param. logger and get test string from cmd line
C#
apache-2.0
davidebbo/OutgoingHttpRequestWebJobsExtension
a772ca5acffd65cb216aa4078f3eb4152f025830
Client/Skybox.cs
Client/Skybox.cs
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace ShiftDrive { /// <summary> /// Contains static utilities to render a skybox. /// </summary> internal static class Skybox { private static float rotation; private static bool idleRotation; public static void SetIdleRotation(bool enabled) { idleRotation = enabled; } public static void Draw(GraphicsDevice graphicsDevice) { // Use the unlit shader to render a skybox. Effect fx = Assets.fxUnlit; // shortcut fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) * Matrix.CreateLookAt(new Vector3(0f, -0.2f, 2f), new Vector3(0, 0, 0), Vector3.Up) * SDGame.Inst.Projection); fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]); foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { part.Effect = fx; } fx.CurrentTechnique.Passes[0].Apply(); mesh.Draw(); } } public static void Update(GameTime gameTime) { if (!idleRotation) return; rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.05); while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace ShiftDrive { /// <summary> /// Contains static utilities to render a skybox. /// </summary> internal static class Skybox { private static float rotation; private static bool idleRotation; public static void SetIdleRotation(bool enabled) { idleRotation = enabled; } public static void Draw(GraphicsDevice graphicsDevice) { // Use the unlit shader to render a skybox. Effect fx = Assets.fxUnlit; // shortcut fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) * Matrix.CreateRotationZ(rotation) * Matrix.CreateLookAt(new Vector3(0f, -0.25f, 2f), new Vector3(0, 0, 0), Vector3.Up) * SDGame.Inst.Projection); fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]); foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { part.Effect = fx; } fx.CurrentTechnique.Passes[0].Apply(); mesh.Draw(); } } public static void Update(GameTime gameTime) { if (!idleRotation) return; rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.04); while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi; } } }
Tweak skybox rotation direction and speed
Tweak skybox rotation direction and speed
C#
bsd-3-clause
iridinite/shiftdrive
574ca1f4824549b5542985f873d231a80392beba
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists"; public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists"; public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache"; } }
Update nullable annotations in Experiments folder
Update nullable annotations in Experiments folder
C#
mit
wvdd007/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,jmarolf/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,genlu/roslyn,weltkante/roslyn,KevinRansom/roslyn,tmat/roslyn,genlu/roslyn,panopticoncentral/roslyn,brettfo/roslyn,diryboy/roslyn,dotnet/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,AmadeusW/roslyn,jmarolf/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,wvdd007/roslyn,weltkante/roslyn,bartdesmet/roslyn,diryboy/roslyn,aelij/roslyn,tmat/roslyn,gafter/roslyn,heejaechang/roslyn,brettfo/roslyn,sharwell/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,physhi/roslyn,genlu/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,gafter/roslyn,mgoertz-msft/roslyn,physhi/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,sharwell/roslyn,mavasani/roslyn,stephentoub/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,weltkante/roslyn,heejaechang/roslyn,tannergooding/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,gafter/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,heejaechang/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,tannergooding/roslyn,tmat/roslyn,tannergooding/roslyn
d3058c5cd2ca1820178e6ac61c7121f1b8f7ecbb
src/AppHarbor/Commands/AddHostnameCommand.cs
src/AppHarbor/Commands/AddHostnameCommand.cs
using System; namespace AppHarbor.Commands { public class AddHostnameCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
using System; namespace AppHarbor.Commands { public class AddHostnameCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("No hostname was specified"); } throw new NotImplementedException(); } } }
Throw a CommandException if no hostname is specified
Throw a CommandException if no hostname is specified
C#
mit
appharbor/appharbor-cli
f09a4e9c5b0e5507d9d3a22b92682a2190030832
osu.Game/Configuration/DevelopmentOsuConfigManager.cs
osu.Game/Configuration/DevelopmentOsuConfigManager.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { LookupKeyBindings = _ => "unknown"; LookupSkinName = _ => "unknown"; } } }
Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available
Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available
C#
mit
peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu
b2059f29b97037e509186cc378297890d60327d4
src/Winium.Desktop.Driver/CommandExecutors/SendKeysToElementExecutor.cs
src/Winium.Desktop.Driver/CommandExecutors/SendKeysToElementExecutor.cs
namespace Winium.Desktop.Driver.CommandExecutors { internal class SendKeysToElementExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var text = this.ExecutedCommand.Parameters["value"].First.ToString(); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); element.SetText(text); return this.JsonResponse(); } #endregion } }
namespace Winium.Desktop.Driver.CommandExecutors { internal class SendKeysToElementExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var text = string.Join(string.Empty, this.ExecutedCommand.Parameters["value"]); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); element.SetText(text); return this.JsonResponse(); } #endregion } }
Fix for wrong keys when using python binding
Fix for wrong keys when using python binding
C#
mpl-2.0
zebraxxl/Winium.Desktop,2gis/Winium.Desktop,jorik041/Winium.Desktop
16f9dd44521306d464aa7f6b65b28025ba77e865
exercises/robot-name/RobotNameTest.cs
exercises/robot-name/RobotNameTest.cs
using Xunit; public class RobotNameTest { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"[A-Z]{2}\d{3}", robot.Name); } [Fact(Skip = "Remove to run test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } }
using Xunit; public class RobotNameTest { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove to run test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } }
Update RobotName name test to be more restrictive
Update RobotName name test to be more restrictive Previously the tests would not catch invalid robot names such as AB1234, or ABC123 because the regex did not have start or end anchors specified. This commit updates the regex so that those names are no longer accepted by the tests.
C#
mit
robkeim/xcsharp,exercism/xcsharp,ErikSchierboom/xcsharp,ErikSchierboom/xcsharp,exercism/xcsharp,robkeim/xcsharp
233caa379d180d18093c1ce69ae968d15eb5014c
NReplayGain/AlbumGain.cs
NReplayGain/AlbumGain.cs
using System; using System.Linq; namespace NReplayGain { /// <summary> /// Contains ReplayGain data for an album. /// </summary> public class AlbumGain { private GainData albumData; public AlbumGain() { this.albumData = new GainData(); } /// <summary> /// After calculating the ReplayGain data for an album, call this to append the data to the album. /// </summary> public void AppendTrackData(TrackGain trackGain) { int[] sourceAccum = trackGain.gainData.Accum; for (int i = 0; i < sourceAccum.Length; ++i) { this.albumData.Accum[i] = sourceAccum[i]; } this.albumData.PeakSample = Math.Max(this.albumData.PeakSample, trackGain.gainData.PeakSample); } /// <summary> /// Returns the normalization gain for the entire album in decibels. /// </summary> public double GetGain() { return ReplayGain.AnalyzeResult(this.albumData.Accum); } /// <summary> /// Returns the peak album value, normalized to the [0,1] interval. /// </summary> public double GetPeak() { return this.albumData.PeakSample / ReplayGain.MAX_SAMPLE_VALUE; } } }
using System; using System.Linq; namespace NReplayGain { /// <summary> /// Contains ReplayGain data for an album. /// </summary> public class AlbumGain { private GainData albumData; public AlbumGain() { this.albumData = new GainData(); } /// <summary> /// After calculating the ReplayGain data for an album, call this to append the data to the album. /// </summary> public void AppendTrackData(TrackGain trackGain) { int[] sourceAccum = trackGain.gainData.Accum; for (int i = 0; i < sourceAccum.Length; ++i) { this.albumData.Accum[i] += sourceAccum[i]; } this.albumData.PeakSample = Math.Max(this.albumData.PeakSample, trackGain.gainData.PeakSample); } /// <summary> /// Returns the normalization gain for the entire album in decibels. /// </summary> public double GetGain() { return ReplayGain.AnalyzeResult(this.albumData.Accum); } /// <summary> /// Returns the peak album value, normalized to the [0,1] interval. /// </summary> public double GetPeak() { return this.albumData.PeakSample / ReplayGain.MAX_SAMPLE_VALUE; } } }
Fix bug in album gain calculation.
Fix bug in album gain calculation.
C#
lgpl-2.1
karamanolev/NReplayGain
5d4aa97f00d2fff23cdd18a5b75f297c07b39f52
src/web/Extensions/SitePageRouteConstraint.cs
src/web/Extensions/SitePageRouteConstraint.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Routing; namespace wwwplatform.Extensions { public class SitePageRouteConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { string path = httpContext.Request.Url.AbsolutePath; string controller = path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First(); var controllers = Assembly.GetExecutingAssembly().DefinedTypes.Where(t => t.Name.EndsWith("Controller") && t.Name.StartsWith(controller)); return controllers.Count() == 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Routing; namespace wwwplatform.Extensions { public class SitePageRouteConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { string path = httpContext.Request.Url.AbsolutePath; string controller = path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First(); var controllers = Assembly.GetExecutingAssembly().DefinedTypes.Where(t => t.Name.EndsWith("Controller") && t.Name.StartsWith(controller, StringComparison.InvariantCultureIgnoreCase)); return controllers.Count() == 0; } } }
Fix route matching for typed-in urls
Fix route matching for typed-in urls
C#
apache-2.0
brondavies/wwwplatform.net,brondavies/wwwplatform.net,brondavies/wwwplatform.net
9cfa83ad5bdaa43722b1931463688f0cfd6bd67f
src/Qowaiv.ComponentModel/Result_T.cs
src/Qowaiv.ComponentModel/Result_T.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Qowaiv.ComponentModel { /// <summary>Represents a result of a validation, executed command, etcetera.</summary> public class Result<T> : Result { /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> public Result(T data) : this(data, Enumerable.Empty<ValidationResult>()) { } /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> /// <param name="messages"> /// The messages related to the result. /// </param> public Result(T data, IEnumerable<ValidationResult> messages) : base(messages) { Data = data; } /// <summary>Gets the data related to result.</summary> public T Data { get; } /// <summary>Implicitly casts the <see cref="Result"/> to the type of the related model.</summary> public static implicit operator T(Result<T> result) => result == null ? default(T) : result.Data; /// <summary>Implicitly casts a model to the <see cref="Result"/>.</summary> public static explicit operator Result<T>(T model) => new Result<T>(model); } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Qowaiv.ComponentModel { /// <summary>Represents a result of a validation, executed command, etcetera.</summary> public class Result<T> : Result { /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> public Result(IEnumerable<ValidationResult> messages) : this(default(T), messages) { } /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> public Result(T data) : this(data, Enumerable.Empty<ValidationResult>()) { } /// <summary>Creates a new instance of a <see cref="Result{T}"/>.</summary> /// <param name="data"> /// The data related to the result. /// </param> /// <param name="messages"> /// The messages related to the result. /// </param> public Result(T data, IEnumerable<ValidationResult> messages) : base(messages) { Data = data; } /// <summary>Gets the data related to result.</summary> public T Data { get; } /// <summary>Implicitly casts a model to the <see cref="Result"/>.</summary> public static implicit operator Result<T>(T model) => new Result<T>(model); /// <summary>Explicitly casts the <see cref="Result"/> to the type of the related model.</summary> public static explicit operator T(Result<T> result) => result == null ? default(T) : result.Data; } }
Add a constructor that only requires messages.
Add a constructor that only requires messages.
C#
mit
Qowaiv/Qowaiv
bf5af3310aa1d643e08a0135531fff7b9aff9416
osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/BreakPart.cs
osu.Game/Screens/Edit/Components/Timelines/Summary/Parts/BreakPart.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Beatmaps.Timing; using osu.Game.Graphics; using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// The part of the timeline that displays breaks in the song. /// </summary> public class BreakPart : TimelinePart { protected override void LoadBeatmap(EditorBeatmap beatmap) { base.LoadBeatmap(beatmap); foreach (var breakPeriod in beatmap.Breaks) Add(new BreakVisualisation(breakPeriod)); } private class BreakVisualisation : DurationVisualisation { public BreakVisualisation(BreakPeriod breakPeriod) : base(breakPeriod.StartTime, breakPeriod.EndTime) { } [BackgroundDependencyLoader] private void load(OsuColour colours) => Colour = colours.Yellow; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Beatmaps.Timing; using osu.Game.Graphics; using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations; namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts { /// <summary> /// The part of the timeline that displays breaks in the song. /// </summary> public class BreakPart : TimelinePart { protected override void LoadBeatmap(EditorBeatmap beatmap) { base.LoadBeatmap(beatmap); foreach (var breakPeriod in beatmap.Breaks) Add(new BreakVisualisation(breakPeriod)); } private class BreakVisualisation : DurationVisualisation { public BreakVisualisation(BreakPeriod breakPeriod) : base(breakPeriod.StartTime, breakPeriod.EndTime) { } [BackgroundDependencyLoader] private void load(OsuColour colours) => Colour = colours.GreyCarmineLight; } } }
Update break colour to not look like kiai time
Update break colour to not look like kiai time
C#
mit
NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu
a02a9634a72e6afddc54ffd3fe8f2b66ed38ddbf
Cqrs/Framework/Cqrs.Ninject/Configuration/NinjectDependencyResolver.cs
Cqrs/Framework/Cqrs.Ninject/Configuration/NinjectDependencyResolver.cs
using System; using System.Linq; using Cqrs.Configuration; using Ninject; using Ninject.Parameters; namespace Cqrs.Ninject.Configuration { public class NinjectDependencyResolver : IServiceLocator { public static IServiceLocator Current { get; private set; } static NinjectDependencyResolver() { Current = new NinjectDependencyResolver(new StandardKernel()); } protected IKernel Kernel { get; private set; } public NinjectDependencyResolver(IKernel kernel) { Kernel = kernel; } /// <summary> /// Starts the <see cref="NinjectDependencyResolver"/> /// </summary> /// <remarks> /// this exists to the static constructor can be triggered. /// </remarks> public static void Start() { } public T GetService<T>() { return Resolve<T>(); } public object GetService(Type type) { return Resolve(type); } protected T Resolve<T>() { return (T)Resolve(typeof(T)); } protected object Resolve(Type serviceType) { return Kernel.Resolve(Kernel.CreateRequest(serviceType, null, new Parameter[0], true, true)).SingleOrDefault(); } } }
using System; using System.Linq; using Cqrs.Configuration; using Ninject; using Ninject.Parameters; namespace Cqrs.Ninject.Configuration { public class NinjectDependencyResolver : IServiceLocator { public static IServiceLocator Current { get; protected set; } static NinjectDependencyResolver() { Current = new NinjectDependencyResolver(new StandardKernel()); } protected IKernel Kernel { get; private set; } public NinjectDependencyResolver(IKernel kernel) { Kernel = kernel; } /// <summary> /// Starts the <see cref="NinjectDependencyResolver"/> /// </summary> /// <remarks> /// this exists to the static constructor can be triggered. /// </remarks> public static void Start() { } public T GetService<T>() { return Resolve<T>(); } public object GetService(Type type) { return Resolve(type); } protected T Resolve<T>() { return (T)Resolve(typeof(T)); } protected object Resolve(Type serviceType) { return Kernel.Resolve(Kernel.CreateRequest(serviceType, null, new Parameter[0], true, true)).SingleOrDefault(); } } }
Allow the static property to be protected
Allow the static property to be protected git-svn-id: d0def854dd7af056e86ca9c2262ea22710193966@122 72444466-9f5c-4d9b-9c6f-db583910f96c
C#
lgpl-2.1
cdmdotnet/CQRS,Chinchilla-Software-Com/CQRS
d68b3004f093cdf67a787b8068a21a7e76193a59
src/LondonTravel.Site/Views/Shared/Error.cshtml
src/LondonTravel.Site/Views/Shared/Error.cshtml
@model int? @{ ViewBag.Title = "Error"; ViewBag.Message = ViewBag.Message ?? "An error occurred while processing your request."; } <h1 class="text-danger">Error (HTTP @(Model ?? 500))</h1> <h2 class="text-danger">@ViewBag.Message</h2>
@model int? @{ ViewBag.MetaDescription = string.Empty; ViewBag.MetaRobots = "NOINDEX"; ViewBag.Title = "Error"; ViewBag.Message = ViewBag.Message ?? "An error occurred while processing your request."; } <h1 class="text-danger">Error (HTTP @(Model ?? 500))</h1> <h2 class="text-danger">@ViewBag.Message</h2>
Add NOINDEX to error pages
Add NOINDEX to error pages Add NOINDEX for robots to error pages.
C#
apache-2.0
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
2ba88923b624d012c69c99d40b834beab47e407e
osu.Game/Overlays/OverlayRulesetSelector.cs
osu.Game/Overlays/OverlayRulesetSelector.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.UserInterface; using osu.Game.Rulesets; using osuTK; namespace osu.Game.Overlays { public class OverlayRulesetSelector : RulesetSelector { public OverlayRulesetSelector() { AutoSizeAxes = Axes.Both; } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new OverlayRulesetTabItem(value); protected override TabFillFlowContainer CreateTabFlow() => new TabFillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(20, 0), }; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Rulesets; using osuTK; namespace osu.Game.Overlays { public class OverlayRulesetSelector : RulesetSelector { public OverlayRulesetSelector() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(RulesetStore store, IAPIProvider api) { var preferredRuleset = store.GetRuleset(api.LocalUser.Value.PlayMode); if (preferredRuleset != null) Current.Value = preferredRuleset; } protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new OverlayRulesetTabItem(value); protected override TabFillFlowContainer CreateTabFlow() => new TabFillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(20, 0), }; } }
Select user preferred ruleset on overlay ruleset selectors initially
Select user preferred ruleset on overlay ruleset selectors initially
C#
mit
smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu
ce735eef51106ebf750c414eab2357409879ea19
osu.Framework/Graphics/Shaders/UniformMapping.cs
osu.Framework/Graphics/Shaders/UniformMapping.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; namespace osu.Framework.Graphics.Shaders { /// <summary> /// A mapping of a global uniform to many shaders which need to receive updates on a change. /// </summary> internal class UniformMapping<T> : IUniformMapping where T : struct { public T Value; public List<GlobalUniform<T>> LinkedUniforms = new List<GlobalUniform<T>>(); public string Name { get; } public UniformMapping(string name) { Name = name; } public void LinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; typedUniform.UpdateValue(this); LinkedUniforms.Add(typedUniform); } public void UnlinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; LinkedUniforms.Remove(typedUniform); } public void UpdateValue(ref T newValue) { Value = newValue; // Iterate by index to remove an enumerator allocation // ReSharper disable once ForCanBeConvertedToForeach for (int i = 0; i < LinkedUniforms.Count; i++) LinkedUniforms[i].UpdateValue(this); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; namespace osu.Framework.Graphics.Shaders { /// <summary> /// A mapping of a global uniform to many shaders which need to receive updates on a change. /// </summary> internal class UniformMapping<T> : IUniformMapping where T : struct { public T Value; public List<GlobalUniform<T>> LinkedUniforms = new List<GlobalUniform<T>>(); public string Name { get; } public UniformMapping(string name) { Name = name; } public void LinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; typedUniform.UpdateValue(this); LinkedUniforms.Add(typedUniform); } public void UnlinkShaderUniform(IUniform uniform) { var typedUniform = (GlobalUniform<T>)uniform; LinkedUniforms.Remove(typedUniform); } public void UpdateValue(ref T newValue) { Value = newValue; for (int i = 0; i < LinkedUniforms.Count; i++) LinkedUniforms[i].UpdateValue(this); } } }
Remove no longer necessary comment
Remove no longer necessary comment
C#
mit
ppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework
19aae9aebc64c681bd3ae140e82e76baa0701cd0
PalasoUIWindowsForms/HtmlBrowser/IWebBrowser.cs
PalasoUIWindowsForms/HtmlBrowser/IWebBrowser.cs
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Windows.Forms; namespace Palaso.UI.WindowsForms.HtmlBrowser { public interface IWebBrowser { bool CanGoBack { get; } bool CanGoForward { get; } string DocumentText { set; } string DocumentTitle { get; } bool Focused { get; } bool IsBusy { get; } bool IsWebBrowserContextMenuEnabled { get; set; } string StatusText { get; } Uri Url { get; set; } bool GoBack(); bool GoForward(); void Navigate(string urlString); void Navigate(Uri url); void Refresh(); void Refresh(WebBrowserRefreshOption opt); void Stop(); void ScrollLastElementIntoView(); object NativeBrowser { get; } } }
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Windows.Forms; namespace Palaso.UI.WindowsForms.HtmlBrowser { public interface IWebBrowser { bool CanGoBack { get; } bool CanGoForward { get; } /// <summary> /// Set of the DocumentText will load the given string content into the browser. /// If a get for DocumentText proves necessary Jason promises to write the reflective /// gecko implementation. /// </summary> string DocumentText { set; } string DocumentTitle { get; } bool Focused { get; } bool IsBusy { get; } bool IsWebBrowserContextMenuEnabled { get; set; } string StatusText { get; } Uri Url { get; set; } bool GoBack(); bool GoForward(); void Navigate(string urlString); void Navigate(Uri url); void Refresh(); void Refresh(WebBrowserRefreshOption opt); void Stop(); void ScrollLastElementIntoView(); object NativeBrowser { get; } } }
Document a promise to reintroduce the DocumentText get
Document a promise to reintroduce the DocumentText get
C#
mit
darcywong00/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,darcywong00/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,gtryus/libpalaso,JohnThomson/libpalaso,darcywong00/libpalaso,tombogle/libpalaso,hatton/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,glasseyes/libpalaso,hatton/libpalaso,chrisvire/libpalaso,sillsdev/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,mccarthyrb/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,gtryus/libpalaso
85b413c519267c75c130cecee2a5175a52bf0070
AgileMapper.UnitTests/WhenViewingMappingPlans.cs
AgileMapper.UnitTests/WhenViewingMappingPlans.cs
namespace AgileObjects.AgileMapper.UnitTests { using System.Collections.Generic; using Shouldly; using TestClasses; using Xunit; public class WhenViewingMappingPlans { [Fact] public void ShouldIncludeASimpleTypeMemberMapping() { var plan = Mapper .GetPlanFor<PublicField<string>>() .ToANew<PublicProperty<string>>(); plan.ShouldContain("instance.Value = omc.Source.Value;"); } [Fact] public void ShouldIncludeAComplexTypeMemberMapping() { var plan = Mapper .GetPlanFor<PersonViewModel>() .ToANew<Person>(); plan.ShouldContain("instance.Name = omc.Source.Name;"); plan.ShouldContain("instance.Line1 = omc.Source.AddressLine1;"); } [Fact] public void ShouldIncludeASimpleTypeEnumerableMemberMapping() { var plan = Mapper .GetPlanFor<PublicProperty<int[]>>() .ToANew<PublicField<IEnumerable<int>>>(); plan.ShouldContain("omc.Source.ForEach"); plan.ShouldContain("instance.Add"); } } }
namespace AgileObjects.AgileMapper.UnitTests { using System; using System.Collections.Generic; using Shouldly; using TestClasses; using Xunit; public class WhenViewingMappingPlans { [Fact] public void ShouldIncludeASimpleTypeMemberMapping() { var plan = Mapper .GetPlanFor<PublicField<string>>() .ToANew<PublicProperty<string>>(); plan.ShouldContain("instance.Value = omc.Source.Value;"); } [Fact] public void ShouldIncludeAComplexTypeMemberMapping() { var plan = Mapper .GetPlanFor<PersonViewModel>() .ToANew<Person>(); plan.ShouldContain("instance.Name = omc.Source.Name;"); plan.ShouldContain("instance.Line1 = omc.Source.AddressLine1;"); } [Fact] public void ShouldIncludeASimpleTypeEnumerableMemberMapping() { var plan = Mapper .GetPlanFor<PublicProperty<int[]>>() .ToANew<PublicField<IEnumerable<int>>>(); plan.ShouldContain("omc.Source.ForEach"); plan.ShouldContain("instance.Add"); } [Fact] public void ShouldIncludeASimpleTypeMemberConversion() { var plan = Mapper .GetPlanFor<PublicProperty<Guid>>() .ToANew<PublicField<string>>(); plan.ShouldContain("omc.Source.Value.ToString("); } } }
Test coverage for viewing a simple type member conversion in a mapping plan
Test coverage for viewing a simple type member conversion in a mapping plan
C#
mit
agileobjects/AgileMapper
88aea3d6e55a4d3cd468c71e8522ac1d55f9fbee
BitCommitment/BitCommitmentProvider.cs
BitCommitment/BitCommitmentProvider.cs
using System; namespace BitCommitment { /// <summary> /// A class to perform bit commitment. It does not care what the input is; it's just a /// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way /// function method for committing bits /// </summary> public class BitCommitmentProvider { public byte[] AliceRandBytes1 { get; set; } public byte[] AliceRandBytes2 { get; set; } public byte[] AliceMessageBytesBytes { get; set; } public BitCommitmentProvider(byte[] one, byte[] two, byte[] messageBytes) { AliceRandBytes1 = one; AliceRandBytes2 = two; AliceMessageBytesBytes = messageBytes; } public byte[] BitCommitMessage() { throw new NotImplementedException(); } } }
using System; namespace BitCommitment { /// <summary> /// A class to perform bit commitment. It does not care what the input is; it's just a /// facility for exchanging bit commitment messages. Based on Bruce Schneier's RandBytes1-way /// function method for committing bits /// </summary> public class BitCommitmentProvider { public byte[] AliceRandBytes1 { get; set; } public byte[] AliceRandBytes2 { get; set; } public byte[] AliceBytesToCommitBytesToCommit { get; set; } public BitCommitmentProvider(byte[] randBytes1, byte[] randBytes2, byte[] bytesToCommit) { AliceRandBytes1 = randBytes1; AliceRandBytes2 = randBytes2; AliceBytesToCommitBytesToCommit = bytesToCommit; } public byte[] BitCommitMessage() { throw new NotImplementedException(); } } }
Refactor to make steps of protocol clearer
Refactor to make steps of protocol clearer
C#
mit
0culus/ElectronicCash
e8fb6859789491e76e2fd8abf0a1e0fde7d4ee66
BobTheBuilder/Syntax/DynamicBuilder.cs
BobTheBuilder/Syntax/DynamicBuilder.cs
using System.Dynamic; using BobTheBuilder.ArgumentStore; namespace BobTheBuilder.Syntax { public class DynamicBuilder<T> : DynamicBuilderBase<T> where T: class { public DynamicBuilder(IArgumentStore argumentStore) : base(argumentStore) { } public override bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result) { ParseMembersFromMethodName(binder, args); result = this; return true; } private void ParseMembersFromMethodName(InvokeMemberBinder binder, object[] args) { var memberName = binder.Name.Replace("With", ""); argumentStore.SetMemberNameAndValue(memberName, args[0]); } } }
using System.Dynamic; using BobTheBuilder.ArgumentStore; namespace BobTheBuilder.Syntax { public class DynamicBuilder<T> : DynamicBuilderBase<T>, IParser where T: class { public DynamicBuilder(IArgumentStore argumentStore) : base(argumentStore) { } public override bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result) { Parse(binder, args); result = this; return true; } public bool Parse(InvokeMemberBinder binder, object[] args) { var memberName = binder.Name.Replace("With", ""); argumentStore.SetMemberNameAndValue(memberName, args[0]); return true; } } }
Implement IParser on method syntax builder.
Implement IParser on method syntax builder.
C#
apache-2.0
fffej/BobTheBuilder,alastairs/BobTheBuilder
f8245bc6347829be36b3b28bfe275d8ccad72ed4
src/Abc.Zebus/Transport/ZmqSocketOptions.cs
src/Abc.Zebus/Transport/ZmqSocketOptions.cs
using System; using Abc.Zebus.Util; namespace Abc.Zebus.Transport { public class ZmqSocketOptions : IZmqSocketOptions { public ZmqSocketOptions() { ReadTimeout = 300.Milliseconds(); SendHighWaterMark = 20000; SendTimeout = 1000.Milliseconds(); SendRetriesBeforeSwitchingToClosedState = 5; ClosedStateDuration = 15.Seconds(); ReceiveHighWaterMark = 20000; } public TimeSpan ReadTimeout { set; get; } public int SendHighWaterMark { get; set; } public TimeSpan SendTimeout { get; set; } public int SendRetriesBeforeSwitchingToClosedState { get; set; } public TimeSpan ClosedStateDuration { get; set; } public int ReceiveHighWaterMark { get; set; } } }
using System; using Abc.Zebus.Util; namespace Abc.Zebus.Transport { public class ZmqSocketOptions : IZmqSocketOptions { public ZmqSocketOptions() { ReadTimeout = 300.Milliseconds(); SendHighWaterMark = 20000; SendTimeout = 100.Milliseconds(); SendRetriesBeforeSwitchingToClosedState = 2; ClosedStateDuration = 15.Seconds(); ReceiveHighWaterMark = 20000; } public TimeSpan ReadTimeout { set; get; } public int SendHighWaterMark { get; set; } public TimeSpan SendTimeout { get; set; } public int SendRetriesBeforeSwitchingToClosedState { get; set; } public TimeSpan ClosedStateDuration { get; set; } public int ReceiveHighWaterMark { get; set; } } }
Make send try policy more aggressive
Make send try policy more aggressive A slow consumer would block the sending thread for 6s (1+5 retries * 1000ms) before being marked as down, which prevents other peers from receiving messages, the new setting is more aggressive (300ms).
C#
mit
Abc-Arbitrage/Zebus,biarne-a/Zebus
d97dc22e79021f94249a99cae827d1d25003bac7
osu.Game.Tests/Visual/UserInterface/TestSceneFirstRunScreenBehaviour.cs
osu.Game.Tests/Visual/UserInterface/TestSceneFirstRunScreenBehaviour.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Screens; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenBehaviour : OsuManualInputManagerTestScene { public TestSceneFirstRunScreenBehaviour() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenBehaviour()); }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Screens; using osu.Game.Overlays; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenBehaviour : OsuManualInputManagerTestScene { [Cached] private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple); public TestSceneFirstRunScreenBehaviour() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenBehaviour()); }); } } }
Add missing dependencies for behaviour screen test
Add missing dependencies for behaviour screen test
C#
mit
ppy/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu
115428ec50d27915b36250e0b17dacca05b95926
Browser/Handling/General/CustomLifeSpanHandler.cs
Browser/Handling/General/CustomLifeSpanHandler.cs
using CefSharp; using CefSharp.Handler; using TweetDuck.Controls; using TweetDuck.Utils; namespace TweetDuck.Browser.Handling.General { sealed class CustomLifeSpanHandler : LifeSpanHandler { private static bool IsPopupAllowed(string url) { return url.StartsWith("https://twitter.com/teams/authorize?"); } public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl) { switch (targetDisposition) { case WindowOpenDisposition.NewBackgroundTab: case WindowOpenDisposition.NewForegroundTab: case WindowOpenDisposition.NewPopup when !IsPopupAllowed(targetUrl): case WindowOpenDisposition.NewWindow: browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl)); return true; default: return false; } } protected override bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { newBrowser = null; return HandleLinkClick(browserControl, targetDisposition, targetUrl); } protected override bool DoClose(IWebBrowser browserControl, IBrowser browser) { return false; } } }
using System; using CefSharp; using CefSharp.Handler; using TweetDuck.Controls; using TweetDuck.Utils; namespace TweetDuck.Browser.Handling.General { sealed class CustomLifeSpanHandler : LifeSpanHandler { private static bool IsPopupAllowed(string url) { return url.StartsWith("https://twitter.com/teams/authorize?", StringComparison.Ordinal) || url.StartsWith("https://accounts.google.com/", StringComparison.Ordinal) || url.StartsWith("https://appleid.apple.com/", StringComparison.Ordinal); } public static bool HandleLinkClick(IWebBrowser browserControl, WindowOpenDisposition targetDisposition, string targetUrl) { switch (targetDisposition) { case WindowOpenDisposition.NewBackgroundTab: case WindowOpenDisposition.NewForegroundTab: case WindowOpenDisposition.NewPopup when !IsPopupAllowed(targetUrl): case WindowOpenDisposition.NewWindow: browserControl.AsControl().InvokeAsyncSafe(() => BrowserUtils.OpenExternalBrowser(targetUrl)); return true; default: return false; } } protected override bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { newBrowser = null; return HandleLinkClick(browserControl, targetDisposition, targetUrl); } protected override bool DoClose(IWebBrowser browserControl, IBrowser browser) { return false; } } }
Fix popups for Google & Apple sign-in
Fix popups for Google & Apple sign-in
C#
mit
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
1fce0da33189907d8c14588af5b35dd8b5efb13a
osu.Game/Rulesets/Edit/IPositionSnapProvider.cs
osu.Game/Rulesets/Edit/IPositionSnapProvider.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 osuTK; namespace osu.Game.Rulesets.Edit { /// <summary> /// A snap provider which given the position of a hit object, offers a more correct position and time value inferred from the context of the beatmap. /// Provided values are done so in an isolated context, without consideration of other nearby hit objects. /// </summary> public interface IPositionSnapProvider { /// <summary> /// Given a position, find a valid time and position snap. /// </summary> /// <remarks> /// This call should be equivalent to running <see cref="FindSnappedPosition"/> with any additional logic that can be performed without the time immutability restriction. /// </remarks> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The time and position post-snapping.</returns> SnapResult FindSnappedPositionAndTime(Vector2 screenSpacePosition); /// <summary> /// Given a position, find a value position snap, restricting time to its input value. /// </summary> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The position post-snapping. Time will always be null.</returns> SnapResult FindSnappedPosition(Vector2 screenSpacePosition); } }
// 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 osuTK; namespace osu.Game.Rulesets.Edit { /// <summary> /// A snap provider which given a proposed position for a hit object, potentially offers a more correct position and time value inferred from the context of the beatmap. /// Provided values are inferred in an isolated context, without consideration of other nearby hit objects. /// </summary> public interface IPositionSnapProvider { /// <summary> /// Given a position, find a valid time and position snap. /// </summary> /// <remarks> /// This call should be equivalent to running <see cref="FindSnappedPosition"/> with any additional logic that can be performed without the time immutability restriction. /// </remarks> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The time and position post-snapping.</returns> SnapResult FindSnappedPositionAndTime(Vector2 screenSpacePosition); /// <summary> /// Given a position, find a value position snap, restricting time to its input value. /// </summary> /// <param name="screenSpacePosition">The screen-space position to be snapped.</param> /// <returns>The position post-snapping. Time will always be null.</returns> SnapResult FindSnappedPosition(Vector2 screenSpacePosition); } }
Reword slightly, to allow better conformity with `IDistanceSnapProvider`
Reword slightly, to allow better conformity with `IDistanceSnapProvider`
C#
mit
NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu
6e07b46ac1931e5d2a27326daf58bb248ba7b185
tools/Build/Build.cs
tools/Build/Build.cs
using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"), DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"), SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src", }, SourceLinkSettings = SourceLinkSettings.Default, }); }); }
using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"), DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("faithlifebuildbot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("Faithlife Build Bot", "faithlifebuildbot@users.noreply.github.com"), SourceCodeUrl = "https://github.com/Faithlife/RepoName/tree/master/src", }, }); }); }
Remove use of obsolete property.
Remove use of obsolete property.
C#
mit
Faithlife/FaithlifeUtility,ejball/ArgsReading,Faithlife/System.Data.SQLite,Faithlife/Parsing,Faithlife/System.Data.SQLite,ejball/XmlDocMarkdown
64a50ee4a489c169e93794913849fa1c57753217
CallMeMaybe/Properties/AssemblyInfo.cs
CallMeMaybe/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CallMeMaybe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("CallMeMaybe")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CallMeMaybe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("CallMeMaybe")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.1.*")] //[assembly: AssemblyVersion("1.0.0.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
Set auto-incrementing file version, starting with 0.1, since we're at alpha stage
Set auto-incrementing file version, starting with 0.1, since we're at alpha stage
C#
mit
j2jensen/CallMeMaybe
2bbdd920b7af637884c97cb57001dc3fa950e929
src/Booma.Proxy.Packets.BlockServer/Attributes/SubCommand60ServerAttribute.cs
src/Booma.Proxy.Packets.BlockServer/Attributes/SubCommand60ServerAttribute.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; using JetBrains.Annotations; namespace Booma.Proxy { /// <summary> /// Marks the 0x60 command server payload with the associated operation code. /// Should be marked on <see cref="BlockNetworkCommandEventServerPayload"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class SubCommand60ServerAttribute : WireDataContractBaseLinkAttribute { /// <inheritdoc /> public SubCommand60ServerAttribute(SubCommand60OperationCode opCode) : base((int)opCode, typeof(BlockNetworkCommandEventClientPayload)) { if(!Enum.IsDefined(typeof(SubCommand60OperationCode), opCode)) throw new InvalidEnumArgumentException(nameof(opCode), (int)opCode, typeof(SubCommand60OperationCode)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; using JetBrains.Annotations; namespace Booma.Proxy { /// <summary> /// Marks the 0x60 command server payload with the associated operation code. /// Should be marked on <see cref="BlockNetworkCommandEventServerPayload"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class SubCommand60ServerAttribute : WireDataContractBaseLinkAttribute { /// <inheritdoc /> public SubCommand60ServerAttribute(SubCommand60OperationCode opCode) : base((int)opCode, typeof(BlockNetworkCommandEventServerPayload)) { if(!Enum.IsDefined(typeof(SubCommand60OperationCode), opCode)) throw new InvalidEnumArgumentException(nameof(opCode), (int)opCode, typeof(SubCommand60OperationCode)); } } }
Fix fault with subcommand server attribute
Fix fault with subcommand server attribute
C#
agpl-3.0
HelloKitty/Booma.Proxy
a47ebca8ce63ff32b42dcb59b7f26f812825cd6b
src/Diploms.DataLayer/DiplomContextExtensions.cs
src/Diploms.DataLayer/DiplomContextExtensions.cs
using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
Add administrator user by default
Add administrator user by default
C#
mit
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
68d6e8c138c5d0b81f3d592dc6f335d2485fc40e
WAWSDeploy/WebDeployHelper.cs
WAWSDeploy/WebDeployHelper.cs
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.Web.Deployment; namespace WAWSDeploy { public class WebDeployHelper { public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile) { var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions); Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile)); // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions()); } } private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions) { var document = XDocument.Load(path); var profile = document.Descendants("publishProfile").First(); string siteName = profile.Attribute("msdeploySite").Value; deploymentBaseOptions = new DeploymentBaseOptions { ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName), UserName = profile.Attribute("userName").Value, Password = profile.Attribute("userPWD").Value, AuthenticationType = "Basic" }; return siteName; } } }
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.Web.Deployment; namespace WAWSDeploy { public class WebDeployHelper { public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile) { contentPath = Path.GetFullPath(contentPath); var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions); Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile)); // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions()); } } private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions) { var document = XDocument.Load(path); var profile = document.Descendants("publishProfile").First(); string siteName = profile.Attribute("msdeploySite").Value; deploymentBaseOptions = new DeploymentBaseOptions { ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName), UserName = profile.Attribute("userName").Value, Password = profile.Attribute("userPWD").Value, AuthenticationType = "Basic" }; return siteName; } } }
Use full path to source folder
Use full path to source folder
C#
apache-2.0
davidebbo/WAWSDeploy,davidebbo/WAWSDeploy
cdb721b79d2cdb1f454a9db53f2df3ec7c897373
LightBlue/Standalone/StandaloneAzureStorage.cs
LightBlue/Standalone/StandaloneAzureStorage.cs
using System; using System.IO; using System.Linq; namespace LightBlue.Standalone { public class StandaloneAzureStorage : IAzureStorage { public const string DevelopmentAccountName = "dev"; private readonly string _storageAccountDirectory; public StandaloneAzureStorage(string connectionString) { var storageAccountName = ExtractAccountName(connectionString); _storageAccountDirectory = Path.Combine(StandaloneEnvironment.LightBlueDataDirectory, storageAccountName); Directory.CreateDirectory(_storageAccountDirectory); } public IAzureBlobStorageClient CreateAzureBlobStorageClient() { return new StandaloneAzureBlobStorageClient(_storageAccountDirectory); } public IAzureQueueStorageClient CreateAzureQueueStorageClient() { throw new NotSupportedException(); } private static string ExtractAccountName(string connectionString) { try { var valuePairs = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(component => component.Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(c => c[0].ToLowerInvariant(), c => c[1]); if (valuePairs.ContainsKey("accountname")) { return valuePairs["accountname"]; } if (valuePairs.ContainsKey("usedevelopmentstorage")) { return DevelopmentAccountName; } } catch (IndexOutOfRangeException ex) { throw new FormatException("Settings must be of the form \"name=value\".", ex); } throw new FormatException("Could not parse the connection string."); } } }
using System; using System.IO; using System.Linq; namespace LightBlue.Standalone { public class StandaloneAzureStorage : IAzureStorage { public const string DevelopmentAccountName = "dev"; private readonly string _storageAccountDirectory; public StandaloneAzureStorage(string connectionString) { var storageAccountName = ExtractAccountName(connectionString); _storageAccountDirectory = Path.Combine(StandaloneEnvironment.LightBlueDataDirectory, storageAccountName); Directory.CreateDirectory(_storageAccountDirectory); } public IAzureBlobStorageClient CreateAzureBlobStorageClient() { return new StandaloneAzureBlobStorageClient(_storageAccountDirectory); } public IAzureQueueStorageClient CreateAzureQueueStorageClient() { return new StandaloneAzureQueueStorageClient(_storageAccountDirectory); } private static string ExtractAccountName(string connectionString) { try { var valuePairs = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(component => component.Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(c => c[0].ToLowerInvariant(), c => c[1]); if (valuePairs.ContainsKey("accountname")) { return valuePairs["accountname"]; } if (valuePairs.ContainsKey("usedevelopmentstorage")) { return DevelopmentAccountName; } } catch (IndexOutOfRangeException ex) { throw new FormatException("Settings must be of the form \"name=value\".", ex); } throw new FormatException("Could not parse the connection string."); } } }
Allow access to standalone queue storage
Allow access to standalone queue storage
C#
apache-2.0
Drewan/LightBlue,Drewan/LightBlue,Drewan/LightBlue,LightBlueProject/LightBlue,wangdoubleyan/LightBlue,LightBlueProject/LightBlue,LightBlueProject/LightBlue,ColinScott/LightBlue,ColinScott/LightBlue,wangdoubleyan/LightBlue,wangdoubleyan/LightBlue,ColinScott/LightBlue
ff1b1549eb83df817e3b068018cb94f0ceecf3ba
src/QuartzNET-DynamoDB.Tests/Integration/JobStore/TriggerGroupGetTests.cs
src/QuartzNET-DynamoDB.Tests/Integration/JobStore/TriggerGroupGetTests.cs
using System; using Quartz.Simpl; using Quartz.Spi; namespace Quartz.DynamoDB.Tests { public class TriggerGroupGetTests { IJobStore _sut; public TriggerGroupGetTests() { _sut = new JobStore(); var signaler = new Quartz.DynamoDB.Tests.Integration.RamJobStoreTests.SampleSignaler(); var loadHelper = new SimpleTypeLoadHelper(); _sut.Initialize(loadHelper, signaler); } } }
using System; using Quartz.Simpl; using Quartz.Spi; using Xunit; namespace Quartz.DynamoDB.Tests { public class TriggerGroupGetTests { IJobStore _sut; public TriggerGroupGetTests() { _sut = new JobStore(); var signaler = new Quartz.DynamoDB.Tests.Integration.RamJobStoreTests.SampleSignaler(); var loadHelper = new SimpleTypeLoadHelper(); _sut.Initialize(loadHelper, signaler); } /// <summary> /// Get paused trigger groups returns one record. /// </summary> [Fact] [Trait("Category", "Integration")] public void GetPausedTriggerGroupReturnsOneRecord() { //create a trigger group by calling for it to be paused. string triggerGroup = Guid.NewGuid().ToString(); _sut.PauseTriggers(Quartz.Impl.Matchers.GroupMatcher<TriggerKey>.GroupEquals(triggerGroup)); var result = _sut.GetPausedTriggerGroups(); Assert.True(result.Contains(triggerGroup)); } } }
Add failing test for get paused trigger groups
Add failing test for get paused trigger groups
C#
apache-2.0
lukeryannetnz/quartznet-dynamodb,lukeryannetnz/quartznet-dynamodb
7994581ebaabac78d7132b45e821256623d651c1
vuwall-motion/vuwall-motion/TransparentForm.cs
vuwall-motion/vuwall-motion/TransparentForm.cs
using System; using System.Drawing; using System.Windows.Forms; namespace vuwall_motion { public partial class TransparentForm : Form { public TransparentForm() { InitializeComponent(); DoubleBuffered = true; } private void TransparentForm_Load(object sender, EventArgs e) { int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle); wl = wl | 0x80000 | 0x20; TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl); TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha); Invalidate(); } private void TransparentForm_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20); } // TODO: Method to get an event from MYO to get x & w positions, used to invalidate } }
using System; using System.Drawing; using System.Windows.Forms; namespace vuwall_motion { public partial class TransparentForm : Form { public TransparentForm() { InitializeComponent(); DoubleBuffered = true; ShowInTaskbar = false; } private void TransparentForm_Load(object sender, EventArgs e) { int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle); wl = wl | 0x80000 | 0x20; TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl); TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha); Invalidate(); } private void TransparentForm_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20); } // TODO: Method to get an event from MYO to get x & w positions, used to invalidate } }
Hide the form in the taskbar
Hide the form in the taskbar
C#
mit
DanH91/vuwall-motion,VuWall/VuWall-Motion
591c5312593f19ca0be8d59e233cdadb78d6a9b3
src/Novell.Directory.Ldap.NETStandard/ILdapConnection.ExtensionMethods.cs
src/Novell.Directory.Ldap.NETStandard/ILdapConnection.ExtensionMethods.cs
namespace Novell.Directory.Ldap { /// <summary> /// Extension Methods for <see cref="ILdapConnection"/> to /// avoid bloating that interface. /// </summary> public static class LdapConnectionExtensionMethods { /// <summary> /// Get some common Attributes from the Root DSE. /// This is really just a specialized <see cref="LdapSearchRequest"/> /// to handle getting some commonly requested information. /// </summary> public static RootDseInfo GetRootDseInfo(this ILdapConnection conn) { var searchResults = conn.Search("", LdapConnection.ScopeBase, "(objectClass=*)", new string[] { "*", "supportedExtension" }, false); if (searchResults.HasMore()) { var sr = searchResults.Next(); return new RootDseInfo(sr); } return null; } } }
namespace Novell.Directory.Ldap { /// <summary> /// Extension Methods for <see cref="ILdapConnection"/> to /// avoid bloating that interface. /// </summary> public static class LdapConnectionExtensionMethods { /// <summary> /// Get some common Attributes from the Root DSE. /// This is really just a specialized <see cref="LdapSearchRequest"/> /// to handle getting some commonly requested information. /// </summary> public static RootDseInfo GetRootDseInfo(this ILdapConnection conn) { var searchResults = conn.Search("", LdapConnection.ScopeBase, "(objectClass=*)", new string[] { "*", "+", "supportedExtension" }, false); if (searchResults.HasMore()) { var sr = searchResults.Next(); return new RootDseInfo(sr); } return null; } } }
Add "+" to attributes to fetch since ApacheDS doesn't return all on * and AD doesn't return anything on +
GetRootDseInfo: Add "+" to attributes to fetch since ApacheDS doesn't return all on * and AD doesn't return anything on +
C#
mit
dsbenghe/Novell.Directory.Ldap.NETStandard,dsbenghe/Novell.Directory.Ldap.NETStandard
63a5a1d02aa9bdf8dfc0c6111146c6f75fc6e20b
Eco/Elements/variable.cs
Eco/Elements/variable.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eco { /// <summary> /// Eco configuration library supports string varibales. /// You can enable variables in your configuration file by adding 'public variable[] variables;' /// field to your root configuration type. /// Variable can be referenced anywhere in a configuration file by it's name using the following syntax: ${name}. /// /// Variable's value can reference another variable. In this case variable value is expanded recursively. /// Eco library throws an exception if a circular variable dendency is detected. /// </summary> [Doc("Represents a configuration variable of the string type. Can be referenced anywhere in a configuration file by the following syntax: ${name}.")] public class variable { [Required, Doc("Name of the varible. Can contain 'word' characters only.")] public string name; [Required, Doc("Variable's value.")] public string value; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eco { /// <summary> /// Eco configuration library supports string varibales. /// You can enable variables in your configuration file by adding 'public variable[] variables;' /// field to your root configuration type. /// Variable can be referenced anywhere in a configuration file by it's name using the following syntax: ${name}. /// /// Variable's value can reference another variable. In this case variable value is expanded recursively. /// Eco library throws an exception if a circular variable dendency is detected. /// </summary> [Doc("Represents a configuration variable of the string type. Can be referenced anywhere in a configuration file by the following syntax: ${name}.")] public class variable { [Required, Doc("Name of the varible. Can contain 'word' characters only (ie [A-Za-z0-9_]).")] public string name; [Required, Doc("Variable's value.")] public string value; } }
Update the 'name' field description
Update the 'name' field description
C#
apache-2.0
lukyad/Eco
7528a5fa1bd0a072cae97185bec05d54fcac11ad
src/Adaptive.Aeron/ActiveSubscriptions.cs
src/Adaptive.Aeron/ActiveSubscriptions.cs
using System; using System.Collections.Generic; using System.Linq; namespace Adaptive.Aeron { internal class ActiveSubscriptions : IDisposable { private readonly Dictionary<int, List<Subscription>> _subscriptionsByStreamIdMap = new Dictionary<int, List<Subscription>>(); public void ForEach(int streamId, Action<Subscription> handler) { List<Subscription> subscriptions; if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions)) { subscriptions.ForEach(handler); } } public void Add(Subscription subscription) { List<Subscription> subscriptions; if (!_subscriptionsByStreamIdMap.TryGetValue(subscription.StreamId(), out subscriptions)) { subscriptions = new List<Subscription>(); _subscriptionsByStreamIdMap[subscription.StreamId()] = subscriptions; } subscriptions.Add(subscription); } public void Remove(Subscription subscription) { int streamId = subscription.StreamId(); var subscriptions = _subscriptionsByStreamIdMap[streamId]; if (subscriptions.Remove(subscription) && subscriptions.Count == 0) { _subscriptionsByStreamIdMap.Remove(streamId); } } public void Dispose() { var subscriptions = from subs in _subscriptionsByStreamIdMap.Values from subscription in subs select subscription; foreach (var subscription in subscriptions) { subscription.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Adaptive.Aeron { internal class ActiveSubscriptions : IDisposable { private readonly Dictionary<int, List<Subscription>> _subscriptionsByStreamIdMap = new Dictionary<int, List<Subscription>>(); public void ForEach(int streamId, Action<Subscription> handler) { List<Subscription> subscriptions; if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions)) { subscriptions.ForEach(handler); } } public void Add(Subscription subscription) { List<Subscription> subscriptions; if (!_subscriptionsByStreamIdMap.TryGetValue(subscription.StreamId(), out subscriptions)) { subscriptions = new List<Subscription>(); _subscriptionsByStreamIdMap[subscription.StreamId()] = subscriptions; } subscriptions.Add(subscription); } public void Remove(Subscription subscription) { int streamId = subscription.StreamId(); List<Subscription> subscriptions; if (_subscriptionsByStreamIdMap.TryGetValue(streamId, out subscriptions)) { if (subscriptions.Remove(subscription) && subscriptions.Count == 0) { _subscriptionsByStreamIdMap.Remove(streamId); } } } public void Dispose() { var subscriptions = from subs in _subscriptionsByStreamIdMap.Values from subscription in subs select subscription; foreach (var subscription in subscriptions) { subscription.Dispose(); } } } }
Deal with case of removing a Subscription that has been previously removed (06624d)
Deal with case of removing a Subscription that has been previously removed (06624d)
C#
apache-2.0
AdaptiveConsulting/Aeron.NET,AdaptiveConsulting/Aeron.NET
28239c4a513ded1dfcc5c9a4845c171ef35b70e1
Wox.Infrastructure/UserSettings/PluginSettings.cs
Wox.Infrastructure/UserSettings/PluginSettings.cs
using System.Collections.Generic; using Wox.Plugin; namespace Wox.Infrastructure.UserSettings { public class PluginsSettings : BaseModel { public string PythonDirectory { get; set; } public Dictionary<string, Plugin> Plugins { get; set; } = new Dictionary<string, Plugin>(); public void UpdatePluginSettings(List<PluginMetadata> metadatas) { foreach (var metadata in metadatas) { if (Plugins.ContainsKey(metadata.ID)) { var settings = Plugins[metadata.ID]; if (settings.ActionKeywords?.Count > 0) { metadata.ActionKeywords = settings.ActionKeywords; metadata.ActionKeyword = settings.ActionKeywords[0]; } metadata.Disabled = settings.Disabled; } else { Plugins[metadata.ID] = new Plugin { ID = metadata.ID, Name = metadata.Name, ActionKeywords = metadata.ActionKeywords, Disabled = false }; } } } } public class Plugin { public string ID { get; set; } public string Name { get; set; } public List<string> ActionKeywords { get; set; } public bool Disabled { get; set; } } }
using System.Collections.Generic; using Wox.Plugin; namespace Wox.Infrastructure.UserSettings { public class PluginsSettings : BaseModel { public string PythonDirectory { get; set; } public Dictionary<string, Plugin> Plugins { get; set; } = new Dictionary<string, Plugin>(); public void UpdatePluginSettings(List<PluginMetadata> metadatas) { foreach (var metadata in metadatas) { if (Plugins.ContainsKey(metadata.ID)) { var settings = Plugins[metadata.ID]; if (settings.ActionKeywords?.Count > 0) { metadata.ActionKeywords = settings.ActionKeywords; metadata.ActionKeyword = settings.ActionKeywords[0]; } metadata.Disabled = settings.Disabled; } else { Plugins[metadata.ID] = new Plugin { ID = metadata.ID, Name = metadata.Name, ActionKeywords = metadata.ActionKeywords, Disabled = metadata.Disabled }; } } } } public class Plugin { public string ID { get; set; } public string Name { get; set; } public List<string> ActionKeywords { get; set; } public bool Disabled { get; set; } } }
Fix to allow plugin to start up disabled as default
Fix to allow plugin to start up disabled as default
C#
mit
qianlifeng/Wox,qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox,Wox-launcher/Wox
1d832a62eecc306869f58b2d68ab0c7ba707c003
src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs
src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs
using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate; using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork; using Ordering.Domain.Exceptions; using System; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories { public class OrderRepository : IOrderRepository { private readonly OrderingContext _context; public IUnitOfWork UnitOfWork { get { return _context; } } public OrderRepository(OrderingContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public Order Add(Order order) { return _context.Orders.Add(order).Entity; } public async Task<Order> GetAsync(int orderId) { return await _context.Orders.FindAsync(orderId) ?? throw new OrderingDomainException($"Not able to get the order. Reason: no valid orderId: {orderId}"); } public void Update(Order order) { _context.Entry(order).State = EntityState.Modified; } } }
Add OrderingDomainException when the order doesn't exist with id orderId
Add OrderingDomainException when the order doesn't exist with id orderId
C#
mit
productinfo/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers
d4151f302570c9c2ea2cd3e6d143cb99cdd24efe
LeetCode/simmetric_tree.cs
LeetCode/simmetric_tree.cs
using System; class Node { public Node(int val, Node left, Node right) { Value = val; Left = left; Right = right; } public int Value { get; private set; } public Node Left { get; private set; } public Node Right { get; private set; } } class Program{ static bool IsMirror(Node left, Node right) { if (left == null && right == null) { return true; } if (left == null && right != null || left != null && right == null) { return false; } return ((left.Value == right.Value) && IsMirror(left.Right, right.Left) && IsMirror(left.Left, right.Right)); } static void Main() { Node root = new Node(1, new Node(2, new Node(3, null, null), new Node(4, null, null)), new Node(2, new Node(4, null, null), new Node(3, null, null))); Node unroot = new Node(1, new Node(2, null, new Node(4, null, null)), new Node(2, null, new Node(4, null, null))); Console.WriteLine("First {0}", IsMirror(root.Left, root.Right)); Console.WriteLine("Second {0}", IsMirror(unroot.Left, unroot.Right)); } }
using System; class Node { public Node(int val, Node left, Node right) { Value = val; Left = left; Right = right; } public int Value { get; private set; } public Node Left { get; private set; } public Node Right { get; private set; } } class Program{ static bool IsMirror(Node left, Node right) { if (left == null || right == null) { return left == null && right == null; } return ((left.Value == right.Value) && IsMirror(left.Right, right.Left) && IsMirror(left.Left, right.Right)); } static void Main() { Node root = new Node(1, new Node(2, new Node(3, null, null), new Node(4, null, null)), new Node(2, new Node(4, null, null), new Node(3, null, null))); Node unroot = new Node(1, new Node(2, null, new Node(4, null, null)), new Node(2, null, new Node(4, null, null))); Console.WriteLine("First {0}", IsMirror(root.Left, root.Right)); Console.WriteLine("Second {0}", IsMirror(unroot.Left, unroot.Right)); } }
Check if tree is mirror. Improved logics.
Check if tree is mirror. Improved logics.
C#
mit
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
aa672cd59d284c7a757ccfa2327f50df0fd306fd
CSharpMath.Xaml.Tests.NuGet/Test.cs
CSharpMath.Xaml.Tests.NuGet/Test.cs
namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Equal(797, forms.Length); using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } }
namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Contains(new[] { 344, 797 }, forms.Length); // 797 on Mac, 344 on Ubuntu using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } }
Update test for possible sizes
Update test for possible sizes
C#
mit
verybadcat/CSharpMath
c935dbae44fd1f4f80faf03a8322b7502ccc0e31
src/Workspaces/Core/Portable/SolutionCrawler/IIncrementalAnalyzerExtensions.cs
src/Workspaces/Core/Portable/SolutionCrawler/IIncrementalAnalyzerExtensions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static partial class IIncrementalAnalyzerExtensions { public static BackgroundAnalysisScope GetOverriddenBackgroundAnalysisScope(this IIncrementalAnalyzer incrementalAnalyzer, OptionSet options, BackgroundAnalysisScope defaultBackgroundAnalysisScope) { // Unit testing analyzer has special semantics for analysis scope. if (incrementalAnalyzer is UnitTestingIncrementalAnalyzer unitTestingAnalyzer) { return unitTestingAnalyzer.GetBackgroundAnalysisScope(options); } // TODO: Remove the below if statement once SourceBasedTestDiscoveryIncrementalAnalyzer has been switched to UnitTestingIncrementalAnalyzer if (incrementalAnalyzer.GetType().FullName == "Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery.SourceBasedTestDiscoveryIncrementalAnalyzer") { return BackgroundAnalysisScope.FullSolution; } return defaultBackgroundAnalysisScope; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static partial class IIncrementalAnalyzerExtensions { public static BackgroundAnalysisScope GetOverriddenBackgroundAnalysisScope(this IIncrementalAnalyzer incrementalAnalyzer, OptionSet options, BackgroundAnalysisScope defaultBackgroundAnalysisScope) { // Unit testing analyzer has special semantics for analysis scope. if (incrementalAnalyzer is UnitTestingIncrementalAnalyzer unitTestingAnalyzer) { return unitTestingAnalyzer.GetBackgroundAnalysisScope(options); } return defaultBackgroundAnalysisScope; } } }
Revert the hard coded name check for SBD incremental analyzer as unit test team has moved to IUnitTestingIncrementalAnalyzer
Revert the hard coded name check for SBD incremental analyzer as unit test team has moved to IUnitTestingIncrementalAnalyzer
C#
mit
stephentoub/roslyn,aelij/roslyn,aelij/roslyn,physhi/roslyn,agocke/roslyn,gafter/roslyn,heejaechang/roslyn,wvdd007/roslyn,jmarolf/roslyn,diryboy/roslyn,weltkante/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,mavasani/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,genlu/roslyn,AlekseyTs/roslyn,brettfo/roslyn,agocke/roslyn,genlu/roslyn,aelij/roslyn,KevinRansom/roslyn,tannergooding/roslyn,wvdd007/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,tmat/roslyn,eriawan/roslyn,tmat/roslyn,reaction1989/roslyn,AmadeusW/roslyn,gafter/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,davkean/roslyn,weltkante/roslyn,AmadeusW/roslyn,heejaechang/roslyn,sharwell/roslyn,jmarolf/roslyn,davkean/roslyn,davkean/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,tmat/roslyn,gafter/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,tannergooding/roslyn,brettfo/roslyn,eriawan/roslyn,reaction1989/roslyn,mavasani/roslyn,physhi/roslyn,dotnet/roslyn,abock/roslyn,ErikSchierboom/roslyn,agocke/roslyn,diryboy/roslyn,physhi/roslyn,abock/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,reaction1989/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,weltkante/roslyn,brettfo/roslyn,diryboy/roslyn,sharwell/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,heejaechang/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn
635b283d05d1df14588259da6b6a1ae05a9d4639
FTAnalyser/SharedAssemblyVersion.cs
FTAnalyser/SharedAssemblyVersion.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.c6b5bf2a")] [assembly: System.Reflection.AssemblyVersion("1.2.0")] [assembly: System.Reflection.AssemblyFileVersion("1.2.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyInformationalVersion("1.2.0.5b2eaa85")] [assembly: System.Reflection.AssemblyVersion("1.2.0")] [assembly: System.Reflection.AssemblyFileVersion("1.2.0")]
Update Messages to correct location
Update Messages to correct location
C#
apache-2.0
ShammyLevva/FTAnalyzer,ShammyLevva/FTAnalyzer,ShammyLevva/FTAnalyzer
65112348041cffc6df4c625c65c914bc03a669f7
osu.Game/Rulesets/Objects/Legacy/Catch/ConvertSpinner.cs
osu.Game/Rulesets/Objects/Legacy/Catch/ConvertSpinner.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Rulesets.Objects.Legacy.Catch { /// <summary> /// Legacy osu!catch Spinner-type, used for parsing Beatmaps. /// </summary> internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasCombo { public double EndTime { get; set; } public double Duration => EndTime - StartTime; public bool NewCombo { get; set; } public int ComboOffset { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Rulesets.Objects.Legacy.Catch { /// <summary> /// Legacy osu!catch Spinner-type, used for parsing Beatmaps. /// </summary> internal sealed class ConvertSpinner : HitObject, IHasEndTime, IHasXPosition, IHasCombo { public double EndTime { get; set; } public double Duration => EndTime - StartTime; public float X => 256; // Required for CatchBeatmapConverter public bool NewCombo { get; set; } public int ComboOffset { get; set; } } }
Fix catch spinners not being allowed for conversion
Fix catch spinners not being allowed for conversion
C#
mit
peppy/osu,ppy/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu,ZLima12/osu,DrabWeb/osu,ZLima12/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,ppy/osu,peppy/osu,EVAST9919/osu,EVAST9919/osu,DrabWeb/osu,DrabWeb/osu,2yangk23/osu,UselessToucan/osu
ea9cb0e3c89582dc6ec06496ef27418b26fa2167
Query/Internal/InfoCarrierQueryContext.cs
Query/Internal/InfoCarrierQueryContext.cs
namespace InfoCarrier.Core.Client.Query.Internal { using System; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; public class InfoCarrierQueryContext : QueryContext { public InfoCarrierQueryContext( Func<IQueryBuffer> createQueryBuffer, ServerContext serverContext, IStateManager stateManager, IConcurrencyDetector concurrencyDetector) : base( createQueryBuffer, stateManager, concurrencyDetector) { this.ServerContext = serverContext; } public ServerContext ServerContext { get; } } }
namespace InfoCarrier.Core.Client.Query.Internal { using System; using Common; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; public class InfoCarrierQueryContext : QueryContext { public InfoCarrierQueryContext( Func<IQueryBuffer> createQueryBuffer, ServerContext serverContext, IStateManager stateManager, IConcurrencyDetector concurrencyDetector) : base( createQueryBuffer, stateManager, concurrencyDetector) { this.ServerContext = serverContext; } public ServerContext ServerContext { get; } public override void StartTracking(object entity, EntityTrackingInfo entityTrackingInfo) { using (new PropertyLoadController(this.ServerContext.DataContext, enableLoading: false)) { base.StartTracking(entity, entityTrackingInfo); } } } }
Disable unwanted lazy loading during query execution
Disable unwanted lazy loading during query execution
C#
mit
azabluda/InfoCarrier.Core
cf0b63ccddde23e7ab98f37cff12dee63f30d958
SQLite.CodeFirst/SqliteInitializerBase.cs
SQLite.CodeFirst/SqliteInitializerBase.cs
using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace SQLite.CodeFirst { public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext { protected readonly DbModelBuilder ModelBuilder; protected readonly string DatabaseFilePath; protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder) { DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString); ModelBuilder = modelBuilder; // This convention will crash the SQLite Provider before "InitializeDatabase" gets called. // See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details. modelBuilder.Conventions.Remove<TimestampAttributeConvention>(); } public virtual void InitializeDatabase(TContext context) { var model = ModelBuilder.Build(context.Database.Connection); using (var transaction = context.Database.BeginTransaction()) { try { var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model); sqliteDatabaseCreator.Create(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } using (var transaction = context.Database.BeginTransaction()) { try { Seed(context); context.SaveChanges(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } protected virtual void Seed(TContext context) { } } }
using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using SQLite.CodeFirst.Convention; namespace SQLite.CodeFirst { public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext { protected readonly DbModelBuilder ModelBuilder; protected readonly string DatabaseFilePath; protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder) { DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString); ModelBuilder = modelBuilder; // This convention will crash the SQLite Provider before "InitializeDatabase" gets called. // See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details. modelBuilder.Conventions.Remove<TimestampAttributeConvention>(); modelBuilder.Conventions.AddAfter<ForeignKeyIndexConvention>(new SqliteForeignKeyIndexConvention()); } public virtual void InitializeDatabase(TContext context) { var model = ModelBuilder.Build(context.Database.Connection); using (var transaction = context.Database.BeginTransaction()) { try { var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model); sqliteDatabaseCreator.Create(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } using (var transaction = context.Database.BeginTransaction()) { try { Seed(context); context.SaveChanges(); transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } protected virtual void Seed(TContext context) { } } }
Apply SqliteForeignKeyIndexConvention right after the ForeignKeyIndexConvetion.
Issue_21: Apply SqliteForeignKeyIndexConvention right after the ForeignKeyIndexConvetion.
C#
apache-2.0
liujunhua/SQLiteCodeFirst,msallin/SQLiteCodeFirst
99ba598b2b3a8b66d1a2230b3361d0e2abc0aa6b
resharper/resharper-unity/src/Unity/Yaml/ProjectModel/MetaProjectFileType.cs
resharper/resharper-unity/src/Unity/Yaml/ProjectModel/MetaProjectFileType.cs
using JetBrains.Annotations; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel { [ProjectFileTypeDefinition(Name)] public class MetaProjectFileType : YamlProjectFileType { public new const string Name = "Meta"; [UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; } public MetaProjectFileType() : base(Name, "Unity Yaml", new[] { UnityFileExtensions.MetaFileExtensionWithDot }) { } } }
using JetBrains.Annotations; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration; using JetBrains.ReSharper.Plugins.Yaml.ProjectModel; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel { [ProjectFileTypeDefinition(Name)] public class MetaProjectFileType : YamlProjectFileType { public new const string Name = "Meta"; [UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; } public MetaProjectFileType() : base(Name, "Unity Meta File", new[] { UnityFileExtensions.MetaFileExtensionWithDot }) { } } }
Fix incorrect project file type description
Fix incorrect project file type description
C#
apache-2.0
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
258a19fdf5b1ff6ced2ca2e59c0ddc8fd217ca0c
BTCPayServer/Views/Home/SwaggerDocs.cshtml
BTCPayServer/Views/Home/SwaggerDocs.cshtml
@inject BTCPayServer.Security.ContentSecurityPolicies csp @{ Layout = null; csp.Add("script-src", "https://cdn.jsdelivr.net"); csp.Add("worker-src", "blob:"); } <!DOCTYPE html> <html> <head> <title>BTCPay Server Greenfield API</title> <!-- needed for adaptive design --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true"> <link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true"> <!-- ReDoc doesn't change outer page styles --> <style> body { margin: 0; padding: 0; } </style> </head> <body> @*Ignore this, this is for making the test ClickOnAllSideMenus happy*@ <div class="navbar-brand" style="visibility:collapse;"></div> <redoc spec-url="@Url.ActionLink("Swagger")"></redoc> <script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.45/bundles/redoc.standalone.js" integrity="sha384-RC31+q3tyqdcilXYaU++ii/FAByqeZ+sjKUHMJ8hMzIY5k4kzNqi4Ett88EZ/4lq" crossorigin="anonymous"></script> </body> </html>
@inject BTCPayServer.Security.ContentSecurityPolicies csp @{ Layout = null; csp.Add("script-src", "https://cdn.jsdelivr.net"); csp.Add("worker-src", "blob: self"); } <!DOCTYPE html> <html> <head> <title>BTCPay Server Greenfield API</title> <!-- needed for adaptive design --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true"> <link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true"> <!-- ReDoc doesn't change outer page styles --> <style> body { margin: 0; padding: 0; } </style> </head> <body> @*Ignore this, this is for making the test ClickOnAllSideMenus happy*@ <div class="navbar-brand" style="visibility:collapse;"></div> <redoc spec-url="@Url.ActionLink("Swagger")"></redoc> <script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.45/bundles/redoc.standalone.js" integrity="sha384-RC31+q3tyqdcilXYaU++ii/FAByqeZ+sjKUHMJ8hMzIY5k4kzNqi4Ett88EZ/4lq" crossorigin="anonymous"></script> </body> </html>
Make CSP more specific for docs
Make CSP more specific for docs
C#
mit
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
6ca099ff17bb6734de780021a7c1c507341e2ac9
Database.Migrations/Migrations/2-TodaysTestResultsView.cs
Database.Migrations/Migrations/2-TodaysTestResultsView.cs
using BroadbandSpeedStats.Database.Schema; using FluentMigrator; namespace BroadbandSpeedTests.Database.Migrations.Migrations { [Migration(20170228)] public class TodaysTestResultsView : Migration { public override void Up() { Execute.Sql($@" CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}], [{Views.TodaysTestResults.Columns.Timestamp}], [{Views.TodaysTestResults.Columns.PingTime}], [{Views.TodaysTestResults.Columns.DownloadSpeed}], [{Views.TodaysTestResults.Columns.UploadSpeed}] FROM [dbo].[{Views.TodaysTestResults.SourceTable}] WHERE WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0 ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC GO"); } public override void Down() { Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]"); } } }
using BroadbandSpeedStats.Database.Schema; using FluentMigrator; namespace BroadbandSpeedTests.Database.Migrations.Migrations { [Migration(20170228)] public class TodaysTestResultsView : Migration { public override void Up() { Execute.Sql($@" CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}], [{Views.TodaysTestResults.Columns.Timestamp}], [{Views.TodaysTestResults.Columns.PingTime}], [{Views.TodaysTestResults.Columns.DownloadSpeed}], [{Views.TodaysTestResults.Columns.UploadSpeed}] FROM [dbo].[{Views.TodaysTestResults.SourceTable}] WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0 ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC GO"); } public override void Down() { Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]"); } } }
Fix a typo in a view
Fix a typo in a view
C#
mit
adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats
e86834b74060d5fc7e2e9314142316b74ccf821b
osu.Game/Screens/Edit/Verify/VisibilitySection.cs
osu.Game/Screens/Edit/Verify/VisibilitySection.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Overlays; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { internal class VisibilitySection : EditorRoundedScreenSettingsSection { [Resolved] private VerifyScreen verify { get; set; } private readonly IssueType[] configurableIssueTypes = { IssueType.Warning, IssueType.Error, IssueType.Negligible }; protected override string Header => "Visibility"; [BackgroundDependencyLoader] private void load(OverlayColourProvider colours) { foreach (IssueType issueType in configurableIssueTypes) { var checkbox = new SettingsCheckbox { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, LabelText = issueType.ToString() }; checkbox.Current.Default = !verify.HiddenIssueTypes.Contains(issueType); checkbox.Current.SetDefault(); checkbox.Current.BindValueChanged(state => { if (!state.NewValue) verify.HiddenIssueTypes.Add(issueType); else verify.HiddenIssueTypes.Remove(issueType); }); Flow.Add(checkbox); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Overlays; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { internal class VisibilitySection : EditorRoundedScreenSettingsSection { [Resolved] private VerifyScreen verify { get; set; } private readonly IssueType[] configurableIssueTypes = { IssueType.Warning, IssueType.Error, IssueType.Negligible }; protected override string Header => "Visibility"; [BackgroundDependencyLoader] private void load(OverlayColourProvider colours) { var hiddenIssueTypes = verify.HiddenIssueTypes.GetBoundCopy(); foreach (IssueType issueType in configurableIssueTypes) { var checkbox = new SettingsCheckbox { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, LabelText = issueType.ToString() }; checkbox.Current.Default = !hiddenIssueTypes.Contains(issueType); checkbox.Current.SetDefault(); checkbox.Current.BindValueChanged(state => { if (!state.NewValue) hiddenIssueTypes.Add(issueType); else hiddenIssueTypes.Remove(issueType); }); Flow.Add(checkbox); } } } }
Use local bound copy for `HiddenIssueTypes`
Use local bound copy for `HiddenIssueTypes`
C#
mit
smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu
44578c2d43db3cea223f7dee543b34500d70f6f4
src/Effects/IBaseEffect.cs
src/Effects/IBaseEffect.cs
namespace SoxSharp.Effects { public interface IBaseEffect { string Name { get; } bool IsValid(); string ToString(); } }
namespace SoxSharp.Effects { public interface IBaseEffect { string Name { get; } string ToString(); } }
Revert "Added method to perform validity check for effect parameters"
Revert "Added method to perform validity check for effect parameters" This reverts commit 819b807fb9e789bc2e47f8463735b2c745ca0361.
C#
apache-2.0
igece/SoxSharp
5efe7f8dad174336165b96dbda2707a083ca4c9f
plugins/PlaysReplacements/PlaysReplacements.cs
plugins/PlaysReplacements/PlaysReplacements.cs
using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces; using StreamCompanionTypes.Interfaces.Sources; namespace PlaysReplacements { public class PlaysReplacements : IPlugin, ITokensSource { private int Plays, Retrys; private Tokens.TokenSetter _tokenSetter; private string lastMapSearchString = ""; public string Description { get; } = ""; public string Name { get; } = nameof(PlaysReplacements); public string Author { get; } = "Piotrekol"; public string Url { get; } = ""; public string UpdateUrl { get; } = ""; public PlaysReplacements() { _tokenSetter = Tokens.CreateTokenSetter(Name); } public void CreateTokens(MapSearchResult map) { if (map.Action == OsuStatus.Playing) { if (lastMapSearchString == map.MapSearchString) Retrys++; else Plays++; lastMapSearchString = map.MapSearchString; } _tokenSetter("plays", Plays); _tokenSetter("retrys", Retrys); } } }
using StreamCompanionTypes.DataTypes; using StreamCompanionTypes.Enums; using StreamCompanionTypes.Interfaces; using StreamCompanionTypes.Interfaces.Sources; namespace PlaysReplacements { public class PlaysReplacements : IPlugin, ITokensSource { private int Plays, Retrys; private Tokens.TokenSetter _tokenSetter; public string Description { get; } = ""; public string Name { get; } = nameof(PlaysReplacements); public string Author { get; } = "Piotrekol"; public string Url { get; } = ""; public string UpdateUrl { get; } = ""; public PlaysReplacements() { _tokenSetter = Tokens.CreateTokenSetter(Name); UpdateTokens(); } public void CreateTokens(MapSearchResult map) { //ignore replays/spect if (map.Action != OsuStatus.Playing) return; switch (map.SearchArgs.EventType) { case OsuEventType.SceneChange: case OsuEventType.MapChange: Plays++; break; case OsuEventType.PlayChange: Retrys++; break; } UpdateTokens(); } private void UpdateTokens() { _tokenSetter("plays", Plays); _tokenSetter("retrys", Retrys); } } }
Refactor plays/retries counting using osu events
Misc: Refactor plays/retries counting using osu events
C#
mit
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
22a5df6309aad3ab7f075c38e7617eee64c4c12c
osu.Game.Rulesets.Catch/UI/CatcherTrailSprite.cs
osu.Game.Rulesets.Catch/UI/CatcherTrailSprite.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherTrailSprite : PoolableDrawable { public Texture Texture { set => sprite.Texture = value; } private readonly Sprite sprite; public CatcherTrailSprite() { InternalChild = sprite = new Sprite { RelativeSizeAxes = Axes.Both }; Size = new Vector2(CatcherArea.CATCHER_SIZE); // Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling. OriginPosition = new Vector2(0.5f, 0.06f) * CatcherArea.CATCHER_SIZE; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Game.Rulesets.Catch.UI { public class CatcherTrailSprite : PoolableDrawable { public Texture Texture { set => sprite.Texture = value; } private readonly Sprite sprite; public CatcherTrailSprite() { InternalChild = sprite = new Sprite { RelativeSizeAxes = Axes.Both }; Size = new Vector2(CatcherArea.CATCHER_SIZE); // Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling. OriginPosition = new Vector2(0.5f, 0.06f) * CatcherArea.CATCHER_SIZE; } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } }
Clear all transforms of catcher trail sprite before returned to pool
Clear all transforms of catcher trail sprite before returned to pool
C#
mit
smoogipooo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu
01e5ca24e916f8506f386e86ea99239977a9be0e
src/Unity.Interception.Serilog.Tests/NullTests.cs
src/Unity.Interception.Serilog.Tests/NullTests.cs
using System; using FluentAssertions; using Microsoft.Practices.Unity; using Unity.Interception.Serilog.Tests.Support; using Xunit; namespace Unity.Interception.Serilog.Tests { public class NullTests { [Fact] public void NullMembersShouldThrow() { var container = new UnityContainer(); Action[] actions = { () => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null), () => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: first"); } } [Fact] public void NullContainerShouldThrow() { Action[] actions = { () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager()) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: container"); } } } }
using System; using FluentAssertions; using Microsoft.Practices.Unity; using Unity.Interception.Serilog.Tests.Support; using Xunit; namespace Unity.Interception.Serilog.Tests { public class NullTests { [Fact] public void NullMembersShouldThrow() { var container = new UnityContainer(); Action[] actions = { () => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null), () => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null), () => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>(); } } [Fact] public void NullContainerShouldThrow() { Action[] actions = { () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()), () => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager()) }; foreach (var action in actions) { action.ShouldThrow<ArgumentNullException>(); } } } }
Remove test on argument null exception message
Remove test on argument null exception message
C#
mit
johanclasson/Unity.Interception.Serilog
afdfeb578966593681699c423ed970da01cebad3
src/SIM.Client/Commands/InstallCommandFacade.cs
src/SIM.Client/Commands/InstallCommandFacade.cs
namespace SIM.Client.Commands { using CommandLine; using JetBrains.Annotations; using SIM.Core.Commands; public class InstallCommandFacade : InstallCommand { [UsedImplicitly] public InstallCommandFacade() { } [Option('n', "name", Required = true)] public override string Name { get; set; } [Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")] public override string SqlPrefix { get; set; } [Option('p', "product")] public override string Product { get; set; } [Option('v', "version")] public override string Version { get; set; } [Option('r', "revision")] public override string Revision { get; set; } [Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)] public override bool? AttachDatabases { get; set; } } }
namespace SIM.Client.Commands { using CommandLine; using JetBrains.Annotations; using SIM.Core.Commands; public class InstallCommandFacade : InstallCommand { [UsedImplicitly] public InstallCommandFacade() { } [Option('n', "name", Required = true)] public override string Name { get; set; } [Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")] public override string SqlPrefix { get; set; } [Option('p', "product")] public override string Product { get; set; } [Option('v', "version")] public override string Version { get; set; } [Option('r', "revision")] public override string Revision { get; set; } [Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)] public override bool? AttachDatabases { get; set; } [Option('u', "skipUnnecessaryFiles", HelpText = "Skip unnecessary files to speed up installation", DefaultValue = AttachDatabasesDefault)] public override bool? SkipUnnecessaryFiles { get; set; } } }
Add option to install command
Add option to install command
C#
mit
Brad-Christie/Sitecore-Instance-Manager,Sitecore/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager
6ddab5650f1f87f64c8674e39d15d91a3ca4dcf4
src/Marten/Services/ConcurrentUpdateException.cs
src/Marten/Services/ConcurrentUpdateException.cs
using System; namespace Marten.Services { public class ConcurrentUpdateException : Exception { public ConcurrentUpdateException(Exception innerException) : base("Write collission detected while commiting the transaction.", innerException) { } } }
using System; namespace Marten.Services { public class ConcurrentUpdateException : Exception { public ConcurrentUpdateException(Exception innerException) : base("Write collision detected while commiting the transaction.", innerException) { } } }
Fix spelling mistake, 'collission' => 'collision'
Fix spelling mistake, 'collission' => 'collision'
C#
mit
mysticmind/marten,ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten,mysticmind/marten,JasperFx/Marten,JasperFx/Marten,mysticmind/marten,mysticmind/marten,mdissel/Marten,ericgreenmix/marten,mdissel/Marten,JasperFx/Marten
a7044a27b344bb2b978757894ad2dcc76378314d
src/THNETII.DependencyInjection.Nesting/NestedServicesServiceCollectionExtensions.cs
src/THNETII.DependencyInjection.Nesting/NestedServicesServiceCollectionExtensions.cs
using Microsoft.Extensions.DependencyInjection; using System; namespace THNETII.DependencyInjection.Nesting { public static class NestedServicesServiceCollectionExtensions { public static IServiceCollection AddNestedServices( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) { throw new NotImplementedException(); return rootServices; } } }
using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; namespace THNETII.DependencyInjection.Nesting { public static class NestedServicesServiceCollectionExtensions { public static IServiceCollection AddNestedServices( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) { return AddNestedServices<string>( rootServices, key, StringComparer.OrdinalIgnoreCase, configureServices ); } public static IServiceCollection AddNestedServices<T>( this IServiceCollection rootServices, string key, Action<INestedServiceCollection> configureServices) => AddNestedServices<T>(rootServices, key, StringComparer.OrdinalIgnoreCase, configureServices); public static IServiceCollection AddNestedServices<T>( this IServiceCollection rootServices, string key, IEqualityComparer<string> keyComparer, Action<INestedServiceCollection> configureServices) { throw new NotImplementedException(); return rootServices; } } }
Add Nesting ServiceCollection Extension method overloads
Add Nesting ServiceCollection Extension method overloads
C#
mit
thnetii/dotnet-common
bd16be64689be0632a7fab4fb058afb9be1e4eb0
Ext.NET/IntegerExtension.cs
Ext.NET/IntegerExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ext.NET { class IntegerExtension { public static void Times(this int n, Action<int> action) { for (int i = 0; i < n; ++i) { action(i); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ext.NET { class IntegerExtension { public static void Times(this int n, Action<int> action) { for (int i = 0; i < n; ++i) { action(i); } } public static IEnumerable<int> To(this int n, int to) { if (n == to) { yield return n; } else if (to > n) { for (int i = n; i < to; ++i) yield return i; } else { for (int i = n; i > to; --i) yield return i; } } } }
Add Int.To(Int) Method, which allow to generate a sequence between two numbers.
Add Int.To(Int) Method, which allow to generate a sequence between two numbers.
C#
mit
garlab/Ext.NET
19c925517b59a9fd25b2f51eb5daaa676a1f5dbf
Portal.CMS.Web/Areas/Admin/Views/Copy/_Copy.cshtml
Portal.CMS.Web/Areas/Admin/Views/Copy/_Copy.cshtml
@model Portal.CMS.Entities.Entities.Copy.Copy @using Portal.CMS.Web.Areas.Admin.Helpers; @{ Layout = ""; var isAdmin = UserHelper.IsAdmin; } <script type="text/javascript"> $(document).ready(function () { tinymce.init({ selector: '#copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', setup:function(ed) { ed.on('change', function(e) { var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() }; $.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'}); }); } }); }); </script> <div class="copy-wrapper"> @if (isAdmin) { <div class="box-title">@Model.CopyName</div> } <div id="copy-@Model.CopyId" class="@(UserHelper.IsAdmin ? "admin" : "") copy-block"> @Html.Raw(Model.CopyBody) </div> </div>
@model Portal.CMS.Entities.Entities.Copy.Copy @using Portal.CMS.Web.Areas.Admin.Helpers; @{ Layout = ""; var isAdmin = UserHelper.IsAdmin; } <script type="text/javascript"> $(document).ready(function () { tinymce.init({ selector: '.copy-@(Model.CopyId).admin', inline: true, plugins: ['advlist autolink lists link image charmap anchor searchreplace visualblocks code fullscreen media table contextmenu paste'], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', setup:function(ed) { ed.on('change', function(e) { var dataParams = { "copyId": @Model.CopyId, "copyName": "@Model.CopyName", "copyBody": ed.getContent() }; $.ajax({data: dataParams, type: 'POST', cache: false, url: '/Admin/Copy/Inline'}); $('.copy-@(Model.CopyId)').html(ed.getContent()); }); } }); }); </script> <div class="copy-wrapper"> @if (isAdmin) { <div class="box-title">@Model.CopyName</div> } <div class="@(UserHelper.IsAdmin ? "admin" : "") copy-@Model.CopyId copy-block"> @Html.Raw(Model.CopyBody) </div> </div>
Copy Updates Other Copy elements of the Same Type on the Same Page When Saving
Copy Updates Other Copy elements of the Same Type on the Same Page When Saving
C#
mit
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
0a5ffb934229fdbd71eddcd9a6371d473fa29e16
build.cake
build.cake
#tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj"); }); Task("Build") .IsDependentOn("NugetRestore") .Does(()=> { DotNetCoreMSBuild("FibonacciHeap.sln"); }); Task("NugetRestore") .IsDependentOn("Clean") .Does(()=> { DotNetCoreRestore(); }); Task("NugetPack") .IsDependentOn("Build") .Does(()=> { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "../../nupkgs" }; DotNetCorePack("src/FibonacciHeap", settings); }); Task("Clean") .Does(()=> { CleanDirectories("**/bin/**"); CleanDirectories("**/obj/**"); CleanDirectories("nupkgs"); }); RunTarget(target);
#tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj"); }); Task("Build") .IsDependentOn("NugetRestore") .Does(()=> { DotNetCoreMSBuild("FibonacciHeap.sln"); }); Task("NugetRestore") .IsDependentOn("Clean") .Does(()=> { DotNetCoreRestore(); }); Task("NugetPack") .IsDependentOn("Clean") .Does(()=> { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "nupkgs" }; DotNetCorePack("src/FibonacciHeap", settings); }); Task("Clean") .Does(()=> { CleanDirectories("**/bin/**"); CleanDirectories("**/obj/**"); CleanDirectories("nupkgs"); }); RunTarget(target);
Fix output path for nuget package.
Fix output path for nuget package.
C#
mit
sqeezy/FibonacciHeap,sqeezy/FibonacciHeap
7e47c72f4240c871c47e7fc9c09904d1e6fcee0a
src/Serilog.Sinks.Graylog/LoggerConfigurationGrayLogExtensions.cs
src/Serilog.Sinks.Graylog/LoggerConfigurationGrayLogExtensions.cs
using Serilog.Configuration; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Graylog.Helpers; using Serilog.Sinks.Graylog.Transport; namespace Serilog.Sinks.Graylog { public static class LoggerConfigurationGrayLogExtensions { public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, GraylogSinkOptions options) { var sink = (ILogEventSink) new GraylogSink(options); return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel); } public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, string hostnameOrAddress, int port, TransportType transportType, LogEventLevel minimumLogEventLevel = LevelAlias.Minimum, MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType, int shortMessageMaxLength = 500, int stackTraceDepth = 10, string facility = GraylogSinkOptions.DefaultFacility ) { var options = new GraylogSinkOptions { HostnameOrAdress = hostnameOrAddress, Port = port, TransportType = transportType, MinimumLogEventLevel = minimumLogEventLevel, MessageGeneratorType = messageIdGeneratorType, ShortMessageMaxLength = shortMessageMaxLength, StackTraceDepth = stackTraceDepth, Facility = facility }; return loggerSinkConfiguration.Graylog(options); } } }
using Serilog.Configuration; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Graylog.Helpers; using Serilog.Sinks.Graylog.Transport; namespace Serilog.Sinks.Graylog { public static class LoggerConfigurationGrayLogExtensions { public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, GraylogSinkOptions options) { var sink = (ILogEventSink) new GraylogSink(options); return loggerSinkConfiguration.Sink(sink, options.MinimumLogEventLevel); } public static LoggerConfiguration Graylog(this LoggerSinkConfiguration loggerSinkConfiguration, string hostnameOrAddress, int port, TransportType transportType, LogEventLevel minimumLogEventLevel = LevelAlias.Minimum, MessageIdGeneratortype messageIdGeneratorType = GraylogSinkOptions.DefaultMessageGeneratorType, int shortMessageMaxLength = GraylogSinkOptions.DefaultShortMessageMaxLength, int stackTraceDepth = GraylogSinkOptions.DefaultStackTraceDepth, string facility = GraylogSinkOptions.DefaultFacility ) { var options = new GraylogSinkOptions { HostnameOrAdress = hostnameOrAddress, Port = port, TransportType = transportType, MinimumLogEventLevel = minimumLogEventLevel, MessageGeneratorType = messageIdGeneratorType, ShortMessageMaxLength = shortMessageMaxLength, StackTraceDepth = stackTraceDepth, Facility = facility }; return loggerSinkConfiguration.Graylog(options); } } }
Change extension method default parameters to use constants
Change extension method default parameters to use constants
C#
mit
whir1/serilog-sinks-graylog
16829b929c4ca3d98deb0ddc13a404c44774f40c
Src/Veil/Compiler/VeilTemplateCompiler.EmitWriteLiteral.cs
Src/Veil/Compiler/VeilTemplateCompiler.EmitWriteLiteral.cs
using Veil.Parser; namespace Veil.Compiler { internal partial class VeilTemplateCompiler<T> { private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node) { LoadWriterToStack(); emitter.LoadConstant(node.LiteralContent); CallWriteFor(typeof(string)); } } }
using Veil.Parser; namespace Veil.Compiler { internal partial class VeilTemplateCompiler<T> { private void EmitWriteLiteral(SyntaxTreeNode.WriteLiteralNode node) { if (string.IsNullOrEmpty(node.LiteralContent)) return; LoadWriterToStack(); emitter.LoadConstant(node.LiteralContent); CallWriteFor(typeof(string)); } } }
Optimize away empty string literals.
Optimize away empty string literals.
C#
mit
csainty/Veil,csainty/Veil
26271971172d2c6d20e5a0aadd89f40b5bcabdbd
ArduinoWindowsRemoteControl/UI/EditCommandForm.cs
ArduinoWindowsRemoteControl/UI/EditCommandForm.cs
using ArduinoWindowsRemoteControl.Helpers; using ArduinoWindowsRemoteControl.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ArduinoWindowsRemoteControl.UI { public partial class EditCommandForm : Form { private List<int> _pressedButtons = new List<int>(); public EditCommandForm() { InitializeComponent(); cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray()); } private void btCancel_Click(object sender, EventArgs e) { Close(); } private void tbCommand_KeyDown(object sender, KeyEventArgs e) { if (!_pressedButtons.Contains(e.KeyValue)) { tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue); _pressedButtons.Add(e.KeyValue); } e.Handled = true; } private void tbCommand_KeyUp(object sender, KeyEventArgs e) { _pressedButtons.Remove(e.KeyValue); e.Handled = true; } private void tbCommand_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } } }
using ArduinoWindowsRemoteControl.Helpers; using ArduinoWindowsRemoteControl.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ArduinoWindowsRemoteControl.UI { public partial class EditCommandForm : Form { private List<int> _pressedButtons = new List<int>(); private bool _isKeyStrokeEnabled = false; public EditCommandForm() { InitializeComponent(); cbRemoteCommand.Items.AddRange(EnumHelpers.GetAvailableEnumValues<RemoteCommand>().ToArray()); } private void btCancel_Click(object sender, EventArgs e) { Close(); } private void tbCommand_KeyDown(object sender, KeyEventArgs e) { if (!_pressedButtons.Contains(e.KeyValue)) { //key command ended, start new one if (_pressedButtons.Count == 0) { _isKeyStrokeEnabled = false; } if (_isKeyStrokeEnabled) { tbCommand.Text += "-"; } else { if (tbCommand.Text.Length > 0) tbCommand.Text += ","; } tbCommand.Text += WinAPIHelpers.GetKeyStringForVirtualCode((byte)e.KeyValue); tbCommand.SelectionStart = tbCommand.Text.Length; _pressedButtons.Add(e.KeyValue); } else { if (_pressedButtons.Last() == e.KeyValue) { _isKeyStrokeEnabled = true; } } e.Handled = true; } private void tbCommand_KeyUp(object sender, KeyEventArgs e) { _pressedButtons.Remove(e.KeyValue); e.Handled = true; } private void tbCommand_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } } }
Add ability to enter commands
Add ability to enter commands
C#
mit
StanislavUshakov/ArduinoWindowsRemoteControl
74b3797b9f72722d406fe47307d2652ffe093814
ExRam.Gremlinq/Gremlin/Steps/ValuesGremlinStep.cs
ExRam.Gremlinq/Gremlin/Steps/ValuesGremlinStep.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; namespace ExRam.Gremlinq { public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep { private readonly Expression<Func<TSource, TTarget>>[] _projections; public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections) { this._projections = projections; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { yield return new TerminalGremlinStep( "values", this._projections .Select(projection => { if (projection.Body is MemberExpression memberExpression) return model.GetIdentifier(memberExpression.Member.Name); throw new NotSupportedException(); }) .ToImmutableList()); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; namespace ExRam.Gremlinq { public sealed class ValuesGremlinStep<TSource, TTarget> : NonTerminalGremlinStep { private readonly Expression<Func<TSource, TTarget>>[] _projections; public ValuesGremlinStep(Expression<Func<TSource, TTarget>>[] projections) { this._projections = projections; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { var keys = this._projections .Select(projection => { if (projection.Body is MemberExpression memberExpression) return model.GetIdentifier(memberExpression.Member.Name); throw new NotSupportedException(); }) .ToArray(); var numberOfIdSteps = keys .OfType<T>() .Count(x => x == T.Id); var propertyKeys = keys .OfType<string>() .Cast<object>() .ToArray(); if (numberOfIdSteps > 1 || (numberOfIdSteps > 0 && propertyKeys.Length > 0)) throw new NotSupportedException(); if (numberOfIdSteps > 0) yield return new TerminalGremlinStep("id"); else { yield return new TerminalGremlinStep( "values", propertyKeys .ToImmutableList()); } } } }
Make one of two red tests green by implementing basic support for the Values-method with Id-Property.
Make one of two red tests green by implementing basic support for the Values-method with Id-Property.
C#
mit
ExRam/ExRam.Gremlinq
ecb7537dc978de646d3ff3ccb27b73ba18794c9f
IPOCS_Programmer/ObjectTypes/PointsMotor_Pulse.cs
IPOCS_Programmer/ObjectTypes/PointsMotor_Pulse.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPOCS_Programmer.ObjectTypes { public class PointsMotor_Pulse : PointsMotor { public override byte motorTypeId { get { return 1; } } public byte ThrowLeftOutput { get; set; } public byte ThrowRightOutput { get; set; } public byte positionPin { get; set; } public bool reverseStatus { get; set; } public override List<byte> Serialize() { var vector = new List<byte>(); vector.Add(motorTypeId); vector.Add(this.ThrowLeftOutput); vector.Add(this.ThrowRightOutput); vector.Add(positionPin); vector.Add((byte)(reverseStatus ? 1 : 0)); return vector; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IPOCS_Programmer.ObjectTypes { public class PointsMotor_Pulse : PointsMotor { public override byte motorTypeId { get { return 1; } } public byte ThrowLeftOutput { get; set; } public byte ThrowRightOutput { get; set; } public byte positionPin { get; set; } public bool reverseStatus { get; set; } public bool lowToThrow { get; set; } public override List<byte> Serialize() { var vector = new List<byte>(); vector.Add(motorTypeId); vector.Add(this.ThrowLeftOutput); vector.Add(this.ThrowRightOutput); vector.Add(positionPin); vector.Add((byte)(reverseStatus ? 1 : 0)); vector.Add((byte)(lowToThrow ? 1 : 0)); return vector; } } }
Make it configurable if high or low throws.
Make it configurable if high or low throws. Resolves #7
C#
mit
GMJS/gmjs_ocs_dpt