commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
0dd5b3bac881b6aa620adcc953650c1336ba8ea9
|
add IsMaxed property to Counter
|
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
|
TCC.Core/Data/Counter.cs
|
TCC.Core/Data/Counter.cs
|
using System;
using System.Windows.Threading;
namespace TCC.Data
{
public class Counter : TSPropertyChanged
{
//TODO use events here
private int _val;
private bool _isMaxed;
private readonly DispatcherTimer _expire;
private readonly bool _autoexpire;
public int Val
{
get => _val;
set
{
if (_val == value) return;
_val = value;
IsMaxed = Val == MaxValue;
RefreshTimer();
NPC();
}
}
public bool IsMaxed
{
get => _isMaxed;
private set
{
if (_isMaxed == value) return;
_isMaxed = value;
NPC();
}
}
public int MaxValue { get; }
public Counter(int max, bool autoexpire)
{
Dispatcher = Dispatcher.CurrentDispatcher;
MaxValue = max;
_autoexpire = autoexpire;
_expire = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(9000) };
_expire.Tick += (s, ev) => Val = 0;
}
private void RefreshTimer()
{
_expire.Stop();
if (_val == 0) return;
if (!_autoexpire) return;
_expire.Start();
}
}
}
|
using System;
using System.Windows.Threading;
namespace TCC.Data
{
public class Counter : TSPropertyChanged
{
//TODO use events here
private int _val;
private readonly DispatcherTimer _expire;
private readonly bool _autoexpire;
public event Action Maxed;
public int Val
{
get => _val;
set
{
if (_val == value) return;
_val = value;
Maxed?.Invoke();
RefreshTimer();
NPC();
}
}
public int MaxValue { get; }
public Counter(int max, bool autoexpire)
{
Dispatcher = Dispatcher.CurrentDispatcher;
MaxValue = max;
_autoexpire = autoexpire;
_expire = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(9000) };
_expire.Tick += (s, ev) => Val = 0;
}
private void RefreshTimer()
{
_expire.Stop();
if (_val == 0) return;
if (!_autoexpire) return;
_expire.Start();
}
}
}
|
mit
|
C#
|
78905df6bed536abf6fe3d295f9e03ab522adbd8
|
Remove todo comments
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Tests/UnitTests/SmartHeaderTests.cs
|
WalletWasabi.Tests/UnitTests/SmartHeaderTests.cs
|
using NBitcoin;
using NBitcoin.DataEncoders;
using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Blockchain;
using WalletWasabi.Blockchain.Blocks;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class SmartHeaderTests
{
[Fact]
public void ConstructorTests()
{
var blockTime = DateTimeOffset.UtcNow;
new SmartHeader(uint256.Zero, uint256.One, 0, blockTime);
new SmartHeader(uint256.Zero, uint256.One, 1, blockTime);
new SmartHeader(uint256.Zero, uint256.One, 1, blockTime);
Assert.Throws<ArgumentNullException>(() => new SmartHeader(null, uint256.One, 1, blockTime));
Assert.Throws<ArgumentNullException>(() => new SmartHeader(uint256.Zero, null, 1, blockTime));
Assert.Throws<InvalidOperationException>(() => new SmartHeader(uint256.Zero, uint256.Zero, 1, blockTime));
}
[Fact]
public void StartingHeaderTests()
{
var startingMain = SmartHeader.GetStartingHeader(Network.Main);
var startingTest = SmartHeader.GetStartingHeader(Network.TestNet);
var startingReg = SmartHeader.GetStartingHeader(Network.RegTest);
var expectedHashMain = new uint256("0000000000000000001c8018d9cb3b742ef25114f27563e3fc4a1902167f9893");
var expectedPrevHashMain = new uint256("000000000000000000cbeff0b533f8e1189cf09dfbebf57a8ebe349362811b80");
uint expectedHeightMain = 481824;
var expectedTimeMain = DateTimeOffset.FromUnixTimeSeconds(1503539857);
var expectedHashTest = new uint256("00000000000f0d5edcaeba823db17f366be49a80d91d15b77747c2e017b8c20a");
var expectedPrevHashTest = new uint256("0000000000211a4d54bceb763ea690a4171a734c48d36f7d8e30b51d6df6ea85");
uint expectedHeightTest = 828575;
var expectedTimeTest = DateTimeOffset.FromUnixTimeSeconds(1463079943);
var expectedHashReg = Network.RegTest.GenesisHash;
var expectedPrevHashReg = uint256.Zero;
uint expectedHeightReg = 0;
var expectedTimeReg = Network.RegTest.GetGenesis().Header.BlockTime;
Assert.Equal(expectedHashMain, startingMain.BlockHash);
Assert.Equal(expectedPrevHashMain, startingMain.PrevHash);
Assert.Equal(expectedHeightMain, startingMain.Height);
Assert.Equal(expectedTimeMain, startingMain.BlockTime);
Assert.Equal(expectedHashTest, startingTest.BlockHash);
Assert.Equal(expectedPrevHashTest, startingTest.PrevHash);
Assert.Equal(expectedHeightTest, startingTest.Height);
Assert.Equal(expectedTimeTest, startingTest.BlockTime);
Assert.Equal(expectedHashReg, startingReg.BlockHash);
Assert.Equal(expectedPrevHashReg, startingReg.PrevHash);
Assert.Equal(expectedHeightReg, startingReg.Height);
Assert.Equal(expectedTimeReg, startingReg.BlockTime);
}
}
}
|
using NBitcoin;
using NBitcoin.DataEncoders;
using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Blockchain;
using WalletWasabi.Blockchain.Blocks;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class SmartHeaderTests
{
// TODO
// equality
// comparision
// line serialization
// need mempool too
[Fact]
public void ConstructorTests()
{
var blockTime = DateTimeOffset.UtcNow;
new SmartHeader(uint256.Zero, uint256.One, 0, blockTime);
new SmartHeader(uint256.Zero, uint256.One, 1, blockTime);
new SmartHeader(uint256.Zero, uint256.One, 1, blockTime);
Assert.Throws<ArgumentNullException>(() => new SmartHeader(null, uint256.One, 1, blockTime));
Assert.Throws<ArgumentNullException>(() => new SmartHeader(uint256.Zero, null, 1, blockTime));
Assert.Throws<InvalidOperationException>(() => new SmartHeader(uint256.Zero, uint256.Zero, 1, blockTime));
}
[Fact]
public void StartingHeaderTests()
{
var startingMain = SmartHeader.GetStartingHeader(Network.Main);
var startingTest = SmartHeader.GetStartingHeader(Network.TestNet);
var startingReg = SmartHeader.GetStartingHeader(Network.RegTest);
var expectedHashMain = new uint256("0000000000000000001c8018d9cb3b742ef25114f27563e3fc4a1902167f9893");
var expectedPrevHashMain = new uint256("000000000000000000cbeff0b533f8e1189cf09dfbebf57a8ebe349362811b80");
uint expectedHeightMain = 481824;
var expectedTimeMain = DateTimeOffset.FromUnixTimeSeconds(1503539857);
var expectedHashTest = new uint256("00000000000f0d5edcaeba823db17f366be49a80d91d15b77747c2e017b8c20a");
var expectedPrevHashTest = new uint256("0000000000211a4d54bceb763ea690a4171a734c48d36f7d8e30b51d6df6ea85");
uint expectedHeightTest = 828575;
var expectedTimeTest = DateTimeOffset.FromUnixTimeSeconds(1463079943);
var expectedHashReg = Network.RegTest.GenesisHash;
var expectedPrevHashReg = uint256.Zero;
uint expectedHeightReg = 0;
var expectedTimeReg = Network.RegTest.GetGenesis().Header.BlockTime;
Assert.Equal(expectedHashMain, startingMain.BlockHash);
Assert.Equal(expectedPrevHashMain, startingMain.PrevHash);
Assert.Equal(expectedHeightMain, startingMain.Height);
Assert.Equal(expectedTimeMain, startingMain.BlockTime);
Assert.Equal(expectedHashTest, startingTest.BlockHash);
Assert.Equal(expectedPrevHashTest, startingTest.PrevHash);
Assert.Equal(expectedHeightTest, startingTest.Height);
Assert.Equal(expectedTimeTest, startingTest.BlockTime);
Assert.Equal(expectedHashReg, startingReg.BlockHash);
Assert.Equal(expectedPrevHashReg, startingReg.PrevHash);
Assert.Equal(expectedHeightReg, startingReg.Height);
Assert.Equal(expectedTimeReg, startingReg.BlockTime);
}
}
}
|
mit
|
C#
|
b4b5e5fb28d2ccc4f3578c13a1c1a5da5e173993
|
Fix issue with navigation controller allowing children to be garbage collected when still in use
|
bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1
|
Source/Eto.Platform.iOS/Forms/Controls/NavigationHandler.cs
|
Source/Eto.Platform.iOS/Forms/Controls/NavigationHandler.cs
|
using System;
using MonoTouch.UIKit;
using Eto.Forms;
using MonoTouch.ObjCRuntime;
using Eto.Drawing;
using System.Collections.Generic;
using System.Linq;
namespace Eto.Platform.iOS.Forms.Controls
{
internal class RotatableNavigationController : UINavigationController
{
[Obsolete]
public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation)
{
return true;
}
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
return UIInterfaceOrientationMask.All;
}
}
public class NavigationHandler : IosControl<UIView, Navigation>, INavigation
{
readonly List<INavigationItem> items = new List<INavigationItem>();
public UINavigationController Navigation
{
get { return (UINavigationController)base.Controller; }
set { base.Controller = value; }
}
class Delegate : UINavigationControllerDelegate
{
public override void DidShowViewController(UINavigationController navigationController, UIViewController viewController, bool animated)
{
Handler.Widget.OnItemShown(EventArgs.Empty);
// need to get the view controllers to reset the references to the popped controllers
// this is due to how xamarin.ios keeps the controllers in an array
// and this resets that array
var controllers = Handler.Navigation.ViewControllers;
Handler.items.RemoveAll(r => !controllers.Contains(r.Content.GetViewController()));
/* for testing garbage collection after a view is popped
#if DEBUG
GC.Collect();
GC.WaitForPendingFinalizers();
#endif
/**/
}
WeakReference handler;
public NavigationHandler Handler { get { return (NavigationHandler)handler.Target; } set { handler = new WeakReference(value); } }
}
public NavigationHandler()
{
Navigation = new UINavigationController
{
WeakDelegate = new Delegate { Handler = this }
};
//Navigation.NavigationBar.Translucent = false;
//Navigation.EdgesForExtendedLayout = UIRectEdge.None;
//Navigation.AutomaticallyAdjustsScrollViewInsets = true;
}
public override UIView Control { get { return Navigation.View; } }
public void Push(INavigationItem item)
{
items.Add(item);
var view = item.Content.GetViewController();
view.NavigationItem.Title = item.Text;
view.View.SetFrameOrigin(new System.Drawing.PointF(0, 100));
//view.AutomaticallyAdjustsScrollViewInsets = true;
//if (view.RespondsToSelector(new Selector("setEdgesForExtendedLayout:")))
// view.EdgesForExtendedLayout = UIRectEdge.None;
view.View.Frame = new System.Drawing.RectangleF(0, 0, 0, 0);
view.View.AutoresizingMask = UIViewAutoresizing.All;
Navigation.PushViewController(view, true);
}
public void Pop()
{
Navigation.PopViewControllerAnimated(true);
}
public virtual Size ClientSize
{
get { return Size; }
set { Size = value; }
}
public bool RecurseToChildren { get { return true; } }
}
}
|
using System;
using MonoTouch.UIKit;
using Eto.Forms;
using MonoTouch.ObjCRuntime;
using Eto.Drawing;
namespace Eto.Platform.iOS.Forms.Controls
{
internal class RotatableNavigationController : UINavigationController
{
[Obsolete]
public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation)
{
return true;
}
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
return UIInterfaceOrientationMask.All;
}
}
public class NavigationHandler : IosControl<UIView, Navigation>, INavigation
{
public UINavigationController Navigation
{
get { return (UINavigationController)base.Controller; }
set { base.Controller = value; }
}
class Delegate : UINavigationControllerDelegate
{
public override void DidShowViewController(UINavigationController navigationController, UIViewController viewController, bool animated)
{
Handler.Widget.OnItemShown(EventArgs.Empty);
// need to get the view controllers to reset the references to the popped controllers
// this is due to how xamarin.ios keeps the controllers in an array
// and this resets that array
var controllers = Handler.Navigation.ViewControllers;
/* for testing garbage collection after a view is popped
#if DEBUG
GC.Collect();
GC.WaitForPendingFinalizers();
#endif
/**/
}
WeakReference handler;
public NavigationHandler Handler { get { return (NavigationHandler)handler.Target; } set { handler = new WeakReference(value); } }
}
public NavigationHandler()
{
Navigation = new UINavigationController
{
WeakDelegate = new Delegate { Handler = this }
};
//Navigation.NavigationBar.Translucent = false;
//Navigation.EdgesForExtendedLayout = UIRectEdge.None;
//Navigation.AutomaticallyAdjustsScrollViewInsets = true;
}
public override UIView Control { get { return Navigation.View; } }
public void Push(INavigationItem item)
{
var view = item.Content.GetViewController();
view.NavigationItem.Title = item.Text;
view.View.SetFrameOrigin(new System.Drawing.PointF(0, 100));
//view.AutomaticallyAdjustsScrollViewInsets = true;
//if (view.RespondsToSelector(new Selector("setEdgesForExtendedLayout:")))
// view.EdgesForExtendedLayout = UIRectEdge.None;
view.View.Frame = new System.Drawing.RectangleF(0, 0, 0, 0);
view.View.AutoresizingMask = UIViewAutoresizing.All;
Navigation.PushViewController(view, true);
}
public void Pop()
{
Navigation.PopViewControllerAnimated(true);
}
public virtual Size ClientSize
{
get { return Size; }
set { Size = value; }
}
public bool RecurseToChildren { get { return true; } }
}
}
|
bsd-3-clause
|
C#
|
2d7d846cda28aed28b50e50ce6f53d9be8979db1
|
add NotOnPrimativeType test
|
brettfo/roslyn,panopticoncentral/roslyn,sharwell/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,physhi/roslyn,panopticoncentral/roslyn,gafter/roslyn,wvdd007/roslyn,stephentoub/roslyn,bartdesmet/roslyn,physhi/roslyn,diryboy/roslyn,AmadeusW/roslyn,genlu/roslyn,jmarolf/roslyn,aelij/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,genlu/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,tmat/roslyn,eriawan/roslyn,KevinRansom/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,aelij/roslyn,jmarolf/roslyn,weltkante/roslyn,KevinRansom/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,tmat/roslyn,mavasani/roslyn,mavasani/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,sharwell/roslyn,AlekseyTs/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,tmat/roslyn,sharwell/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,jmarolf/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,physhi/roslyn,gafter/roslyn,genlu/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,mavasani/roslyn,diryboy/roslyn,AlekseyTs/roslyn,eriawan/roslyn,aelij/roslyn
|
src/Analyzers/CSharp/Tests/ConvertNameOf/ConvertNameOfTests.cs
|
src/Analyzers/CSharp/Tests/ConvertNameOf/ConvertNameOfTests.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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.ConvertNameOf;
using Microsoft.CodeAnalysis.CSharp.CSharpConvertNameOfCodeFixProvider;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNameOf
{
public partial class ConvertNameOfTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpConvertNameOfDiagnosticAnalyzer(), new CSharpConvertNameOfCodeFixProvider());
[Fact]
public async Task BasicType()
{
var text = @"
class Test
{
void Method()
{
var typeName = [||]typeof(Test).Name;
}
}
";
var expected = @"
class Test
{
void Method()
{
var typeName = [||]nameof(Test);
}
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact]
public async Task ClassLibraryType()
{
var text = @"
class Test
{
void Method()
{
var typeName = [||]typeof(String).Name;
}
}
";
var expected = @"
class Test
{
void Method()
{
var typeName = [||]nameof(String);
}
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact]
public async Task NotOnVariableContainingType()
{
var text = @"class Test
{
void Method()
{
var typeVar = typeof(String);[||]
var typeName = typeVar.Name;
}
}
";
await TestMissingInRegularAndScriptAsync(text);
}
[Fact]
public async Task NotOnPrimitiveType()
{
var text = @"class Test
{
void Method()
{
var typeName = [||]typeof(int).Name;
}
}
";
await TestMissingInRegularAndScriptAsync(text);
}
}
}
|
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.ConvertNameOf;
using Microsoft.CodeAnalysis.CSharp.CSharpConvertNameOfCodeFixProvider;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNameOf
{
public partial class ConvertNameOfTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpConvertNameOfDiagnosticAnalyzer(), new CSharpConvertNameOfCodeFixProvider());
[Fact]
public async Task BasicType()
{
var text = @"
class Test
{
void Method()
{
var typeName = [||]typeof(Test).Name;
}
}
";
var expected = @"
class Test
{
void Method()
{
var typeName = [||]nameof(Test);
}
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact]
public async Task ClassLibraryType()
{
var text = @"
class Test
{
void Method()
{
var typeName = [||]typeof(String).Name;
}
}
";
var expected = @"
class Test
{
void Method()
{
var typeName = [||]nameof(String);
}
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact]
public async Task NotOnVariableContainingType()
{
var text = @"class Test
{
void Method()
{
var typeVar = typeof(String);[||]
var typeName = typeVar.Name;
}
}
";
await TestMissingInRegularAndScriptAsync(text);
}
}
}
|
mit
|
C#
|
74ad5126c06c6098171954623bbaf9eb87a0ceed
|
Update DataMigration.cs comments (#9239)
|
xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2
|
src/OrchardCore/OrchardCore.Data.Abstractions/DataMigration.cs
|
src/OrchardCore/OrchardCore.Data.Abstractions/DataMigration.cs
|
using YesSql.Sql;
namespace OrchardCore.Data.Migration
{
/// <summary>
/// A <see cref="DataMigration"/> is discovered through method reflection
/// and runs sequentially from the Create() method through UpdateFromX().
/// </summary>
/// <example>
/// Usage of method implementations:
/// <code>
/// public class Migrations : DataMigration
/// {
/// public int Create() { return 1; } // or
/// public Task<int> CreateAsync() { return 1; }
/// public int UpdateFrom1() { return 2; } // or
/// public Task<int> UpdateFrom1Async() { return 2; }
/// public void Uninstall() { } // or
/// public Task UninstallAsync() { }
/// }
/// </code>
/// </example>
public abstract class DataMigration : IDataMigration
{
/// <inheritdocs />
public ISchemaBuilder SchemaBuilder { get; set; }
}
}
|
using YesSql.Sql;
namespace OrchardCore.Data.Migration
{
/// <summary>
/// A <see cref="DataMigration"/> is discovered through method reflection
/// and runs sequentially from the Create() method through UpdateFromX().
/// </summary>
/// <example>
/// Usage of method implementations:
/// <code>
/// public class Migrations : DataMigration
/// {
/// public void Create() { return 1; } // or
/// public Task CreateAsync() { return 1; }
/// public void UpdateFrom1() { return 2; } // or
/// public Task UpdateFrom1Async() { return 2; }
/// public void Uninstall() { } // or
/// public Task UninstallAsync() { }
/// }
/// </code>
/// </example>
public abstract class DataMigration : IDataMigration
{
/// <inheritdocs />
public ISchemaBuilder SchemaBuilder { get; set; }
}
}
|
bsd-3-clause
|
C#
|
761df62629496a24395eb76e30ad4f7cea50324b
|
Make sure our directories are there in SQLite3
|
shana/Akavache,akavache/Akavache,martijn00/Akavache,kmjonmastro/Akavache,mms-/Akavache,PureWeen/Akavache,Loke155/Akavache,ghuntley/AkavacheSandpit,bbqchickenrobot/Akavache,shana/Akavache,shiftkey/Akavache,christer155/Akavache,MarcMagnin/Akavache,MathieuDSTP/MyAkavache,gimsum/Akavache,jcomtois/Akavache
|
Akavache.Sqlite3/Registrations.cs
|
Akavache.Sqlite3/Registrations.cs
|
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reactive;
using System.Reactive.Linq;
namespace Akavache.Sqlite3
{
public class Registrations : IWantsToRegisterStuff
{
public void Register(Action<Func<object>, Type, string> registerFunction)
{
// NB: We want the most recently registered fs, since there really
// only should be one
var fs = RxApp.DependencyResolver.GetServices<IFilesystemProvider>().LastOrDefault();
if (fs == null)
{
throw new Exception("Failed to initialize Akavache properly. Do you have a reference to Akavache.dll?");
}
var dirs = new[] {
fs.GetDefaultLocalMachineCacheDirectory(),
fs.GetDefaultRoamingCacheDirectory(),
fs.GetDefaultSecretCacheDirectory(),
};
dirs.ToObservable()
.SelectMany(x => fs.CreateRecursive(x))
.Aggregate(Unit.Default, (acc, x) => acc)
.Wait();
var localCache = new Lazy<IBlobCache>(() =>
new SqlitePersistentBlobCache(Path.Combine(fs.GetDefaultLocalMachineCacheDirectory(), "blobs.db"), RxApp.TaskpoolScheduler));
registerFunction(() => localCache.Value, typeof(IBlobCache), "LocalMachine");
var userAccount = new Lazy<IBlobCache>(() =>
new SqlitePersistentBlobCache(Path.Combine(fs.GetDefaultRoamingCacheDirectory(), "blobs.db"), RxApp.TaskpoolScheduler));
registerFunction(() => userAccount.Value, typeof(IBlobCache), "UserAccount");
var secure = new Lazy<ISecureBlobCache>(() =>
new EncryptedBlobCache(Path.Combine(fs.GetDefaultSecretCacheDirectory(), "secret.db"), RxApp.TaskpoolScheduler));
registerFunction(() => secure.Value, typeof(ISecureBlobCache), null);
}
}
}
|
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Akavache.Sqlite3
{
public class Registrations : IWantsToRegisterStuff
{
public void Register(Action<Func<object>, Type, string> registerFunction)
{
// NB: We want the most recently registered fs, since there really
// only should be one
var fs = RxApp.DependencyResolver.GetServices<IFilesystemProvider>().LastOrDefault();
if (fs == null)
{
throw new Exception("Failed to initialize Akavache properly. Do you have a reference to Akavache.dll?");
}
var localCache = new Lazy<IBlobCache>(() =>
new SqlitePersistentBlobCache(Path.Combine(fs.GetDefaultLocalMachineCacheDirectory(), "blobs.db"), RxApp.TaskpoolScheduler));
registerFunction(() => localCache.Value, typeof(IBlobCache), "LocalMachine");
var userAccount = new Lazy<IBlobCache>(() =>
new SqlitePersistentBlobCache(Path.Combine(fs.GetDefaultRoamingCacheDirectory(), "blobs.db"), RxApp.TaskpoolScheduler));
registerFunction(() => userAccount.Value, typeof(IBlobCache), "UserAccount");
var secure = new Lazy<ISecureBlobCache>(() =>
new EncryptedBlobCache(Path.Combine(fs.GetDefaultSecretCacheDirectory(), "secret.db"), RxApp.TaskpoolScheduler));
registerFunction(() => secure.Value, typeof(ISecureBlobCache), null);
}
}
}
|
mit
|
C#
|
4d60ea4a45079dd029467b97442c5252951585d4
|
comment formatting
|
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity
|
Assets/MixedRealityToolkit.Tools/ReserializeAssetsUtility/ReserializeAssetsUtility.cs
|
Assets/MixedRealityToolkit.Tools/ReserializeAssetsUtility/ReserializeAssetsUtility.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor
{
/// <summary>
/// Adds menu items to automate reserializing specific files in Unity.
/// </summary>
/// <remarks>
/// Reserialization can be needed between Unity versions or when the
/// underlying script or asset definitions are changed.
/// </remarks>
public class ReserializeUtility
{
[MenuItem("Mixed Reality Toolkit/Utilities/Reserialize/Prefabs, Scenes, and ScriptableObjects")]
private static void ReserializePrefabsAndScenes()
{
var array = GetAssets("t:Prefab t:Scene t:ScriptableObject");
AssetDatabase.ForceReserializeAssets(array);
}
[MenuItem("Mixed Reality Toolkit/Utilities/Reserialize/Materials and Textures")]
private static void ReserializeMaterials()
{
var array = GetAssets("t:Material t:Texture");
AssetDatabase.ForceReserializeAssets(array);
}
[MenuItem("Assets/Mixed Reality Toolkit/Reserialize Selection")]
public static void ReserializeSelection()
{
Object[] selectedAssets = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
// Transform asset object to asset paths.
List<string> assetsPath = new List<string>();
foreach (Object asset in selectedAssets)
{
assetsPath.Add(AssetDatabase.GetAssetPath(asset));
}
string[] array = assetsPath.ToArray();
AssetDatabase.ForceReserializeAssets(array);
Debug.Log($"Reserialized {assetsPath.Count} assets.");
}
private static string[] GetAssets(string filter)
{
string[] allPrefabsGUID = AssetDatabase.FindAssets($"{filter}");
List<string> allPrefabs = new List<string>();
foreach (string guid in allPrefabsGUID)
{
allPrefabs.Add(AssetDatabase.GUIDToAssetPath(guid));
}
return allPrefabs.ToArray();
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor
{
/// <summary>
/// Adds menu items to automate reserializing specific files in Unity.
/// </summary>
/// <remarks>
/// Reserialization can be needed between Unity versions or when the
/// underlying script or asset definitions are changed.
/// </remarks>
public class ReserializeUtility
{
[MenuItem("Mixed Reality Toolkit/Utilities/Reserialize/Prefabs, Scenes, and ScriptableObjects")]
private static void ReserializePrefabsAndScenes()
{
var array = GetAssets("t:Prefab t:Scene t:ScriptableObject");
AssetDatabase.ForceReserializeAssets(array);
}
[MenuItem("Mixed Reality Toolkit/Utilities/Reserialize/Materials and Textures")]
private static void ReserializeMaterials()
{
var array = GetAssets("t:Material t:Texture");
AssetDatabase.ForceReserializeAssets(array);
}
[MenuItem("Assets/Mixed Reality Toolkit/Reserialize Selection")]
public static void ReserializeSelection()
{
Object[] selectedAssets = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
//transform asset object to asset paths
List<string> assetsPath = new List<string>();
foreach (Object asset in selectedAssets)
{
assetsPath.Add(AssetDatabase.GetAssetPath(asset));
}
string[] array = assetsPath.ToArray();
AssetDatabase.ForceReserializeAssets(array);
Debug.Log($"Reserialized {assetsPath.Count} assets.");
}
private static string[] GetAssets(string filter)
{
string[] allPrefabsGUID = AssetDatabase.FindAssets($"{filter}");
List<string> allPrefabs = new List<string>();
foreach (string guid in allPrefabsGUID)
{
allPrefabs.Add(AssetDatabase.GUIDToAssetPath(guid));
}
return allPrefabs.ToArray();
}
}
}
|
mit
|
C#
|
581d79772f0b9da578f329272a99cc1ab39f5fe1
|
Set the right version in the AssemblyInfo
|
shanegrueling/Genkan
|
Genkan/Properties/AssemblyInfo.cs
|
Genkan/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Genkan")]
[assembly: AssemblyDescription("A RPC-Server for OWIN")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Shane Grüling")]
[assembly: AssemblyProduct("Genkan")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ddc500e0-4bb6-40e1-a9a8-670be39b4983")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
|
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("Genkan")]
[assembly: AssemblyDescription("A RPC-Server for OWIN")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Shane Grüling")]
[assembly: AssemblyProduct("Genkan")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ddc500e0-4bb6-40e1-a9a8-670be39b4983")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
1e9064494a732540c42e9a34e6b912b0a80d5565
|
Update IBase.cs
|
KernowCode/UBADDAS
|
KernowCode.KTest.Ubaddas/IBase.cs
|
KernowCode.KTest.Ubaddas/IBase.cs
|
using System;
namespace KernowCode.KTest.Ubaddas
{
/// <summary>
/// BDD initiator
/// </summary>
public interface IBase : IAs
{
/// <summary>
/// <para>Specifies the start of the 'Given' section of BDD</para>
/// <para>This can be followed by 'And' and 'When'</para>
/// <para>Must be preceeded with the 'As' statement</para>
/// <para>Example</para>
/// <para> .Given(customer.Login)</para>
/// </summary>
/// <param name="domainEntityCommand">The entitiy interface command method (without executing parenthesis)</param>
/// <returns>Interface providing fluent methods 'And' and 'When'</returns>
IGiven Given(Action domainEntityCommand);
/// <summary>
/// <para>Specifies the start of the 'Given' section of BDD</para>
/// <para>This can be followed by 'And' and 'When'</para>
/// <para>Must be preceeded with the 'As' statement</para>
/// <para>Example</para>
/// <para> .Given(x => RegisterCustomer(x, customer))</para>
/// </summary>
/// <param name="actionDelegate">A delegate containing a call to a method that will execute another set of behaviours. Specify 'ISet behaviour' as the first parameter of your method and use behaviour to perform another Given,When,Then</param>
/// <returns>Interface providing fluent methods 'And' and 'When'</returns>
IGiven Given(Action<ISet> actionDelegate);
}
}
|
using System;
namespace KernowCode.KTest.Ubaddas
{
/// <summary>
/// BDD initiator
/// </summary>
public interface IBase : IAs
{
/// <summary>
/// <para>Specifies the start of the 'Given' section of BDD</para>
/// <para>This can be followed by 'And' and 'When'</para>
/// <para>Must be preceeded with the 'As' statement</para>
/// <para>Example</para>
/// <para> .Given(customer.Login)</para>
/// </summary>
/// <param name="domainEntityCommand">The entitiy interface command method (without executing parenthesis)</param>
/// <returns>Interface providing fluent methods 'And' and 'When'</returns>
IGiven Given(Action domainEntityCommand);
/// <summary>
/// <para>Specifies the start of the 'Given' section of BDD</para>
/// <para>This can be followed by 'And' and 'When'</para>
/// /// <para>Must be preceeded with the 'As' statement</para>
/// <para>Example</para>
/// <para> .Given(x => RegisterCustomer(x, customer))</para>
/// </summary>
/// <param name="actionDelegate">A delegate containing a call to a method that will execute another set of behaviours. Specify 'ISet behaviour' as the first parameter of your method and use behaviour to perform another Given,When,Then</param>
/// <returns>Interface providing fluent methods 'And' and 'When'</returns>
IGiven Given(Action<ISet> actionDelegate);
}
}
|
mit
|
C#
|
203fc5d7fa2c91d086c86abf1b5e0a8dc537f8f5
|
Update ExplicitNull.cs
|
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
|
main/Smartsheet/Api/Models/ExplicitNull.cs
|
main/Smartsheet/Api/Models/ExplicitNull.cs
|
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Smartsheet.Api.Models
{
public class ExplicitNull : IPrimitiveObjectValue<object>
{
public virtual object Value
{
get { return null; }
set { }
}
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.NULL; }
}
public virtual void Serialize(JsonWriter writer)
{
writer.WriteNull();
}
}
}
|
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed To in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Smartsheet.Api.Models
{
public class ExplicitNull : IPrimitiveObjectValue<object>
{
public virtual object Value
{
get { return null; }
set { }
}
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.NULL; }
}
public virtual void Serialize(JsonWriter writer)
{
writer.WriteNull();
}
}
}
|
apache-2.0
|
C#
|
1068fc3e2b07c58f7b28e595c781d73e3365b91a
|
Fix the missing click on the custom select
|
lehmamic/columbus,lehmamic/columbus
|
Diskordia.Columbus.Bots/FareDeals/SingaporeAirlines/PageObjects/CustomSelectElement.cs
|
Diskordia.Columbus.Bots/FareDeals/SingaporeAirlines/PageObjects/CustomSelectElement.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using Polly;
namespace Diskordia.Columbus.Bots.FareDeals.SingaporeAirlines.PageObjects
{
public class CustomSelectElement
{
private readonly IWebDriver driver;
private readonly string id;
public CustomSelectElement(IWebDriver driver, string id)
{
if(driver == null)
{
throw new ArgumentNullException(nameof(driver));
}
if(id == null)
{
throw new ArgumentNullException(nameof(id));
}
this.id = id;
this.driver = driver;
}
public IEnumerable<string> Options
{
get
{
return this.driver.FindElements(By.CssSelector($"#{this.id} option"))
.Select(e => e.GetAttribute("value"))
.ToArray();
}
}
public void Select(string value)
{
IEnumerable<IWebElement> allCustomSelectElements = this.driver.FindElements(By.ClassName("custom-select"));
IWebElement customSelectElement = allCustomSelectElements.FirstOrDefault(e => IsCustomSelectWithId(e, this.id));
Policy.Handle<WebDriverException>()
.Or<InvalidOperationException>() // can happen when the notifications popup is there
.WaitAndRetry(2, retryAttempt => TimeSpan.FromSeconds(2))
.Execute(() =>
{
this.ClickOption(customSelectElement, value);
});
}
private static bool IsCustomSelectWithId(IWebElement element, string id)
{
return element.FindElements(By.Id(id)).Any();
}
private void ClickOption(IWebElement customSelectElement, string value)
{
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
Actions actions = new Actions(driver);
// e.g. customSelect-19-combobox
string inputOverlayId = customSelectElement.FindElement(By.ClassName("input-overlay")).GetAttribute("id");
// in this case customSelect-19-listbox
string optionElementId = inputOverlayId.Replace("combobox", "listbox");
IJavaScriptExecutor executor = (IJavaScriptExecutor)this.driver;
executor.ExecuteScript("arguments[0].click();", customSelectElement);
this.driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));
var optionElement = this.driver.FindElements(By.CssSelector($"#{optionElementId} li"))
.FirstOrDefault(e => string.Equals(e.GetAttribute("data-value"), value, StringComparison.OrdinalIgnoreCase));
if (optionElement != null)
{
actions.MoveToElement(optionElement);
actions.Perform();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using Polly;
namespace Diskordia.Columbus.Bots.FareDeals.SingaporeAirlines.PageObjects
{
public class CustomSelectElement
{
private readonly IWebDriver driver;
private readonly string id;
public CustomSelectElement(IWebDriver driver, string id)
{
if(driver == null)
{
throw new ArgumentNullException(nameof(driver));
}
if(id == null)
{
throw new ArgumentNullException(nameof(id));
}
this.id = id;
this.driver = driver;
}
public IEnumerable<string> Options
{
get
{
return this.driver.FindElements(By.CssSelector($"#{this.id} option"))
.Select(e => e.GetAttribute("value"))
.ToArray();
}
}
public void Select(string value)
{
IEnumerable<IWebElement> allCustomSelectElements = this.driver.FindElements(By.ClassName("custom-select"));
IWebElement customSelectElement = allCustomSelectElements.FirstOrDefault(e => IsCustomSelectWithId(e, this.id));
Policy.Handle<WebDriverException>()
.Or<InvalidOperationException>() // can happen when the notifications popup is there
.WaitAndRetry(2, retryAttempt => TimeSpan.FromSeconds(2))
.Execute(() =>
{
this.ClickOption(customSelectElement, value);
});
}
private static bool IsCustomSelectWithId(IWebElement element, string id)
{
return element.FindElements(By.Id(id)).Any();
}
private void ClickOption(IWebElement customSelectElement, string value)
{
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
Actions actions = new Actions(driver);
// e.g. customSelect-19-combobox
string inputOverlayId = customSelectElement.FindElement(By.ClassName("input-overlay")).GetAttribute("id");
// in this case customSelect-19-listbox
string optionElementId = inputOverlayId.Replace("combobox", "listbox");
actions.MoveToElement(customSelectElement);
actions.Perform();
var optionElement = this.driver.FindElements(By.CssSelector($"#{optionElementId} li"))
.FirstOrDefault(e => string.Equals(e.GetAttribute("data-value"), value, StringComparison.OrdinalIgnoreCase));
if (optionElement != null)
{
actions.MoveToElement(optionElement);
actions.Perform();
}
}
}
}
|
mit
|
C#
|
9ee016aa4e18e5f41b3a6243875012abf0ea1476
|
Bump version
|
MacDennis76/Rainbow,kamsar/Rainbow,PetersonDave/Rainbow
|
src/SharedAssemblyInfo.cs
|
src/SharedAssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Rainbow")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta03")]
[assembly: CLSCompliant(false)]
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Rainbow")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta02")]
[assembly: CLSCompliant(false)]
|
mit
|
C#
|
bbb12d05d13d2276c0205f4257de5c2813f8fed9
|
Bump to v0.9 - this is going to be the beta for 1.0
|
andrewdavey/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette,damiensawyer/cassette,damiensawyer/cassette,BluewireTechnologies/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,honestegg/cassette,damiensawyer/cassette
|
src/SharedAssemblyInfo.cs
|
src/SharedAssemblyInfo.cs
|
#region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Cassette is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2011")]
[assembly: AssemblyVersion("0.9.0")]
[assembly: AssemblyFileVersion("0.9.0")]
|
#region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Cassette is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © Andrew Davey 2011")]
[assembly: AssemblyVersion("0.8.3")]
[assembly: AssemblyFileVersion("0.8.3")]
|
mit
|
C#
|
dcd4142d93d9cc6c49a52f1cc844c7375cb13a99
|
Update script 10369.
|
F0rTh3H0rd3/LevelingQuestsTNB,TheNoobCompany/LevelingQuestsTNB
|
Profiles/Quester/Scripts/10369.cs
|
Profiles/Quester/Scripts/10369.cs
|
WoWUnit wowUnit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreBlackList);
if(wowUnit.IsValid)
{
nManager.Wow.Helpers.Quest.GetSetIgnoreFight = true;
MovementManager.FindTarget(wowUnit, CombatClass.GetAggroRange);
Thread.Sleep(100);
if(MovementManager.InMovement && wowUnit.Position.DistanceTo(ObjectManager.Me.Position) >= 10f)
{
return false;
}
MountTask.DismountMount();
Thread.Sleep(300);
while(!wowUnit.IsElite)
{
if (ObjectManager.Me.IsDead)
break;
MovementManager.Face(wowUnit);
Thread.Sleep(500);
Interact.InteractWith(wowUnit.GetBaseAddress);
Thread.Sleep(500);
Logging.Write("Use Item");
ItemsManager.UseItem(ItemsManager.GetItemNameById(questObjective.UseItemId));
questObjective.IsObjectiveCompleted = true;
}
nManager.Wow.Helpers.Quest.GetSetIgnoreFight = false;
}
else if (!MovementManager.InMovement && questObjective.Hotspots.Count > 0)
{
// Need GoTo Zone:
if (questObjective.Hotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)].DistanceTo(ObjectManager.Me.Position) > 5)
{
nManager.Wow.Helpers.Quest.TravelToQuestZone(questObjective.Hotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)], ref questObjective.TravelToQuestZone, questObjective.ContinentId,questObjective.ForceTravelToQuestZone);
MovementManager.Go(PathFinder.FindPath(questObjective.Hotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)]));
}
else
{
// Start Move
MovementManager.GoLoop(questObjective.Hotspots);
}
}
|
WoWUnit wowUnit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreBlackList);
if(wowUnit.IsValid)
{
nManager.Wow.Helpers.Quest.GetSetIgnoreFight = true;
MovementManager.FindTarget(wowUnit, CombatClass.GetAggroRange);
Thread.Sleep(100);
if(MovementManager.InMovement && wowUnit.Position.DistanceTo(ObjectManager.Me.Position) >= 10f)
{
return false;
}
MovementManager.StopMove();
Thread.Sleep(300);
while(!wowUnit.IsTrivial)
{
MovementManager.Face(wowUnit);
Thread.Sleep(500);
Interact.InteractWith(wowUnit.GetBaseAddress);
Thread.Sleep(500);
Logging.Write("Use Item");
ItemsManager.UseItem(ItemsManager.GetItemNameById(questObjective.UseItemId));
questObjective.IsObjectiveCompleted = true;
}
nManager.Wow.Helpers.Quest.GetSetIgnoreFight = false;
}
else if (!MovementManager.InMovement && questObjective.Hotspots.Count > 0)
{
// Mounting Mount
MountTask.Mount();
// Need GoTo Zone:
if (questObjective.Hotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)].DistanceTo(ObjectManager.Me.Position) > 5)
{
nManager.Wow.Helpers.Quest.TravelToQuestZone(questObjective.Hotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)], ref questObjective.TravelToQuestZone, questObjective.ContinentId,questObjective.ForceTravelToQuestZone);
MovementManager.Go(PathFinder.FindPath(questObjective.Hotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.Hotspots, ObjectManager.Me.Position)]));
}
else
{
// Start Move
MovementManager.GoLoop(questObjective.Hotspots);
}
}
|
mit
|
C#
|
2d19f37dc6100a605b725e8d1eeb938109c43e06
|
Add missing `new` method in `UserTrackingScrollContainer` for scrolling into view
|
smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,ppy/osu,ppy/osu
|
osu.Game/Graphics/Containers/UserTrackingScrollContainer.cs
|
osu.Game/Graphics/Containers/UserTrackingScrollContainer.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;
namespace osu.Game.Graphics.Containers
{
public class UserTrackingScrollContainer : UserTrackingScrollContainer<Drawable>
{
public UserTrackingScrollContainer()
{
}
public UserTrackingScrollContainer(Direction direction)
: base(direction)
{
}
}
public class UserTrackingScrollContainer<T> : OsuScrollContainer<T>
where T : Drawable
{
/// <summary>
/// Whether the last scroll event was user triggered, directly on the scroll container.
/// </summary>
public bool UserScrolling { get; private set; }
public void CancelUserScroll() => UserScrolling = false;
public UserTrackingScrollContainer()
{
}
public UserTrackingScrollContainer(Direction direction)
: base(direction)
{
}
protected override void OnUserScroll(float value, bool animated = true, double? distanceDecay = default)
{
UserScrolling = true;
base.OnUserScroll(value, animated, distanceDecay);
}
public new void ScrollIntoView(Drawable target, bool animated = true)
{
UserScrolling = false;
base.ScrollIntoView(target, animated);
}
public new void ScrollTo(float value, bool animated = true, double? distanceDecay = null)
{
UserScrolling = false;
base.ScrollTo(value, animated, distanceDecay);
}
public new void ScrollToEnd(bool animated = true, bool allowDuringDrag = false)
{
UserScrolling = false;
base.ScrollToEnd(animated, allowDuringDrag);
}
}
}
|
// 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;
namespace osu.Game.Graphics.Containers
{
public class UserTrackingScrollContainer : UserTrackingScrollContainer<Drawable>
{
public UserTrackingScrollContainer()
{
}
public UserTrackingScrollContainer(Direction direction)
: base(direction)
{
}
}
public class UserTrackingScrollContainer<T> : OsuScrollContainer<T>
where T : Drawable
{
/// <summary>
/// Whether the last scroll event was user triggered, directly on the scroll container.
/// </summary>
public bool UserScrolling { get; private set; }
public void CancelUserScroll() => UserScrolling = false;
public UserTrackingScrollContainer()
{
}
public UserTrackingScrollContainer(Direction direction)
: base(direction)
{
}
protected override void OnUserScroll(float value, bool animated = true, double? distanceDecay = default)
{
UserScrolling = true;
base.OnUserScroll(value, animated, distanceDecay);
}
public new void ScrollTo(float value, bool animated = true, double? distanceDecay = null)
{
UserScrolling = false;
base.ScrollTo(value, animated, distanceDecay);
}
public new void ScrollToEnd(bool animated = true, bool allowDuringDrag = false)
{
UserScrolling = false;
base.ScrollToEnd(animated, allowDuringDrag);
}
}
}
|
mit
|
C#
|
8763ed933e4cca38417b07c22717aa9160a08271
|
remove kinematic from carried boxes
|
jkloo/ScienceTeam
|
Assets/scripts/CarryableController.cs
|
Assets/scripts/CarryableController.cs
|
using UnityEngine;
using System.Collections;
public class CarryableController : MonoBehaviour {
private Animator anim;
private bool carried = false;
private Vector2 startPosition;
private CameraFollow cameraFollow;
void Awake()
{
anim = GetComponent<Animator>();
startPosition = transform.position;
GameObject camera = GameObject.FindGameObjectWithTag("MainCamera");
cameraFollow = camera.GetComponent<CameraFollow>();
}
public void SetCarriedStatus(bool status)
{
carried = status;
anim.SetBool("Carried", status);
collider2D.isTrigger = status;
}
void FixedUpdate()
{
if(!InRange(transform.position.x, cameraFollow.minX, cameraFollow.maxX)
|| !InRange(transform.position.y, cameraFollow.minY - 5, cameraFollow.maxY + 5))
{
transform.position = startPosition;
rigidbody2D.velocity = new Vector2(0.0f, 0.0f);
}
}
bool InRange(float v, float min, float max)
{
return v >= min && v <= max;
}
}
|
using UnityEngine;
using System.Collections;
public class CarryableController : MonoBehaviour {
private Animator anim;
private bool carried = false;
private Vector2 startPosition;
private CameraFollow cameraFollow;
void Awake()
{
anim = GetComponent<Animator>();
startPosition = transform.position;
GameObject camera = GameObject.FindGameObjectWithTag("MainCamera");
cameraFollow = camera.GetComponent<CameraFollow>();
}
public void SetCarriedStatus(bool status)
{
carried = status;
anim.SetBool("Carried", status);
// rigidbody2D.isKinematic = status;
collider2D.isTrigger = status;
}
void FixedUpdate()
{
if(!InRange(transform.position.x, cameraFollow.minX, cameraFollow.maxX)
|| !InRange(transform.position.y, cameraFollow.minY - 5, cameraFollow.maxY + 5))
{
transform.position = startPosition;
rigidbody2D.velocity = new Vector2(0.0f, 0.0f);
}
}
bool InRange(float v, float min, float max)
{
return v >= min && v <= max;
}
}
|
mit
|
C#
|
dc3fa9436172d7264cbca8168fb8cc9e6fb0284a
|
Add Equatable to RelabelingFunction
|
lou1306/CIV,lou1306/CIV
|
CIV.Ccs/Helpers/RelabelingFunction.cs
|
CIV.Ccs/Helpers/RelabelingFunction.cs
|
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace CIV.Ccs
{
public class RelabelingFunction : ICollection<KeyValuePair<string, string>>, IEquatable<RelabelingFunction>
{
readonly IDictionary<string, string> dict = new Dictionary<string, string>();
public int Count => dict.Count;
public bool IsReadOnly => dict.IsReadOnly;
/// <summary>
/// Allows square-bracket indexing, i.e. relabeling[key].
/// </summary>
/// <param name="key">The key to access or set.</param>
public string this[string key] => dict[key];
internal bool ContainsKey(string label) => dict.ContainsKey(label);
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
=> dict.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => dict.GetEnumerator();
public void Add(string action, string relabeled)
{
if (action == Const.tau)
{
throw new ArgumentException("Cannot relabel tau");
}
if (action.IsOutput())
{
action = action.Coaction();
relabeled = relabeled.Coaction();
}
dict.Add(action, relabeled);
}
public void Add(KeyValuePair<string, string> item) => Add(item.Key, item.Value);
public void Clear() => dict.Clear();
public bool Contains(KeyValuePair<string, string> item) => dict.Contains(item);
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
=> dict.CopyTo(array, arrayIndex);
public bool Remove(KeyValuePair<string, string> item) => dict.Remove(item);
public bool Equals(RelabelingFunction other)
{
// https://stackoverflow.com/questions/3804367/
// We can use this solution because dict is a value-type dictionary,
// i.e. <string, string>
return dict.Count == other.dict.Count
&& !dict.Except(other.dict).Any();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace CIV.Ccs
{
public class RelabelingFunction : ICollection<KeyValuePair<string, string>>
{
readonly IDictionary<string, string> dict = new Dictionary<string, string>();
public int Count => dict.Count;
public bool IsReadOnly => dict.IsReadOnly;
/// <summary>
/// Allows square-bracket indexing, i.e. relabeling[key].
/// </summary>
/// <param name="key">The key to access or set.</param>
public string this[string key] => dict[key];
internal bool ContainsKey(string label) => dict.ContainsKey(label);
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
=> dict.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => dict.GetEnumerator();
public void Add(string action, string relabeled)
{
if (action == Const.tau)
{
throw new ArgumentException("Cannot relabel tau");
}
if (action.IsOutput())
{
action = action.Coaction();
relabeled = relabeled.Coaction();
}
dict.Add(action, relabeled);
}
public void Add(KeyValuePair<string, string> item) => Add(item.Key, item.Value);
public void Clear() => dict.Clear();
public bool Contains(KeyValuePair<string, string> item) => dict.Contains(item);
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
=> dict.CopyTo(array, arrayIndex);
public bool Remove(KeyValuePair<string, string> item) => dict.Remove(item);
}
}
|
mit
|
C#
|
b2e99796cef8f589d96684c0872c83c0523e5bb4
|
Add extension method LastName
|
inputfalken/Sharpy
|
Sharpy/src/GeneratorExtensions.cs
|
Sharpy/src/GeneratorExtensions.cs
|
using GeneratorAPI;
using Sharpy.Enums;
using Sharpy.Implementation;
using Sharpy.IProviders;
namespace Sharpy {
/// <summary>
/// </summary>
public static class GeneratorExtensions {
/// <summary>
/// <para>
/// Provider Contains various methods for generating common data types.
/// To get the same result every time you execute the program use the seed overload constructor.
/// </para>
/// </summary>
/// <param name="factory"></param>
/// <param name="provider"></param>
/// <returns></returns>
public static IGenerator<Provider> Provider(this GeneratorFactory factory, Provider provider) {
return Generator.Create(provider);
}
/// <summary>
/// <para>
/// Returns a generator which randomizes First names.
/// </para>
/// <remarks>
/// If INameProvider is not supplied the implementation will get defaulted to <see cref="NameByOrigin"/>
/// </remarks>
/// </summary>
public static IGenerator<string> FirstName(this GeneratorFactory factory, INameProvider provider = null) {
provider = provider ?? new NameByOrigin();
return Generator.Function(provider.FirstName);
}
/// <summary>
/// <para>
/// Returns a generator which randomizes First names based on gender supplied.
/// </para>
/// <remarks>
/// If INameProvider is not supplied the implementation will get defaulted to <see cref="NameByOrigin"/>
/// </remarks>
/// </summary>
public static IGenerator<string> FirstName(this GeneratorFactory factory, Gender gender,
INameProvider provider = null) {
provider = provider ?? new NameByOrigin();
return Generator.Function(() => provider.FirstName(gender));
}
/// <summary>
/// Creates <see cref="IGenerator{T}"/> whose generic argument is <see cref="string"/>.
/// Each invokation of <see cref="IGenerator{T}.Generate"/> will return a <see cref="string"/> representing a last name.
/// <para> </para>
/// <remarks>
/// If an implementation of <see cref="INameProvider"/> is not supplied the implementation will get defaulted to <see cref="NameByOrigin"/>
/// </remarks>
/// </summary>
public static IGenerator<string> LastName(this GeneratorFactory factory, INameProvider lastNameProvider = null) {
lastNameProvider = lastNameProvider ?? new NameByOrigin();
return Generator.Function(lastNameProvider.LastName);
}
}
}
|
using GeneratorAPI;
using Sharpy.Enums;
using Sharpy.Implementation;
using Sharpy.IProviders;
namespace Sharpy {
/// <summary>
/// </summary>
public static class GeneratorExtensions {
/// <summary>
/// <para>
/// Provider Contains various methods for generating common data types.
/// To get the same result every time you execute the program use the seed overload constructor.
/// </para>
/// </summary>
/// <param name="factory"></param>
/// <param name="provider"></param>
/// <returns></returns>
public static IGenerator<Provider> Provider(this GeneratorFactory factory, Provider provider) {
return Generator.Create(provider);
}
/// <summary>
/// <para>
/// Returns a generator which randomizes First names.
/// </para>
/// <remarks>
/// If INameProvider is not supplied the implementation will get defaulted to <see cref="NameByOrigin"/>
/// </remarks>
/// </summary>
public static IGenerator<string> FirstName(this GeneratorFactory factory, INameProvider provider = null) {
provider = provider ?? new NameByOrigin();
return Generator.Function(provider.FirstName);
}
/// <summary>
/// <para>
/// Returns a generator which randomizes First names based on gender supplied.
/// </para>
/// <remarks>
/// If INameProvider is not supplied the implementation will get defaulted to <see cref="NameByOrigin"/>
/// </remarks>
/// </summary>
public static IGenerator<string> FirstName(this GeneratorFactory factory, Gender gender,
INameProvider provider = null) {
provider = provider ?? new NameByOrigin();
return Generator.Function(() => provider.FirstName(gender));
}
}
}
|
mit
|
C#
|
35814e024e04b67027dae58dc4e76c1bbe61a370
|
Revert AssemblyVersion to 1.0.0.0
|
jterry75/Docker.DotNet,ahmetalpbalkan/Docker.DotNet,jterry75/Docker.DotNet
|
Docker.DotNet/Properties/AssemblyInfo.cs
|
Docker.DotNet/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Docker.DotNet")]
[assembly: InternalsVisibleTo("Docker.DotNet.UnitTests")]
[assembly: InternalsVisibleTo("Docker.DotNet.IntegrationTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Docker.DotNet")]
[assembly: AssemblyCopyright("Copyright © 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.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Docker.DotNet")]
[assembly: InternalsVisibleTo("Docker.DotNet.UnitTests")]
[assembly: InternalsVisibleTo("Docker.DotNet.IntegrationTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Docker.DotNet")]
[assembly: AssemblyCopyright("Copyright © 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.16.0.0")]
[assembly: AssemblyFileVersion("1.16.0.0")]
|
apache-2.0
|
C#
|
9652d5350d44e02468e27a1124d8ab096e721413
|
Improve comment
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Wabisabi/IssuanceRequest.cs
|
WalletWasabi/Wabisabi/IssuanceRequest.cs
|
using System.Collections.Generic;
using WalletWasabi.Crypto.Groups;
namespace WalletWasabi.Wabisabi
{
/// <summary>
/// Represents a request for issuance a new credential.
/// </summary>
public class IssuanceRequest
{
internal IssuanceRequest(GroupElement ma, IEnumerable<GroupElement> bitCommitments)
{
Ma = ma;
BitCommitments = bitCommitments;
}
/// <summary>
/// Pedersen commitment to the credential amount.
/// </summary>
public GroupElement Ma { get; }
/// <summary>
/// Commitments to the amount's individual bits.
/// </summary>
public IEnumerable<GroupElement> BitCommitments { get; }
}
}
|
using System.Collections.Generic;
using WalletWasabi.Crypto.Groups;
namespace WalletWasabi.Wabisabi
{
/// <summary>
/// Represents a request for issuance a new credential.
/// </summary>
public class IssuanceRequest
{
internal IssuanceRequest(GroupElement ma, IEnumerable<GroupElement> bitCommitments)
{
Ma = ma;
BitCommitments = bitCommitments;
}
/// <summary>
/// Pedersen commitment to the credential amount.
/// </summary>
public GroupElement Ma { get; }
/// <summary>
/// Commitments the the value's bits decomposed amount.
/// </summary>
public IEnumerable<GroupElement> BitCommitments { get; }
}
}
|
mit
|
C#
|
1a3c76caa8f1582c9a4f5b9efdba93feb20b7c80
|
Remove bucket name
|
visualeyes/cabinet,visualeyes/cabinet,visualeyes/cabinet
|
src/Cabinet.Web.SelfHostTest/App_Start/Startup.IOC.cs
|
src/Cabinet.Web.SelfHostTest/App_Start/Startup.IOC.cs
|
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Autofac;
using Autofac.Integration.WebApi;
using Cabinet.Core;
using Cabinet.FileSystem;
using Cabinet.S3;
using Cabinet.Web.SelfHostTest.Framework;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.StaticFiles;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace Cabinet.Web.SelfHostTest {
public partial class Startup {
private const string BucketName = "test-bucket";
public ContainerBuilder ConfigureAutoFac(FileCabinetFactory cabinetFactory) {
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterInstance<IPathMapper>(new PathMapper(AppDomain.CurrentDomain.SetupInformation.ApplicationBase));
builder.RegisterType<UploadKeyProvider>().As<IKeyProvider>();
builder.RegisterInstance<IFileCabinetFactory>(cabinetFactory);
//builder.Register((c) => {
// var mapper = c.Resolve<IPathMapper>();
// string uploadDir = mapper.MapPath("~/App_Data/Uploads");
// var fileConfig = new FileSystemCabinetConfig(uploadDir, true);
// return cabinetFactory.GetCabinet(fileConfig);
//});
builder.Register((c) => {
var s3Config = new AmazonS3CabinetConfig(BucketName, RegionEndpoint.APSoutheast2, new StoredProfileAWSCredentials());
return cabinetFactory.GetCabinet(s3Config);
});
return builder;
}
}
}
|
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Autofac;
using Autofac.Integration.WebApi;
using Cabinet.Core;
using Cabinet.FileSystem;
using Cabinet.S3;
using Cabinet.Web.SelfHostTest.Framework;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.StaticFiles;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace Cabinet.Web.SelfHostTest {
public partial class Startup {
private const string BucketName = "careerhub-info";
public ContainerBuilder ConfigureAutoFac(FileCabinetFactory cabinetFactory) {
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterInstance<IPathMapper>(new PathMapper(AppDomain.CurrentDomain.SetupInformation.ApplicationBase));
builder.RegisterType<UploadKeyProvider>().As<IKeyProvider>();
builder.RegisterInstance<IFileCabinetFactory>(cabinetFactory);
//builder.Register((c) => {
// var mapper = c.Resolve<IPathMapper>();
// string uploadDir = mapper.MapPath("~/App_Data/Uploads");
// var fileConfig = new FileSystemCabinetConfig(uploadDir, true);
// return cabinetFactory.GetCabinet(fileConfig);
//});
builder.Register((c) => {
var s3Config = new AmazonS3CabinetConfig(BucketName, RegionEndpoint.APSoutheast2, new StoredProfileAWSCredentials());
return cabinetFactory.GetCabinet(s3Config);
});
return builder;
}
}
}
|
mit
|
C#
|
b87478f6e2c3f245c34a5c11e714a74d4c90e9e9
|
replace 'as' with direct cast to avoid possible nullref
|
NeoAdonis/osu,2yangk23/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,ppy/osu,UselessToucan/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,UselessToucan/osu,2yangk23/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu
|
osu.Game.Rulesets.Catch/Mods/CatchModRelax.cs
|
osu.Game.Rulesets.Catch/Mods/CatchModRelax.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.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
using System;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModRelax : ModRelax, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Description => @"Use the mouse to control the catcher.";
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset) =>
((Container)drawableRuleset.Playfield.Parent).Add(new CatchModRelaxHelper(drawableRuleset.Playfield as CatchPlayfield));
private class CatchModRelaxHelper : Drawable, IKeyBindingHandler<CatchAction>, IRequireHighFrequencyMousePosition
{
private readonly CatcherArea.Catcher catcher;
public CatchModRelaxHelper(CatchPlayfield catchPlayfield)
{
catcher = catchPlayfield.CatcherArea.MovableCatcher;
RelativeSizeAxes = Axes.Both;
}
//disable keyboard controls
public bool OnPressed(CatchAction action) => true;
public bool OnReleased(CatchAction action) => true;
protected override bool OnMouseMove(MouseMoveEvent e)
{
//lock catcher to mouse position horizontally
catcher.X = e.MousePosition.X / DrawSize.X;
//make Yuzu face the direction he's moving
var direction = Math.Sign(e.Delta.X);
if (direction != 0)
catcher.Scale = new Vector2(Math.Abs(catcher.Scale.X) * direction, catcher.Scale.Y);
return base.OnMouseMove(e);
}
}
}
}
|
// 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.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
using System;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModRelax : ModRelax, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Description => @"Use the mouse to control the catcher.";
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset) =>
(drawableRuleset.Playfield.Parent as Container).Add(new CatchModRelaxHelper(drawableRuleset.Playfield as CatchPlayfield));
private class CatchModRelaxHelper : Drawable, IKeyBindingHandler<CatchAction>, IRequireHighFrequencyMousePosition
{
private readonly CatcherArea.Catcher catcher;
public CatchModRelaxHelper(CatchPlayfield catchPlayfield)
{
catcher = catchPlayfield.CatcherArea.MovableCatcher;
RelativeSizeAxes = Axes.Both;
}
//disable keyboard controls
public bool OnPressed(CatchAction action) => true;
public bool OnReleased(CatchAction action) => true;
protected override bool OnMouseMove(MouseMoveEvent e)
{
//lock catcher to mouse position horizontally
catcher.X = e.MousePosition.X / DrawSize.X;
//make Yuzu face the direction he's moving
var direction = Math.Sign(e.Delta.X);
if (direction != 0)
catcher.Scale = new Vector2(Math.Abs(catcher.Scale.X) * direction, catcher.Scale.Y);
return base.OnMouseMove(e);
}
}
}
}
|
mit
|
C#
|
a5dcd8db86e45357872c73921e02f015897c969b
|
Fix cat pending tasks
|
elastic/elasticsearch-net,elastic/elasticsearch-net
|
src/Nest/Cat/CatPendingTasks/CatPendingTasksRecord.cs
|
src/Nest/Cat/CatPendingTasks/CatPendingTasksRecord.cs
|
using System.Runtime.Serialization;
using Utf8Json;
namespace Nest
{
[DataContract]
public class CatPendingTasksRecord : ICatRecord
{
[DataMember(Name ="insertOrder")]
[JsonFormatter(typeof(NullableStringIntFormatter))]
public int? InsertOrder { get; set; }
[DataMember(Name ="priority")]
public string Priority { get; set; }
[DataMember(Name ="source")]
public string Source { get; set; }
[DataMember(Name ="timeInQueue")]
public string TimeInQueue { get; set; }
}
}
|
using System.Runtime.Serialization;
namespace Nest
{
[DataContract]
public class CatPendingTasksRecord : ICatRecord
{
[DataMember(Name ="insertOrder")]
public int? InsertOrder { get; set; }
[DataMember(Name ="priority")]
public string Priority { get; set; }
[DataMember(Name ="source")]
public string Source { get; set; }
[DataMember(Name ="timeInQueue")]
public string TimeInQueue { get; set; }
}
}
|
apache-2.0
|
C#
|
2d6107592d09546b31f0abdb49c231ec99e9312f
|
fix typo
|
Pathoschild/StardewMods
|
LookupAnything/Framework/ModConfig.cs
|
LookupAnything/Framework/ModConfig.cs
|
namespace Pathoschild.Stardew.LookupAnything.Framework
{
/// <summary>The parsed mod configuration.</summary>
internal class ModConfig
{
/*********
** Accessors
*********/
/// <summary>Whether to close the lookup UI when the lookup key is release.</summary>
public bool HideOnKeyUp { get; set; }
/// <summary>The number of pixels to shift content on each up/down scroll.</summary>
public int ScrollAmount { get; set; } = 160;
/// <summary>Whether to hide content until the player has discovered it in-game (where applicable).</summary>
public bool ProgressionMode { get; set; } = false;
/// <summary>Whether to highlight item gift tastes which haven't been revealed in the NPC profile.</summary>
public bool HighlightUnrevealedGiftTastes { get; set; } = false;
/// <summary>Whether to show advanced data mining fields.</summary>
public bool ShowDataMiningFields { get; set; }
/// <summary>Whether to include map tiles as lookup targets.</summary>
public bool EnableTileLookups { get; set; }
/// <summary>The key bindings.</summary>
public ModConfigRawKeys Controls { get; set; } = new ModConfigRawKeys();
}
}
|
namespace Pathoschild.Stardew.LookupAnything.Framework
{
/// <summary>The parsed mod configuration.</summary>
internal class ModConfig
{
/*********
** Accessors
*********/
/// <summary>Whether to close the lookup UI when the lookup key is release.</summary>
public bool HideOnKeyUp { get; set; }
/// <summary>The number of pixels to shift content on each up/down scroll.</summary>
public int ScrollAmount { get; set; } = 160;
/// <summary>Whether to hide content until the player has discovered it in-game (where applicable).</summary>
public bool ProgressionMode { get; set; } = false;
/// <summary>>Whether to highlight item gift tastes which haven't been revealed in the NPC profile.</summary>
public bool HighlightUnrevealedGiftTastes { get; set; } = false;
/// <summary>Whether to show advanced data mining fields.</summary>
public bool ShowDataMiningFields { get; set; }
/// <summary>Whether to include map tiles as lookup targets.</summary>
public bool EnableTileLookups { get; set; }
/// <summary>The key bindings.</summary>
public ModConfigRawKeys Controls { get; set; } = new ModConfigRawKeys();
}
}
|
mit
|
C#
|
7a3efddf4e60882cd471ee4cde3ab3a837b8ebfc
|
Remove un-needed temp variable
|
KevinRansom/roslyn,gafter/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,jmarolf/roslyn,AmadeusW/roslyn,mavasani/roslyn,eriawan/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,genlu/roslyn,tannergooding/roslyn,aelij/roslyn,mavasani/roslyn,dotnet/roslyn,tannergooding/roslyn,aelij/roslyn,mgoertz-msft/roslyn,tmat/roslyn,gafter/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,weltkante/roslyn,KevinRansom/roslyn,stephentoub/roslyn,gafter/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,wvdd007/roslyn,genlu/roslyn,weltkante/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,aelij/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,brettfo/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,physhi/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,brettfo/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,tmat/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,stephentoub/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,diryboy/roslyn,AlekseyTs/roslyn,brettfo/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,genlu/roslyn,KirillOsenkov/roslyn,physhi/roslyn,jmarolf/roslyn,sharwell/roslyn,bartdesmet/roslyn,eriawan/roslyn,bartdesmet/roslyn,tmat/roslyn,jasonmalinowski/roslyn
|
src/Features/Core/Portable/MakeClassAbstract/AbstractMakeClassAbstractCodeFixProvider.cs
|
src/Features/Core/Portable/MakeClassAbstract/AbstractMakeClassAbstractCodeFixProvider.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.
#nullable enable
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeClassAbstract
{
internal abstract class AbstractMakeClassAbstractCodeFixProvider<TClassDeclarationSyntax> : SyntaxEditorBasedCodeFixProvider
where TClassDeclarationSyntax : SyntaxNode
{
protected abstract bool IsValidRefactoringContext(SyntaxNode? node, out TClassDeclarationSyntax? classDeclaration);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
if (context.Diagnostics.Length == 1 &&
IsValidRefactoringContext(context.Diagnostics[0].Location?.FindNode(context.CancellationToken), out _))
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
}
return Task.CompletedTask;
}
protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
for (var i = 0; i < diagnostics.Length; i++)
{
if (IsValidRefactoringContext(diagnostics[i].Location?.FindNode(cancellationToken), out var classDeclaration))
{
editor.ReplaceNode(classDeclaration,
(currentClassDeclaration, generator) => generator.WithModifiers(currentClassDeclaration, DeclarationModifiers.Abstract));
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Make_class_abstract, createChangedDocument, FeaturesResources.Make_class_abstract)
{
}
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeClassAbstract
{
internal abstract class AbstractMakeClassAbstractCodeFixProvider<TClassDeclarationSyntax> : SyntaxEditorBasedCodeFixProvider
where TClassDeclarationSyntax : SyntaxNode
{
protected abstract bool IsValidRefactoringContext(SyntaxNode? node, out TClassDeclarationSyntax? classDeclaration);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
if (context.Diagnostics.Length == 1 &&
IsValidRefactoringContext(context.Diagnostics[0].Location?.FindNode(context.CancellationToken), out _))
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
}
return Task.CompletedTask;
}
protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
for (var i = 0; i < diagnostics.Length; i++)
{
var memberDeclaration = diagnostics[i].Location?.FindNode(cancellationToken);
if (IsValidRefactoringContext(memberDeclaration, out var classDeclaration))
{
editor.ReplaceNode(classDeclaration,
(currentClassDeclaration, generator) => generator.WithModifiers(currentClassDeclaration, DeclarationModifiers.Abstract));
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Make_class_abstract, createChangedDocument, FeaturesResources.Make_class_abstract)
{
}
}
}
}
|
mit
|
C#
|
ec7ecde3d5688f45ca9fd2a09b2b560d2a30e2bf
|
Update RemoteNLogViewerOptionsPartialConfigurationValidator.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Analytics/Logging/NLog/RemoteNLogViewerOptionsPartialConfigurationValidator.cs
|
TIKSN.Core/Analytics/Logging/NLog/RemoteNLogViewerOptionsPartialConfigurationValidator.cs
|
using FluentValidation;
using TIKSN.Configuration.Validator;
namespace TIKSN.Analytics.Logging.NLog
{
public class
RemoteNLogViewerOptionsPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<
RemoteNLogViewerOptions>
{
public RemoteNLogViewerOptionsPartialConfigurationValidator() =>
this.RuleFor(instance => instance.Url.Scheme)
.Must(IsProperScheme)
.When(instance => instance.Url != null);
private static bool IsProperScheme(string scheme)
{
return scheme.ToLowerInvariant() switch
{
"tcp" or "tcp4" or "tcp6" or "udp" or "udp4" or "udp6" or "http" or "https" => true,
_ => false,
};
}
}
}
|
using FluentValidation;
using TIKSN.Configuration.Validator;
namespace TIKSN.Analytics.Logging.NLog
{
public class
RemoteNLogViewerOptionsPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<
RemoteNLogViewerOptions>
{
public RemoteNLogViewerOptionsPartialConfigurationValidator() =>
this.RuleFor(instance => instance.Url.Scheme)
.Must(IsProperScheme)
.When(instance => instance.Url != null);
private static bool IsProperScheme(string scheme)
{
switch (scheme.ToLowerInvariant())
{
case "tcp":
case "tcp4":
case "tcp6":
case "udp":
case "udp4":
case "udp6":
case "http":
case "https":
return true;
default:
return false;
}
}
}
}
|
mit
|
C#
|
d5bf9a800de97fe01c59319d2f048641ad9c120b
|
Revert "Remove unimplemented tests"
|
slvnperron/NUnit-retry
|
src/NUnit-retry.Tests/FixtureTests.cs
|
src/NUnit-retry.Tests/FixtureTests.cs
|
// /////////////////////////////////////////////////////////////////////
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// /////////////////////////////////////////////////////////////////////
namespace NUnit_retry.Tests
{
using NUnit.Framework;
[TestFixture]
[Retry]
public class FixtureTests
{
[Test]
public void ShouldSucceed_One_Time_Out_Of_3()
{
InterTestContext.IncrementMethodTries("class_1_on_3");
if (InterTestContext.InterTestCounts["class_1_on_3"] == 1)
{
Assert.Fail();
}
Assert.Pass();
}
[TestCase(TestName = "TestCaseName")]
public void ShouldSucceed_One_Time_Out_Of_3_TestCase()
{
InterTestContext.IncrementMethodTries("class_1_on_3_TestCase");
if (InterTestContext.InterTestCounts["class_1_on_3_TestCase"] == 1)
{
Assert.Fail();
}
Assert.Pass();
}
public TestCaseData[] CaseSource
{
get { return new TestCaseData[] { new TestCaseData().SetName("TestCaseSourceName"), }; }
}
[TestCaseSource("CaseSource")]
public void ShouldSucceed_One_Time_Out_Of_3_TestCaseSource()
{
InterTestContext.IncrementMethodTries("class_1_on_3_TestCaseSource");
if (InterTestContext.InterTestCounts["class_1_on_3_TestCaseSource"] == 1)
{
Assert.Fail();
}
Assert.Pass();
}
}
public class InheritedAttribute : FixtureTests
{
[Test]
public void Inherited_ShouldSucceed_One_Time_Out_Of_3()
{
InterTestContext.IncrementMethodTries("inherited_1_on_3");
if (InterTestContext.InterTestCounts["inherited_1_on_3"] == 1)
{
Assert.Fail();
}
Assert.Pass();
}
}
}
|
// /////////////////////////////////////////////////////////////////////
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// /////////////////////////////////////////////////////////////////////
namespace NUnit_retry.Tests
{
using NUnit.Framework;
[TestFixture]
[Retry]
public class FixtureTests
{
[Test]
public void ShouldSucceed_One_Time_Out_Of_3()
{
InterTestContext.IncrementMethodTries("class_1_on_3");
if (InterTestContext.InterTestCounts["class_1_on_3"] == 1)
{
Assert.Fail();
}
Assert.Pass();
}
}
public class InheritedAttribute : FixtureTests
{
[Test]
public void Inherited_ShouldSucceed_One_Time_Out_Of_3()
{
InterTestContext.IncrementMethodTries("inherited_1_on_3");
if (InterTestContext.InterTestCounts["inherited_1_on_3"] == 1)
{
Assert.Fail();
}
Assert.Pass();
}
}
}
|
mit
|
C#
|
281ea971908bb2c608f368efacc9303aab40295e
|
Update anchor within help link (follow-up to r3671). Closes #3647.
|
rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac
|
templates/anydiff.cs
|
templates/anydiff.cs
|
<?cs include "header.cs"?>
<div id="ctxtnav" class="nav"></div>
<div id="content" class="changeset">
<div id="title">
<h1>Select Base and Target for Diff:</h1>
</div>
<div id="anydiff">
<form action="<?cs var:anydiff.changeset_href ?>" method="get">
<table>
<tr>
<th><label for="old_path">From:</label></th>
<td>
<input type="text" id="old_path" name="old_path" value="<?cs
var:anydiff.old_path ?>" size="44" />
<label for="old_rev">at Revision:</label>
<input type="text" id="old_rev" name="old" value="<?cs
var:anydiff.old_rev ?>" size="4" />
</td>
</tr>
<tr>
<th><label for="new_path">To:</label></th>
<td>
<input type="text" id="new_path" name="new_path" value="<?cs
var:anydiff.new_path ?>" size="44" />
<label for="new_rev">at Revision:</label>
<input type="text" id="new_rev" name="new" value="<?cs
var:anydiff.new_rev ?>" size="4" />
</td>
</tr>
</table>
<div class="buttons">
<input type="submit" value="View changes" />
</div>
</form>
</div>
<div id="help">
<strong>Note:</strong> See <a href="<?cs var:trac.href.wiki
?>/TracChangeset#ExaminingDifferencesBetweenBranches">TracChangeset</a> for help on using the arbitrary diff feature.
</div>
</div>
<?cs include "footer.cs"?>
|
<?cs include "header.cs"?>
<div id="ctxtnav" class="nav"></div>
<div id="content" class="changeset">
<div id="title">
<h1>Select Base and Target for Diff:</h1>
</div>
<div id="anydiff">
<form action="<?cs var:anydiff.changeset_href ?>" method="get">
<table>
<tr>
<th><label for="old_path">From:</label></th>
<td>
<input type="text" id="old_path" name="old_path" value="<?cs
var:anydiff.old_path ?>" size="44" />
<label for="old_rev">at Revision:</label>
<input type="text" id="old_rev" name="old" value="<?cs
var:anydiff.old_rev ?>" size="4" />
</td>
</tr>
<tr>
<th><label for="new_path">To:</label></th>
<td>
<input type="text" id="new_path" name="new_path" value="<?cs
var:anydiff.new_path ?>" size="44" />
<label for="new_rev">at Revision:</label>
<input type="text" id="new_rev" name="new" value="<?cs
var:anydiff.new_rev ?>" size="4" />
</td>
</tr>
</table>
<div class="buttons">
<input type="submit" value="View changes" />
</div>
</form>
</div>
<div id="help">
<strong>Note:</strong> See <a href="<?cs var:trac.href.wiki
?>/TracChangeset#ExaminingArbitraryDifferences">TracChangeset</a> for help on using the arbitrary diff feature.
</div>
</div>
<?cs include "footer.cs"?>
|
bsd-3-clause
|
C#
|
d198d89004f2c6c5274492e18dbbcaef70266009
|
test fix
|
coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk
|
data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook3.cs
|
data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook3.cs
|
using CoinAPI.WebSocket.V1.DataModels;
using Microsoft.Extensions.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
namespace CoinAPI.WebSocket.V1.Tests
{
[TestClass]
public class TestOrderBook3
{
[TestMethod]
public void TestOrderBook3Receive()
{
var config = new ConfigurationBuilder().AddJsonFile("config.json").Build();
int mssgCount = 0;
var helloMsg = new Hello()
{
apikey = System.Guid.Parse(config["TestApiKey"]),
subscribe_data_type = new string[] { "book_l3" },
subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD", "COINBASE_SPOT_BTC_USD" }
};
using (var wsClient = new CoinApiWsClient(isSandbox: false))
{
var mre = new ManualResetEvent(false);
wsClient.OrderBookL3Event += (s, i) =>
{
mre.Set();
mssgCount++;
};
wsClient.SendHelloMessage(helloMsg);
mre.WaitOne(TimeSpan.FromSeconds(10));
Assert.AreNotEqual(0, mssgCount);
}
}
}
}
|
using CoinAPI.WebSocket.V1.DataModels;
using Microsoft.Extensions.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
namespace CoinAPI.WebSocket.V1.Tests
{
[TestClass]
public class TestOrderBook3
{
[TestMethod]
public void TestOrderBook3Receive()
{
var config = new ConfigurationBuilder().AddJsonFile("config.json").Build();
int mssgCount = 0;
var helloMsg = new Hello()
{
apikey = System.Guid.Parse(config["TestApiKey"]),
subscribe_data_type = new string[] { "book_l3" },
subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD COINBASE_SPOT_BTC_USD" }
};
using (var wsClient = new CoinApiWsClient(isSandbox: true))
{
var mre = new ManualResetEvent(false);
wsClient.OrderBookL3Event += (s, i) =>
{
mre.Set();
mssgCount++;
};
wsClient.SendHelloMessage(helloMsg);
mre.WaitOne(TimeSpan.FromSeconds(10));
Assert.AreNotEqual(0, mssgCount);
}
}
}
}
|
mit
|
C#
|
ac2e14def650f79412d3d3c5a73a0ce71dab9956
|
update assmebly info
|
bcatcho/transition,bcatcho/transition
|
Transition/Properties/AssemblyInfo.cs
|
Transition/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Transition")]
[assembly: AssemblyDescription ("A state machine language and interpreter")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Brandon Catcho")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("0.2.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Transition")]
[assembly: AssemblyDescription ("A state machine language and interpreter")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Brandon Catcho")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("0.1.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
mit
|
C#
|
78dea0156a9bcb6458e98fbf4719d18f27cffa69
|
Use TextWriter overload for template filling. Change was requested by pull request reviewer.
|
rexm/Handlebars.Net,rexm/Handlebars.Net
|
source/Handlebars.Benchmark/LargeArray.cs
|
source/Handlebars.Benchmark/LargeArray.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Attributes;
using HandlebarsDotNet;
namespace HandlebarsNet.Benchmark
{
public class LargeArray
{
private object _data;
private HandlebarsTemplate<TextWriter, object, object> _default;
[Params(20000, 40000, 80000)]
public int N { get; set; }
[GlobalSetup]
public void Setup()
{
const string template = @"{{#each this}}{{this}}{{/each}}";
var handlebars = Handlebars.Create();
using (var reader = new StringReader(template))
{
_default = handlebars.Compile(reader);
}
_data = Enumerable.Range(0, N).ToList();
}
[Benchmark]
public void Default() => _default(TextWriter.Null, _data);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BenchmarkDotNet.Attributes;
using HandlebarsDotNet;
namespace HandlebarsNet.Benchmark
{
public class LargeArray
{
private object _data;
private HandlebarsTemplate<object, object> _default;
[Params(20000, 40000, 80000)]
public int N { get; set; }
[GlobalSetup]
public void Setup()
{
const string template = @"{{#each this}}{{this}}{{/each}}";
_default = Handlebars.Compile(template);
_data = Enumerable.Range(0, N).ToList();
}
[Benchmark]
public void Default() => _default(_data);
}
}
|
mit
|
C#
|
cde0db515fc86cbfeac74865eebd3376a09136cf
|
Use Stopwatch's .Restart() instead of .Reset() & .Start() (fixes #30)
|
akamsteeg/SwissArmyKnife
|
src/SwissArmyKnife/StopwatchExtensions.cs
|
src/SwissArmyKnife/StopwatchExtensions.cs
|
using System;
using System.Diagnostics;
namespace SwissArmyKnife
{
/// <summary>
/// Extension methods for <see cref="Stopwatch"/>
/// </summary>
public static class StopwatchExtensions
{
/// <summary>
/// Get the current value of the <see cref="Stopwatch"/>
/// and restart the timer
/// </summary>
/// <param name="sw"></param>
/// <returns></returns>
public static TimeSpan GetElapsedAndRestart(this Stopwatch sw)
{
sw.Stop();
var result = sw.Elapsed;
sw.Restart();
return result;
}
}
}
|
using System;
using System.Diagnostics;
namespace SwissArmyKnife
{
/// <summary>
/// Extension methods for <see cref="Stopwatch"/>
/// </summary>
public static class StopwatchExtensions
{
/// <summary>
/// Get the current value of the <see cref="Stopwatch"/>
/// and restart the timer
/// </summary>
/// <param name="sw"></param>
/// <returns></returns>
public static TimeSpan GetElapsedAndRestart(this Stopwatch sw)
{
sw.Stop();
var result = sw.Elapsed;
sw.Reset();
sw.Start();
return result;
}
}
}
|
mit
|
C#
|
b47d04c049328aa07745db6449d9d29b9b165458
|
Add error to see if CI is blocking Deployment
|
monkey3310/appveyor-shields-badges
|
AppveyorShieldBadges/Program.cs
|
AppveyorShieldBadges/Program.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace AppveyorShieldBadges
{
public class Program
{
public static void Main(string[] args)
{
var host = ;new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace AppveyorShieldBadges
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
|
mit
|
C#
|
0b4e32d797d4d7f197702f9a21ed1a2d688fe418
|
fix bug (null terminate does not work)
|
oggy83/BlendReader
|
BlendReader/Util/ConvertUtil.cs
|
BlendReader/Util/ConvertUtil.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Blender
{
public static class ConvertUtil
{
public static String CharArray2String(object obj)
{
var sb = new StringBuilder();
object[] array = (object[])obj;
foreach (object o in array)
{
char? c = (char?)o;
if (c == '\0')
{
break;
}
sb.Append(c);
}
return sb.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Blender
{
public static class ConvertUtil
{
public static String CharArray2String(object obj)
{
var sb = new StringBuilder();
object[] array = (object[])obj;
foreach (object o in array)
{
char? c = (char?)o;
if (c != '\0')
{
sb.Append(c);
}
}
return sb.ToString();
}
}
}
|
mit
|
C#
|
8ea8330e7f5f6b6181a879382455006738acea9c
|
Use UITest compiler directive instead of ENABLE_TEST_CLOUD
|
jamesmontemagno/Coffee-Filter,hoanganhx86/Coffee-Filter
|
CoffeeFilter.iOS/AppDelegate.cs
|
CoffeeFilter.iOS/AppDelegate.cs
|
using UIKit;
using Foundation;
namespace CoffeeFilter.iOS
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
const string GoogleMapsAPIKey = "AIzaSyAAOpU0qjK0LBTe2UCCxPQP1iTaSv_Xihw";
public override UIWindow Window { get; set; }
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
#if DEBUG
// Xamarin.Insights.Initialize("ef02f98fd6fb47ce8624862ab7625b933b6fb21d");
#else
Xamarin.Insights.Initialize ("8da86f8b3300aa58f3dc9bbef455d0427bb29086");
#endif
// Register Google maps key to use street view
Google.Maps.MapServices.ProvideAPIKey(GoogleMapsAPIKey);
// Code to start the Xamarin Test Cloud Agent
#if UITest
Xamarin.Calabash.Start();
#endif
return true;
}
}
}
|
using UIKit;
using Foundation;
namespace CoffeeFilter.iOS
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
const string GoogleMapsAPIKey = "AIzaSyAAOpU0qjK0LBTe2UCCxPQP1iTaSv_Xihw";
public override UIWindow Window { get; set; }
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
#if DEBUG
// Xamarin.Insights.Initialize("ef02f98fd6fb47ce8624862ab7625b933b6fb21d");
#else
Xamarin.Insights.Initialize ("8da86f8b3300aa58f3dc9bbef455d0427bb29086");
#endif
// Register Google maps key to use street view
Google.Maps.MapServices.ProvideAPIKey(GoogleMapsAPIKey);
// Code to start the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
Xamarin.Calabash.Start();
#endif
return true;
}
}
}
|
mit
|
C#
|
1fb9359d9072cf6ed857e68be948271ae22ca2f5
|
Fix HeldPrefix having different name on client.
|
space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14
|
Content.Client/GameObjects/Components/Items/ItemComponent.cs
|
Content.Client/GameObjects/Components/Items/ItemComponent.cs
|
using Content.Shared.GameObjects;
using Content.Shared.GameObjects.Components.Items;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.ResourceManagement;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Components.Renderable;
using Robust.Shared.IoC;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Client.GameObjects
{
[RegisterComponent]
public class ItemComponent : Component
{
public override string Name => "Item";
public override uint? NetID => ContentNetIDs.ITEM;
[ViewVariables] protected ResourcePath RsiPath;
private string _equippedPrefix;
[ViewVariables(VVAccess.ReadWrite)]
public string EquippedPrefix
{
get => _equippedPrefix;
set => _equippedPrefix = value;
}
public (RSI rsi, RSI.StateId stateId)? GetInHandStateInfo(string hand)
{
if (RsiPath == null)
{
return null;
}
var rsi = GetRSI();
var stateId = EquippedPrefix != null ? $"{EquippedPrefix}-inhand-{hand}" : $"inhand-{hand}";
if (rsi.TryGetState(stateId, out _))
{
return (rsi, stateId);
}
return null;
}
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataFieldCached(ref RsiPath, "sprite", null);
serializer.DataFieldCached(ref _equippedPrefix, "HeldPrefix", null);
}
protected RSI GetRSI()
{
var resourceCache = IoCManager.Resolve<IResourceCache>();
return resourceCache.GetResource<RSIResource>(SharedSpriteComponent.TextureRoot / RsiPath).RSI;
}
public override void HandleComponentState(ComponentState curState, ComponentState nextState)
{
if(curState == null)
return;
var itemComponentState = (ItemComponentState)curState;
EquippedPrefix = itemComponentState.EquippedPrefix;
}
}
}
|
using Content.Shared.GameObjects;
using Content.Shared.GameObjects.Components.Items;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.ResourceManagement;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Components.Renderable;
using Robust.Shared.IoC;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Client.GameObjects
{
[RegisterComponent]
public class ItemComponent : Component
{
public override string Name => "Item";
public override uint? NetID => ContentNetIDs.ITEM;
[ViewVariables] protected ResourcePath RsiPath;
private string _equippedPrefix;
[ViewVariables(VVAccess.ReadWrite)]
public string EquippedPrefix
{
get => _equippedPrefix;
set => _equippedPrefix = value;
}
public (RSI rsi, RSI.StateId stateId)? GetInHandStateInfo(string hand)
{
if (RsiPath == null)
{
return null;
}
var rsi = GetRSI();
var stateId = EquippedPrefix != null ? $"{EquippedPrefix}-inhand-{hand}" : $"inhand-{hand}";
if (rsi.TryGetState(stateId, out _))
{
return (rsi, stateId);
}
return null;
}
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataFieldCached(ref RsiPath, "sprite", null);
serializer.DataFieldCached(ref _equippedPrefix, "prefix", null);
}
protected RSI GetRSI()
{
var resourceCache = IoCManager.Resolve<IResourceCache>();
return resourceCache.GetResource<RSIResource>(SharedSpriteComponent.TextureRoot / RsiPath).RSI;
}
public override void HandleComponentState(ComponentState curState, ComponentState nextState)
{
if(curState == null)
return;
var itemComponentState = (ItemComponentState)curState;
EquippedPrefix = itemComponentState.EquippedPrefix;
}
}
}
|
mit
|
C#
|
5c75e90f2b870c1b52409fb11abc7230b69338aa
|
Add support for dialog viewmodels supplied by a Func factory.
|
mthamil/SharpEssentials
|
SharpEssentials.Controls/Commands/OpenDialogCommand.cs
|
SharpEssentials.Controls/Commands/OpenDialogCommand.cs
|
// Sharp Essentials
// Copyright 2014 Matthew Hamilton - matthamilton@live.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Windows;
using SharpEssentials.Reflection;
namespace SharpEssentials.Controls.Commands
{
/// <summary>
/// Creates and displays a window of a given type.
/// </summary>
public class OpenDialogCommand : DependencyCommandBase
{
/// <summary>
/// Creates and opens a new instance of the specified Window
/// type.
/// </summary>
/// <param name="parameter">
/// The data context to set on the window. If null,
/// the data context will not be set, preventing an override
/// of any existing context.
/// </param>
public override void Execute(object parameter)
{
var window = (Window)Activator.CreateInstance(Type);
if (parameter != null)
{
// Detect Lazy<T> data contexts.
var parameterType = parameter.GetType();
if (parameterType.IsClosedTypeOf(LazyType))
parameter = parameterType.GetProperty(LazyValueName).GetValue(parameter);
// Detect Func<T> data contexts.
if (parameterType.IsClosedTypeOf(FuncType))
parameter = parameterType.GetMethod(FuncInvokeName).Invoke(parameter, null);
window.DataContext = parameter;
}
if (Owner != null)
window.Owner = Owner;
window.ShowDialog();
}
/// <summary>
/// The type of window to create.
/// </summary>
public Type Type { get; set; }
/// <summary>
/// The new window's owner.
/// </summary>
public Window Owner
{
get { return (Window)GetValue(OwnerProperty); }
set { SetValue(OwnerProperty, value); }
}
/// <summary>
/// The Owner dependency property.
/// </summary>
public static readonly DependencyProperty OwnerProperty =
DependencyProperty.RegisterAttached(nameof(Owner),
typeof(Window),
typeof(OpenDialogCommand),
new FrameworkPropertyMetadata(null));
private static readonly Type LazyType = typeof(Lazy<>);
private const string LazyValueName = nameof(Lazy<object>.Value);
private static readonly Type FuncType = typeof(Func<>);
private const string FuncInvokeName = nameof(Func<object>.Invoke);
}
}
|
// Sharp Essentials
// Copyright 2014 Matthew Hamilton - matthamilton@live.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Windows;
using SharpEssentials.Reflection;
namespace SharpEssentials.Controls.Commands
{
/// <summary>
/// Creates and displays a window of a given type.
/// </summary>
public class OpenDialogCommand : DependencyCommandBase
{
/// <summary>
/// Creates and opens a new instance of the specified Window
/// type.
/// </summary>
/// <param name="parameter">
/// The data context to set on the window. If null,
/// the data context will not be set, preventing an override
/// of any existing context.
/// </param>
public override void Execute(object parameter)
{
var window = (Window)Activator.CreateInstance(Type);
if (parameter != null)
{
// Detect Lazy<T> data contexts.
var parameterType = parameter.GetType();
if (parameterType.IsClosedTypeOf(LazyType))
parameter = parameterType.GetProperty(LazyValueName).GetValue(parameter);
window.DataContext = parameter;
}
if (Owner != null)
window.Owner = Owner;
window.ShowDialog();
}
/// <summary>
/// The type of window to create.
/// </summary>
public Type Type { get; set; }
/// <summary>
/// The new window's owner.
/// </summary>
public Window Owner
{
get { return (Window)GetValue(OwnerProperty); }
set { SetValue(OwnerProperty, value); }
}
/// <summary>
/// The Owner dependency property.
/// </summary>
public static readonly DependencyProperty OwnerProperty =
DependencyProperty.RegisterAttached(nameof(Owner),
typeof(Window),
typeof(OpenDialogCommand),
new FrameworkPropertyMetadata(null));
private static readonly Type LazyType = typeof(Lazy<>);
private const string LazyValueName = nameof(Lazy<object>.Value);
}
}
|
apache-2.0
|
C#
|
5f52fe11a7380d28187c57232a93b24af146788a
|
Add a default value for changeset.workitems.
|
guyboltonking/git-tfs,guyboltonking/git-tfs,adbre/git-tfs,PKRoma/git-tfs,irontoby/git-tfs,TheoAndersen/git-tfs,steveandpeggyb/Public,allansson/git-tfs,jeremy-sylvis-tmg/git-tfs,WolfVR/git-tfs,allansson/git-tfs,NathanLBCooper/git-tfs,bleissem/git-tfs,jeremy-sylvis-tmg/git-tfs,codemerlin/git-tfs,hazzik/git-tfs,jeremy-sylvis-tmg/git-tfs,WolfVR/git-tfs,steveandpeggyb/Public,adbre/git-tfs,pmiossec/git-tfs,irontoby/git-tfs,vzabavnov/git-tfs,TheoAndersen/git-tfs,steveandpeggyb/Public,hazzik/git-tfs,NathanLBCooper/git-tfs,adbre/git-tfs,allansson/git-tfs,andyrooger/git-tfs,codemerlin/git-tfs,TheoAndersen/git-tfs,spraints/git-tfs,WolfVR/git-tfs,modulexcite/git-tfs,bleissem/git-tfs,NathanLBCooper/git-tfs,git-tfs/git-tfs,codemerlin/git-tfs,bleissem/git-tfs,kgybels/git-tfs,modulexcite/git-tfs,spraints/git-tfs,kgybels/git-tfs,kgybels/git-tfs,spraints/git-tfs,hazzik/git-tfs,TheoAndersen/git-tfs,allansson/git-tfs,guyboltonking/git-tfs,hazzik/git-tfs,irontoby/git-tfs,modulexcite/git-tfs
|
GitTfs/Core/TfsChangesetInfo.cs
|
GitTfs/Core/TfsChangesetInfo.cs
|
using System.Collections.Generic;
using System.Linq;
namespace Sep.Git.Tfs.Core
{
public class TfsChangesetInfo
{
public IGitTfsRemote Remote { get; set; }
public long ChangesetId { get; set; }
public string GitCommit { get; set; }
public IEnumerable<ITfsWorkitem> Workitems { get; set; }
public TfsChangesetInfo()
{
Workitems = Enumerable.Empty<ITfsWorkitem>();
}
}
}
|
using System.Collections.Generic;
namespace Sep.Git.Tfs.Core
{
public class TfsChangesetInfo
{
public IGitTfsRemote Remote { get; set; }
public long ChangesetId { get; set; }
public string GitCommit { get; set; }
public IEnumerable<ITfsWorkitem> Workitems { get; set; }
}
}
|
apache-2.0
|
C#
|
0133ee962da47e25fcc6255a94833f34db73955b
|
Change JoystickSettingsStrings.cs text
|
NeoAdonis/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu
|
osu.Game/Localisation/JoystickSettingsStrings.cs
|
osu.Game/Localisation/JoystickSettingsStrings.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.Localisation;
namespace osu.Game.Localisation
{
public static class JoystickSettingsStrings
{
private const string prefix = @"osu.Game.Resources.Localisation.JoystickSettings";
/// <summary>
/// "Joystick / Gamepad"
/// </summary>
public static LocalisableString JoystickGamepad => new TranslatableString(getKey(@"joystick_gamepad"), @"Joystick / Gamepad");
/// <summary>
/// "Deadzone Threshold"
/// </summary>
public static LocalisableString DeadzoneThreshold => new TranslatableString(getKey(@"deadzone_threshold"), @"Deadzone");
private static string getKey(string key) => $@"{prefix}:{key}";
}
}
|
// 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.Localisation;
namespace osu.Game.Localisation
{
public static class JoystickSettingsStrings
{
private const string prefix = @"osu.Game.Resources.Localisation.JoystickSettings";
/// <summary>
/// "Joystick / Gamepad"
/// </summary>
public static LocalisableString JoystickGamepad => new TranslatableString(getKey(@"joystick_gamepad"), @"Joystick / Gamepad");
/// <summary>
/// "Deadzone Threshold"
/// </summary>
public static LocalisableString DeadzoneThreshold => new TranslatableString(getKey(@"deadzone_threshold"), @"Deadzone Threshold");
private static string getKey(string key) => $@"{prefix}:{key}";
}
}
|
mit
|
C#
|
d7f2f98c7807431537aee76b584dd54b0145f7d9
|
fix bug
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/Behaviors/SplitViewAutoBehavior.cs
|
WalletWasabi.Fluent/Behaviors/SplitViewAutoBehavior.cs
|
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Xaml.Interactivity;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
namespace WalletWasabi.Fluent.Behaviors
{
public class SplitViewAutoBehavior : Behavior<SplitView>
{
private CompositeDisposable Disposables { get; set; }
protected override void OnAttached()
{
Disposables = new CompositeDisposable();
Disposables.Add(AssociatedObject.WhenAnyValue(x => x.Bounds)
.DistinctUntilChanged()
.Subscribe(SplitViewBoundsChanged));
base.OnAttached();
}
private void SplitViewBoundsChanged(Rect x)
{
if (AssociatedObject is null)
{
return;
}
if (x.Width <= 650)
{
AssociatedObject.DisplayMode = SplitViewDisplayMode.CompactOverlay;
if (AssociatedObject.IsPaneOpen)
{
AssociatedObject.IsPaneOpen = false;
}
}
else
{
AssociatedObject.DisplayMode = SplitViewDisplayMode.CompactInline;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
Disposables?.Dispose();
}
}
}
|
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Xaml.Interactivity;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
namespace WalletWasabi.Fluent.Behaviors
{
public class SplitViewAutoBehavior : Behavior<SplitView>
{
private CompositeDisposable Disposables { get; set; }
protected override void OnAttached()
{
Disposables = new CompositeDisposable();
Disposables.Add(AssociatedObject.WhenAnyValue(x => x.Bounds)
.DistinctUntilChanged()
.Subscribe(SplitViewBoundsChanged));
base.OnAttached();
}
private void SplitViewBoundsChanged(Rect x)
{
if (AssociatedObject is null)
{
return;
}
if (x.Width <= 650)
{
AssociatedObject.DisplayMode = SplitViewDisplayMode.CompactOverlay;
if (AssociatedObject.IsPaneOpen)
{
AssociatedObject.IsPaneOpen = false;
}
}
else
{
AssociatedObject.DisplayMode = SplitViewDisplayMode.CompactInline;
if (!AssociatedObject.IsPaneOpen)
{
AssociatedObject.IsPaneOpen = true;
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
Disposables?.Dispose();
}
}
}
|
mit
|
C#
|
726322c523653ce2670a65834c76dfea9ee5bea9
|
Improve handling of bad format for intervals
|
Seddryck/NBi,Seddryck/NBi
|
NBi.Core/Calculation/Predicate/Numeric/NumericWithinRange.cs
|
NBi.Core/Calculation/Predicate/Numeric/NumericWithinRange.cs
|
using NBi.Core.ResultSet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Scalar.Interval;
using NBi.Core.Scalar.Caster;
namespace NBi.Core.Calculation.Predicate.Numeric
{
class NumericWithinRange : AbstractPredicateReference
{
public NumericWithinRange(bool not, object reference) : base(not, reference)
{ }
protected override bool Apply(object x)
{
var builder = new NumericIntervalBuilder(Reference);
builder.Build();
if (!builder.IsValid())
throw builder.GetException();
var interval = builder.GetInterval();
var caster = new NumericCaster();
var numX = caster.Execute(x);
return interval.Contains(numX);
}
public override string ToString() => $"is within the interval {Reference}";
}
}
|
using NBi.Core.ResultSet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBi.Core.Scalar.Interval;
using NBi.Core.Scalar.Caster;
namespace NBi.Core.Calculation.Predicate.Numeric
{
class NumericWithinRange : AbstractPredicateReference
{
public NumericWithinRange(bool not, object reference) : base(not, reference)
{ }
protected override bool Apply(object x)
{
var builder = new NumericIntervalBuilder(Reference);
builder.Build();
var interval = builder.GetInterval();
var caster = new NumericCaster();
var numX = caster.Execute(x);
return interval.Contains(numX);
}
public override string ToString() => $"is within the interval {Reference}";
}
}
|
apache-2.0
|
C#
|
ed9edb8759359a8ad2394e377727ab23f28d2070
|
remove extra stack creation via curly brace in switch statements
|
cra0zy/MonoGame.Extended,LithiumToast/MonoGame.Extended,HyperionMT/MonoGame.Extended,rafaelalmeidatk/MonoGame.Extended,Aurioch/MonoGame.Extended,rafaelalmeidatk/MonoGame.Extended
|
Source/MonoGame.Extended/Graphics/PrimitiveTypeExtensions.cs
|
Source/MonoGame.Extended/Graphics/PrimitiveTypeExtensions.cs
|
using System;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGame.Extended.Graphics
{
public static class PrimitiveTypeExtensions
{
internal static int GetPrimitiveCount(this PrimitiveType primitiveType, int verticesOrIndicesCount)
{
switch (primitiveType)
{
case PrimitiveType.LineStrip:
return verticesOrIndicesCount - 1;
case PrimitiveType.LineList:
return verticesOrIndicesCount / 2;
case PrimitiveType.TriangleStrip:
return verticesOrIndicesCount - 2;
case PrimitiveType.TriangleList:
return verticesOrIndicesCount / 3;
default:
throw new ArgumentException("Invalid primitive type.");
}
}
}
}
|
using System;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGame.Extended.Graphics
{
public static class PrimitiveTypeExtensions
{
internal static int GetPrimitiveCount(this PrimitiveType primitiveType, int verticesOrIndicesCount)
{
switch (primitiveType)
{
case PrimitiveType.LineStrip:
{
return verticesOrIndicesCount - 1;
}
case PrimitiveType.LineList:
{
return verticesOrIndicesCount / 2;
}
case PrimitiveType.TriangleStrip:
{
return verticesOrIndicesCount - 2;
}
case PrimitiveType.TriangleList:
{
return verticesOrIndicesCount / 3;
}
default:
{
throw new ArgumentException("Invalid primitive type.");
}
}
}
}
}
|
mit
|
C#
|
c55b58c6386fa8948682ece4e5da3b06cad3678d
|
Update EntityQueryRepository.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs
|
TIKSN.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>, IQueryRepository<TEntity, TIdentity>
where TContext : DbContext
where TEntity : class, IEntity<TIdentity>, new()
where TIdentity : IEquatable<TIdentity>
{
public EntityQueryRepository(TContext dbContext) : base(dbContext)
{
}
protected IQueryable<TEntity> Entities => dbContext.Set<TEntity>().AsNoTracking();
public Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.AnyAsync(a => a.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken);
}
public async Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids, CancellationToken cancellationToken)
{
return await Entities.Where(entity => ids.Contains(entity.ID)).ToListAsync(cancellationToken);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>, IQueryRepository<TEntity, TIdentity>
where TContext : DbContext
where TEntity : class, IEntity<TIdentity>, new()
where TIdentity : IEquatable<TIdentity>
{
public EntityQueryRepository(TContext dbContext) : base(dbContext)
{
}
protected IQueryable<TEntity> Entities => dbContext.Set<TEntity>().AsNoTracking();
public Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.AnyAsync(a => a.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken);
}
public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken)
{
return Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken);
}
}
}
|
mit
|
C#
|
63f965d794f7315415965e6ccd2bc16c22fbdb96
|
Remove location from model
|
codevlabs/Glimpse,rho24/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,gabrielweyer/Glimpse,codevlabs/Glimpse,rho24/Glimpse,dudzon/Glimpse,flcdrg/Glimpse,Glimpse/Glimpse,SusanaL/Glimpse,sorenhl/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,rho24/Glimpse,dudzon/Glimpse,elkingtonmcb/Glimpse,codevlabs/Glimpse,SusanaL/Glimpse,paynecrl97/Glimpse,paynecrl97/Glimpse,sorenhl/Glimpse,dudzon/Glimpse,paynecrl97/Glimpse,flcdrg/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,gabrielweyer/Glimpse,SusanaL/Glimpse,flcdrg/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse
|
source/Glimpse.Mvc4.MusicStore.Sample/Models/Album.cs
|
source/Glimpse.Mvc4.MusicStore.Sample/Models/Album.cs
|
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Spatial;
namespace MvcMusicStore.Models
{
public class Album {
[ScaffoldColumn(false)]
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
[Required]
[StringLength(160, MinimumLength = 2)]
public string Title { get; set; }
[Required]
[Range(0.01, 100.00)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[DisplayName("Album Art URL")]
[StringLength(1024)]
public string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
}
}
|
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Spatial;
namespace MvcMusicStore.Models
{
public class Album {
[ScaffoldColumn(false)]
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
[Required]
[StringLength(160, MinimumLength = 2)]
public string Title { get; set; }
[Required]
[Range(0.01, 100.00)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[DisplayName("Album Art URL")]
[StringLength(1024)]
public string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
public DbGeography Location { get; set; }
}
}
|
apache-2.0
|
C#
|
5ed19cacf3629bb263212aff05ac95ece06ebaff
|
Make IOperationCodeable contravariant
|
HelloKitty/Booma.Proxy
|
src/Booma.Packet.Common/Message/IOperationCodeable.cs
|
src/Booma.Packet.Common/Message/IOperationCodeable.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Booma.Proxy;
namespace Booma
{
public interface IOperationCodeable<TOperationCodeType>
public interface IOperationCodeable<out TOperationCodeType>
where TOperationCodeType : Enum
{
TOperationCodeType OperationCode { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Booma.Proxy;
namespace Booma
{
public interface IOperationCodeable<TOperationCodeType>
where TOperationCodeType : Enum
{
TOperationCodeType OperationCode { get; }
}
}
|
agpl-3.0
|
C#
|
ad88f717d68a79cdaf27d3526eddc98cb600b337
|
fix typo
|
charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui,tebben/Mapsui
|
Mapsui/UI/InfoEventArgs.cs
|
Mapsui/UI/InfoEventArgs.cs
|
using System;
using Mapsui.Geometries;
using Mapsui.Layers;
using Mapsui.Providers;
namespace Mapsui.UI
{
public class InfoEventArgs : EventArgs
{
/// <summary>
/// The layer to which the touched feature belongs
/// </summary>
public ILayer Layer { get; set; }
/// <summary>
/// The feature touched but the user
/// </summary>
public IFeature Feature { get; set; }
/// <summary>
/// World position of the place the user touched
/// </summary>
public Point WorldPosition { get; set; }
/// <summary>
/// Screen position of the place the user touched
/// </summary>
public Point ScreenPosition { get; set; }
/// <summary>
/// Number of times the user tapped the location
/// </summary>
public int NumTaps { get; set; }
/// <summary>
/// If the interaction was handled by the event subscriber
/// </summary>
public bool Handled { get; set; }
}
}
|
using System;
using Mapsui.Geometries;
using Mapsui.Layers;
using Mapsui.Providers;
namespace Mapsui.UI
{
public class InfoEventArgs : EventArgs
{
/// <summary>
/// The layer to which the touched feature belongs
/// </summary>
public ILayer Layer { get; set; }
/// <summary>
/// The feature touched but the user
/// </summary>
public IFeature Feature { get; set; }
/// <summary>
/// World position of the place the user touched
/// </summary>
public Point WorldPosition { get; set; }
/// <summary>
/// Screen position of the place the user touched
/// </summary>
public Point ScreenPosition { get; set; }
/// <summary>
/// Number of times the user tapped the location
/// </summary>
public int NumTaps { get; set; }
/// <summary>
/// If the interaction was handled but the event subscriber
/// </summary>
public bool Handled { get; set; }
}
}
|
mit
|
C#
|
84714108acdb029e827fe13ac894c0f0a16b2d65
|
Fix missing s in Expression(s)
|
couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net
|
src/Couchbase.Lite.Shared/Query/IndexConfiguration.cs
|
src/Couchbase.Lite.Shared/Query/IndexConfiguration.cs
|
//
// IndexConfiguration.cs
//
// Copyright (c) 2021 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using LiteCore.Interop;
using System;
namespace Couchbase.Lite.Internal.Query
{
public abstract class IndexConfiguration
{
#region Properties
/// <summary>
/// Gets the expressions to use to create the index
/// </summary>
public string[] Expressions { get; }
internal C4QueryLanguage QueryLanguage { get; }
internal C4IndexType IndexType { get; }
internal abstract C4IndexOptions Options { get; }
#endregion
#region Constructor
internal IndexConfiguration(C4IndexType indexType, params string[] items)
: this(indexType, C4QueryLanguage.N1QLQuery)
{
Expressions = items;
}
internal IndexConfiguration(C4IndexType indexType, C4QueryLanguage queryLanguage)
{
IndexType = indexType;
QueryLanguage = queryLanguage;
}
#endregion
#region Internal Methods
internal string ToN1QL()
{
if (Expressions.Length == 1)
return Expressions[0];
return String.Join(",", Expressions);
}
#endregion
}
}
|
//
// IndexConfiguration.cs
//
// Copyright (c) 2021 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using LiteCore.Interop;
using System;
namespace Couchbase.Lite.Internal.Query
{
public abstract class IndexConfiguration
{
#region Properties
/// <summary>
/// Gets the expressions to use to create the index
/// </summary>
public string[] Expression { get; }
internal C4QueryLanguage QueryLanguage { get; }
internal C4IndexType IndexType { get; }
internal abstract C4IndexOptions Options { get; }
#endregion
#region Constructor
internal IndexConfiguration(C4IndexType indexType, params string[] items)
: this(indexType, C4QueryLanguage.N1QLQuery)
{
Expression = items;
}
internal IndexConfiguration(C4IndexType indexType, C4QueryLanguage queryLanguage)
{
IndexType = indexType;
QueryLanguage = queryLanguage;
}
#endregion
#region Internal Methods
internal string ToN1QL()
{
if (Expression.Length == 1)
return Expression[0];
return String.Join(",", Expression);
}
#endregion
}
}
|
apache-2.0
|
C#
|
f7593e2446569755e288577871860d089770aa7b
|
Update LogWithNameAttribute.cs
|
destructurama/attributed
|
src/Destructurama.Attributed/Attributed/LogWithNameAttribute.cs
|
src/Destructurama.Attributed/Attributed/LogWithNameAttribute.cs
|
// Copyright 2015-2018 Destructurama Contributors, Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Serilog.Core;
using Serilog.Events;
using System;
namespace Destructurama.Attributed
{
/// <summary>
/// Apply to a property to use a custom name when that property is logged.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class LogWithNameAttribute : Attribute, IPropertyDestructuringAttribute
{
/// <summary>
/// Initialize a new instance of <see cref="LogWithNameAttribute"/>.
/// </summary>
/// <param name="newName">The new name to use when logging the target property.</param>
public LogWithNameAttribute(string newName)
{
PropertyName = newName;
}
/// <summary>
/// The new name to use when logging the target property.
/// </summary>
public string PropertyName { get; }
/// <summary>
/// <inheritdoc/>
/// </summary>
public bool TryCreateLogEventProperty(string name, object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventProperty property)
{
var propValue = propertyValueFactory.CreatePropertyValue(value);
LogEventPropertyValue logEventPropVal = propValue switch
{
ScalarValue scalar => new ScalarValue(scalar.Value),
DictionaryValue dictionary => new DictionaryValue(dictionary.Elements),
SequenceValue sequence => new SequenceValue(sequence.Elements),
StructureValue structure => new StructureValue(structure.Properties),
_ => null
};
property = new LogEventProperty(PropertyName, logEventPropVal);
return true;
}
}
}
|
// Copyright 2015-2018 Destructurama Contributors, Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Serilog.Core;
using Serilog.Events;
using System;
namespace Destructurama.Attributed
{
/// <summary>
///Apply to a property to use a custom name when that property is logged.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class LogWithNameAttribute : Attribute, IPropertyDestructuringAttribute
{
/// <summary>
/// Initialize a new instance of <see cref="LogWithNameAttribute"/>.
/// </summary>
/// <param name="newName">The new name to use when logging the target property.</param>
public LogWithNameAttribute(string newName)
{
PropertyName = newName;
}
/// <summary>
/// The new name to use when logging the target property.
/// </summary>
public string PropertyName { get; }
/// <summary>
/// <inheritdoc/>
/// </summary>
public bool TryCreateLogEventProperty(string name, object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventProperty property)
{
var propValue = propertyValueFactory.CreatePropertyValue(value);
LogEventPropertyValue logEventPropVal = propValue switch
{
ScalarValue scalar => new ScalarValue(scalar.Value),
DictionaryValue dictionary => new DictionaryValue(dictionary.Elements),
SequenceValue sequence => new SequenceValue(sequence.Elements),
StructureValue structure => new StructureValue(structure.Properties),
_ => null
};
property = new LogEventProperty(PropertyName, logEventPropVal);
return true;
}
}
}
|
apache-2.0
|
C#
|
cba228f56e3940422fab9f8a17b5855dbbc0ac0f
|
Augmente le stress quand on ne remarque pas un élève
|
Steguer/GreatParanoidTeacher
|
Assets/Scripts/Student.cs
|
Assets/Scripts/Student.cs
|
using UnityEngine;
using System.Collections;
public class Student : MonoBehaviour {
public float Timer;
public int EnrageCountHit = 10;
public float TimerFail;
public int incrementStress = 1;
private Animator animator;
private bool isClickable = false;
private float TimerFailCopy;
private int numCheat;
private bool enaStress = true;
// Use this for initialization
void Start () {
animator = GetComponent<Animator> ();
TimerFailCopy = TimerFail;
//TimerSpamCopy = TimerSpam;
}
public void Cheat(bool EnrageMode)
{
if (!EnrageMode) {
animator.SetInteger ("numCheat", Random.Range (1, 3));
}
else
{
animator.SetBool ("Enraged",true);
}
animator.SetTrigger ("isCheating");
}
public void Hit()
{
animator.SetTrigger ("isHit");
AnimatorStateInfo currentAnimeState = animator.GetCurrentAnimatorStateInfo(0);
if (currentAnimeState.IsName ("Enrage") | currentAnimeState.IsName ("EnrageHit")) {
EnrageCountHit--;
if(EnrageCountHit<=0)
{
animator.SetBool("Enrage",false);
EnrageCountHit=10;
}
}
}
// Update is called once per frame
void Update () {
CheckStates ();
}
void CheckStates ()
{
if (TimerFail > 0.0f)
TimerFail -= Time.deltaTime;
if(TimerFail<=0.0f)
animator.SetBool("isFail",true);
AnimatorStateInfo currentAnimeState = animator.GetCurrentAnimatorStateInfo(0);
if (currentAnimeState.IsName ("StudentIdle")) {
isClickable = true;
enaStress = true;
animator.SetBool ("isFail", false);
TimerFail = TimerFailCopy;
animator.SetBool ("Enraged",false);
}
if(currentAnimeState.IsName("StudentCheating1") ||currentAnimeState.IsName("StudentCheating2") ||currentAnimeState.IsName("StudentCheating3"))
if(isClickable){
//Debug.Log ("StudentCheating");
}
if(currentAnimeState.IsName("StudentEvilHit"))
if(isClickable){
//Augmenter les points ?
Debug.Log ("StudentEvilHit");
isClickable=false;
}
if(currentAnimeState.IsName("StudentInnocentHit"))
if(isClickable){
//Decementer les Points ?
Debug.Log ("StudentInnocentHit");
isClickable=false;
}
if (currentAnimeState.IsName ("StudentSucceed")) {
//Incrementer le stress
if(enaStress) {
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>().playerStress += incrementStress;
enaStress = false;
}
animator.SetBool("isFail",false);
}
}
}
|
using UnityEngine;
using System.Collections;
public class Student : MonoBehaviour {
private Animator animator;
private bool isClickable = false;
public float Timer;
public float TimerFail;
private float TimerFailCopy;
public int EnrageCountHit = 10;
private int numCheat;
// Use this for initialization
void Start () {
animator = GetComponent<Animator> ();
TimerFailCopy = TimerFail;
//TimerSpamCopy = TimerSpam;
}
public void Cheat(bool EnrageMode)
{
if (!EnrageMode) {
animator.SetInteger ("numCheat", Random.Range (1, 3));
}
else
{
animator.SetBool ("Enraged",true);
}
animator.SetTrigger ("isCheating");
}
public void Hit()
{
animator.SetTrigger ("isHit");
AnimatorStateInfo currentAnimeState = animator.GetCurrentAnimatorStateInfo(0);
if (currentAnimeState.IsName ("Enrage") | currentAnimeState.IsName ("EnrageHit")) {
EnrageCountHit--;
if(EnrageCountHit<=0)
{
animator.SetBool("Enrage",false);
EnrageCountHit=10;
}
}
}
// Update is called once per frame
void Update () {
CheckStates ();
}
void CheckStates ()
{
if (TimerFail > 0.0f)
TimerFail -= Time.deltaTime;
if(TimerFail<=0.0f)
animator.SetBool("isFail",true);
AnimatorStateInfo currentAnimeState = animator.GetCurrentAnimatorStateInfo(0);
if (currentAnimeState.IsName ("StudentIdle")) {
isClickable = true;
animator.SetBool ("isFail", false);
TimerFail = TimerFailCopy;
animator.SetBool ("Enraged",false);
}
if(currentAnimeState.IsName("StudentCheating1") ||currentAnimeState.IsName("StudentCheating2") ||currentAnimeState.IsName("StudentCheating3"))
if(isClickable){
//Debug.Log ("StudentCheating");
}
if(currentAnimeState.IsName("StudentEvilHit"))
if(isClickable){
//Augmenter les points ?
Debug.Log ("StudentEvilHit");
isClickable=false;
}
if(currentAnimeState.IsName("StudentInnocentHit"))
if(isClickable){
//Decementer les Points ?
Debug.Log ("StudentInnocentHit");
isClickable=false;
}
if (currentAnimeState.IsName ("StudentSucceed")) {
//Incrementer le stress
animator.SetBool("isFail",false);
}
}
}
|
mit
|
C#
|
50430e277ebdc7cceba0c5780c8199489b6bafbf
|
Fix for test Legacy.MasterDetailTest.MasterDetail
|
lnu/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core
|
src/NHibernate/Hql/Ast/ANTLR/Tree/HqlSqlWalkerTreeNodeStream.cs
|
src/NHibernate/Hql/Ast/ANTLR/Tree/HqlSqlWalkerTreeNodeStream.cs
|
using System;
using Antlr.Runtime.Tree;
namespace NHibernate.Hql.Ast.ANTLR.Tree
{
[CLSCompliant(false)]
public class HqlSqlWalkerTreeNodeStream : CommonTreeNodeStream
{
public HqlSqlWalkerTreeNodeStream(object tree) : base(tree) {}
public HqlSqlWalkerTreeNodeStream(ITreeAdaptor adaptor, object tree) : base(adaptor, tree) {}
public HqlSqlWalkerTreeNodeStream(ITreeAdaptor adaptor, object tree, int initialBufferSize)
: base(adaptor, tree, initialBufferSize) {}
/// <summary>
/// Insert a new node into both the Tree and the Node Array. Add DOWN & UP nodes if needed
/// </summary>
/// <param name="parent">The parent node</param>
/// <param name="child">The child node</param>
public void InsertChild(IASTNode parent, IASTNode child)
{
if (child.ChildCount > 0)
{
throw new InvalidOperationException("Currently do not support adding nodes with children");
}
int parentIndex = nodes.IndexOf(parent);
int numberOfChildNodes = NumberOfChildNodes(parentIndex);
int insertPoint;
if (numberOfChildNodes == 0)
{
insertPoint = parentIndex + 1; // We want to insert immediately after the parent
nodes.Insert(insertPoint, down);
insertPoint++; // We've just added a new node
}
else
{
insertPoint = parentIndex + numberOfChildNodes;
}
parent.AddChild(child);
nodes.Insert(insertPoint, child);
insertPoint++;
if (numberOfChildNodes == 0)
{
nodes.Insert(insertPoint, up);
}
}
/// <summary>
/// Count the number of child nodes (including DOWNs & UPs) of a parent node
/// </summary>
/// <param name="parentIndex">The index of the parent in the node array</param>
/// <returns>The number of child nodes</returns>
int NumberOfChildNodes(int parentIndex)
{
if (nodes.Count -1 == parentIndex)
{
// We are at the end
return 0;
}
else if (nodes[parentIndex + 1] != down)
{
// Next node is not a DOWN node, so we have no children
return 0;
}
else
{
// Count the DOWNs & UPs
int downCount = 0;
int index = 1;
do
{
if (nodes[parentIndex + index] == down)
{
downCount++;
}
else if (nodes[parentIndex + index] == up)
{
downCount--;
}
index++;
} while (downCount > 0);
return index - 1;
}
}
}
}
|
using System;
using Antlr.Runtime.Tree;
namespace NHibernate.Hql.Ast.ANTLR.Tree
{
[CLSCompliant(false)]
public class HqlSqlWalkerTreeNodeStream : CommonTreeNodeStream
{
public HqlSqlWalkerTreeNodeStream(object tree) : base(tree) {}
public HqlSqlWalkerTreeNodeStream(ITreeAdaptor adaptor, object tree) : base(adaptor, tree) {}
public HqlSqlWalkerTreeNodeStream(ITreeAdaptor adaptor, object tree, int initialBufferSize)
: base(adaptor, tree, initialBufferSize) {}
public void InsertChild(IASTNode parent, IASTNode child)
{
// Adding a child to the current node. If currently no children, then also need to insert Down & Up nodes
bool needUp = false;
int insertPoint = nodes.IndexOf(parent) + parent.ChildCount + 1;
if (parent.ChildCount == 0)
{
nodes.Insert(insertPoint, down);
needUp = true;
}
insertPoint++; // We either just inserted a Down node, or one existed already which we need to count
parent.AddChild(child);
nodes.Insert(insertPoint, child);
insertPoint++;
if (needUp)
{
nodes.Insert(insertPoint, up);
}
}
}
}
|
lgpl-2.1
|
C#
|
db53909c61753cb9a4121d9960d0b764d586186a
|
add DontDestroyOnLoad() for ToggleComm
|
yasokada/unity-150923-udpRs232c,yasokada/unity-150831-udpMonitor
|
Assets/udpMonitorScript.cs
|
Assets/udpMonitorScript.cs
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class udpMonitorScript : MonoBehaviour {
Thread monThr = null; // monitor Thread
static bool created = false;
public Toggle ToggleComm;
private string ipadr1;
private string ipadr2;
private int port;
void Start () {
if (!created) {
created = true;
DontDestroyOnLoad (this.gameObject);
DontDestroyOnLoad(ToggleComm.gameObject.transform.parent.gameObject);
ToggleComm.isOn = false; // false at first
monThr = new Thread (new ThreadStart (FuncMonData));
monThr.Start ();
} else {
Destroy(this.gameObject);
Destroy(ToggleComm.gameObject.transform.parent.gameObject);
}
}
void Monitor() {
UdpClient client = new UdpClient (port);
client.Client.ReceiveTimeout = 300; // msec
client.Client.Blocking = false;
while (ToggleComm.isOn) {
try {
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.ASCII.GetString(data);
if (text.Length == 0) {
Thread.Sleep(20);
continue;
}
string fromIP = anyIP.Address.ToString();
// send to the other
if (fromIP.Equals(ipadr1)) {
client.Send(data, data.Length, ipadr2, port);
Debug.Log("from: " + ipadr1 + " to " + ipadr2);
Debug.Log(data.Length.ToString());
} else {
client.Send(data, data.Length, ipadr1, port);
Debug.Log("from: " + ipadr2 + " to " + ipadr1);
Debug.Log(data.Length.ToString());
}
}
catch (Exception err) {
}
// without this sleep, on android, the app will freeze at Unity splash screen
Thread.Sleep(200);
}
client.Close ();
}
private bool readSetting() {
// TODO: return false if reading fails
ipadr1 = SettingKeeperControl.str_ipadr1;
ipadr2 = SettingKeeperControl.str_ipadr2;
port = SettingKeeperControl.port;
return true;
}
private void FuncMonData()
{
Debug.Log ("Start FuncMonData");
while (true) {
while(ToggleComm.isOn == false) {
Thread.Sleep(100);
continue;
}
Debug.Log("read setting");
readSetting();
Debug.Log("monitor");
Monitor();
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class udpMonitorScript : MonoBehaviour {
Thread monThr = null; // monitor Thread
static bool created = false;
public Toggle ToggleComm;
private string ipadr1;
private string ipadr2;
private int port;
void Start () {
if (!created) {
DontDestroyOnLoad (this);
created = true;
ToggleComm.isOn = false; // false at first
monThr = new Thread (new ThreadStart (FuncMonData));
monThr.Start ();
} else {
Destroy(this);
}
}
void Monitor() {
UdpClient client = new UdpClient (port);
client.Client.ReceiveTimeout = 300; // msec
client.Client.Blocking = false;
while (ToggleComm.isOn) {
try {
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.ASCII.GetString(data);
if (text.Length == 0) {
Thread.Sleep(20);
continue;
}
string fromIP = anyIP.Address.ToString();
// send to the other
if (fromIP.Equals(ipadr1)) {
client.Send(data, data.Length, ipadr2, port);
Debug.Log("from: " + ipadr1 + " to " + ipadr2);
Debug.Log(data.Length.ToString());
} else {
client.Send(data, data.Length, ipadr1, port);
Debug.Log("from: " + ipadr2 + " to " + ipadr1);
Debug.Log(data.Length.ToString());
}
}
catch (Exception err) {
}
// without this sleep, on android, the app will freeze at Unity splash screen
Thread.Sleep(200);
}
client.Close ();
}
private bool readSetting() {
// TODO: return false if reading fails
ipadr1 = SettingKeeperControl.str_ipadr1;
ipadr2 = SettingKeeperControl.str_ipadr2;
port = SettingKeeperControl.port;
return true;
}
private void FuncMonData()
{
Debug.Log ("Start FuncMonData");
while (true) {
while(ToggleComm.isOn == false) {
Thread.Sleep(100);
continue;
}
Debug.Log("read setting");
readSetting();
Debug.Log("monitor");
Monitor();
}
}
}
|
mit
|
C#
|
9e3568b0a1a537b2b69f3a72f1695684c5e30d72
|
add readSetting()
|
yasokada/unity-150923-udpRs232c,yasokada/unity-150831-udpMonitor
|
Assets/udpMonitorScript.cs
|
Assets/udpMonitorScript.cs
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Threading;
public class udpMonitorScript : MonoBehaviour {
Thread monThr; // monitor Thread
public Toggle ToggleComm;
private string ipadr1;
private string ipadr2;
private int port;
void Start () {
ToggleComm.isOn = false; // false at first
monThr = new Thread (new ThreadStart (FuncMonData));
monThr.Start ();
}
void Monitor() {
Debug.Log ("start monitor");
while (ToggleComm.isOn) {
Thread.Sleep(100);
}
Debug.Log ("end monitor");
}
private bool readSetting() {
// TODO: return false if reading fails
ipadr1 = SettingKeeperControl.str_ipadr1;
ipadr2 = SettingKeeperControl.str_ipadr2;
port = SettingKeeperControl.port;
return true;
}
private void FuncMonData()
{
Debug.Log ("Start FuncMonData");
while (true) {
while(ToggleComm.isOn == false) {
Thread.Sleep(100);
continue;
}
readSetting();
Monitor();
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Threading;
public class udpMonitorScript : MonoBehaviour {
Thread monThr; // monitor Thread
public Toggle ToggleComm;
void Start () {
monThr = new Thread (new ThreadStart (FuncMonData));
monThr.Start ();
}
void Update () {
}
void Monitor() {
Debug.Log ("start monitor");
while (ToggleComm.isOn) {
Thread.Sleep(100);
}
Debug.Log ("end monitor");
}
private void FuncMonData()
{
Debug.Log ("Start FuncMonData");
while (true) {
while(ToggleComm.isOn == false) {
Thread.Sleep(100);
continue;
}
Monitor();
}
}
}
|
mit
|
C#
|
27043bec591e481c712e4ed7bac1906122f7d33b
|
Remove custom SQL CE checks from IsConnectionStringConfigured
|
KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS
|
src/Umbraco.Core/Extensions/ConfigConnectionStringExtensions.cs
|
src/Umbraco.Core/Extensions/ConfigConnectionStringExtensions.cs
|
// Copyright (c) Umbraco.
// See LICENSE for more details.
using Umbraco.Cms.Core.Configuration;
namespace Umbraco.Extensions
{
public static class ConfigConnectionStringExtensions
{
public static bool IsConnectionStringConfigured(this ConfigConnectionString databaseSettings)
=> databaseSettings != null &&
!string.IsNullOrWhiteSpace(databaseSettings.ConnectionString) &&
!string.IsNullOrWhiteSpace(databaseSettings.ProviderName);
}
}
|
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.IO;
using System.Linq;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
namespace Umbraco.Extensions
{
public static class ConfigConnectionStringExtensions
{
public static bool IsConnectionStringConfigured(this ConfigConnectionString databaseSettings)
{
var dbIsSqlCe = false;
if (databaseSettings?.ProviderName != null)
{
dbIsSqlCe = databaseSettings.ProviderName == Constants.DbProviderNames.SqlCe;
}
var sqlCeDatabaseExists = false;
if (dbIsSqlCe)
{
var parts = databaseSettings.ConnectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dataSourcePart = parts.FirstOrDefault(x => x.InvariantStartsWith("Data Source="));
if (dataSourcePart != null)
{
var datasource = dataSourcePart.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
var filePath = datasource.Replace("Data Source=", string.Empty);
sqlCeDatabaseExists = File.Exists(filePath);
}
}
// Either the connection details are not fully specified or it's a SQL CE database that doesn't exist yet
if (databaseSettings == null
|| string.IsNullOrWhiteSpace(databaseSettings.ConnectionString) || string.IsNullOrWhiteSpace(databaseSettings.ProviderName)
|| (dbIsSqlCe && sqlCeDatabaseExists == false))
{
return false;
}
return true;
}
}
}
|
mit
|
C#
|
8e8f33ec7b5fb0a24f279692c76ba3d214997bc2
|
Remove null hinting for now
|
ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu,ZLima12/osu,peppy/osu-new,peppy/osu,EVAST9919/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,smoogipooo/osu,johnneijzen/osu,smoogipoo/osu
|
osu.Game/Rulesets/RulesetInfo.cs
|
osu.Game/Rulesets/RulesetInfo.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 System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;
namespace osu.Game.Rulesets
{
public class RulesetInfo : IEquatable<RulesetInfo>
{
public int? ID { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public string InstantiationInfo { get; set; }
[JsonIgnore]
public bool Available { get; set; }
public virtual Ruleset CreateInstance()
{
if (!Available) return null;
return (Ruleset)Activator.CreateInstance(Type.GetType(InstantiationInfo), this);
}
public bool Equals(RulesetInfo other) => other != null && ID == other.ID && Available == other.Available && Name == other.Name && InstantiationInfo == other.InstantiationInfo;
public override bool Equals(object obj) => obj is RulesetInfo rulesetInfo && Equals(rulesetInfo);
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
unchecked
{
var hashCode = ID.HasValue ? ID.GetHashCode() : 0;
hashCode = (hashCode * 397) ^ (InstantiationInfo != null ? InstantiationInfo.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Available.GetHashCode();
return hashCode;
}
}
public override string ToString() => $"{Name} ({ShortName}) ID: {ID}";
}
}
|
// 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;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace osu.Game.Rulesets
{
public class RulesetInfo : IEquatable<RulesetInfo>
{
public int? ID { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public string InstantiationInfo { get; set; }
[JsonIgnore]
public bool Available { get; set; }
[CanBeNull]
public virtual Ruleset CreateInstance()
{
if (!Available) return null;
return (Ruleset)Activator.CreateInstance(Type.GetType(InstantiationInfo), this);
}
public bool Equals(RulesetInfo other) => other != null && ID == other.ID && Available == other.Available && Name == other.Name && InstantiationInfo == other.InstantiationInfo;
public override bool Equals(object obj) => obj is RulesetInfo rulesetInfo && Equals(rulesetInfo);
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
unchecked
{
var hashCode = ID.HasValue ? ID.GetHashCode() : 0;
hashCode = (hashCode * 397) ^ (InstantiationInfo != null ? InstantiationInfo.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Available.GetHashCode();
return hashCode;
}
}
public override string ToString() => $"{Name} ({ShortName}) ID: {ID}";
}
}
|
mit
|
C#
|
a1d82ea1eb801906a48314ecf85977f017e9afec
|
Fix yfrog preview
|
fin-alice/Mystique,azyobuzin/Mystique
|
Casket/Uploaders/YFrog.cs
|
Casket/Uploaders/YFrog.cs
|
using Acuerdo.External.Uploader;
using Dulcet.ThirdParty;
using Dulcet.Twitter.Credential;
namespace Casket.Uploaders
{
public class YFrog : IUploader
{
private static string _appkey = "238DGHOTa6a8f8356246fb3d3e9c7dae65cb3970";
public string UploadImage(OAuth credential, string path, string comment)
{
string url;
if (!credential.UploadToYFrog(_appkey, path, out url))
{
return null;
}
else
{
return url;
}
}
public string ServiceName
{
get { return "YFrog"; }
}
public bool IsResolvable(string url)
{
return url.StartsWith("http://yfrog.com/") || url.StartsWith("http://twitter.yfrog.com/");
}
public string Resolve(string url)
{
if (IsResolvable(url))
return url.Replace("twitter.", "") + ":medium";
else
return null;
}
}
}
|
using Acuerdo.External.Uploader;
using Dulcet.ThirdParty;
using Dulcet.Twitter.Credential;
namespace Casket.Uploaders
{
public class YFrog : IUploader
{
private static string _appkey = "238DGHOTa6a8f8356246fb3d3e9c7dae65cb3970";
public string UploadImage(OAuth credential, string path, string comment)
{
string url;
if (!credential.UploadToYFrog(_appkey, path, out url))
{
return null;
}
else
{
return url;
}
}
public string ServiceName
{
get { return "YFrog"; }
}
public bool IsResolvable(string url)
{
return url.StartsWith("http://yfrog.com/");
}
public string Resolve(string url)
{
if (IsResolvable(url))
return url + ":medium";
else
return null;
}
}
}
|
mit
|
C#
|
97a2f6e93d39abd68b5a8793afa62b2df7a26172
|
Introduce custom IObserver
|
citizenmatt/ndc-london-2013
|
rx/rx/Program.cs
|
rx/rx/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace rx
{
class Program
{
static void Main(string[] args)
{
var subject = new Subject<string>();
using (subject.Subscribe(result => Console.WriteLine(result)))
{
var wc = new WebClient();
var task = wc.DownloadStringTaskAsync("http://www.google.com/robots.txt");
task.ContinueWith(t =>
{
subject.OnNext(t.Result);
subject.OnCompleted();
});
// Wait for the async call
Console.ReadLine();
}
}
}
public class Subject<T>
{
private readonly IList<IBobserver<T>> observers = new List<IBobserver<T>>();
public IDisposable Subscribe(IBobserver<T> observer)
{
observers.Add(observer);
return new Disposable(() => observers.Remove(observer));
}
public void OnNext(T result)
{
foreach (var observer in observers)
{
observer.OnNext(result);
}
}
public void OnCompleted()
{
foreach (var observer in observers)
{
observer.OnCompleted();
}
}
}
public interface IBobserver<T>
{
void OnNext(T result);
void OnCompleted();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace rx
{
class Program
{
static void Main(string[] args)
{
var subject = new Subject<string>();
using (subject.Subscribe(result => Console.WriteLine(result)))
{
var wc = new WebClient();
var task = wc.DownloadStringTaskAsync("http://www.google.com/robots.txt");
task.ContinueWith(t =>
{
subject.OnNext(t.Result);
subject.OnCompleted();
});
// Wait for the async call
Console.ReadLine();
}
}
}
public class Subject<T>
{
private readonly IList<Action<T>> observers = new List<Action<T>>();
public IDisposable Subscribe(Action<T> observer)
{
observers.Add(observer);
return new Disposable(() => observers.Remove(observer));
}
public void OnNext(T result)
{
foreach (var observer in observers)
{
observer(result);
}
}
public void OnCompleted()
{
foreach (var observer in observers)
{
observer.OnCompleted();
}
}
}
}
|
mit
|
C#
|
ff886964d6a0fdb9433ee21b122dc27e686ef09f
|
Make HtmlTemplateBundle.GetTemplateId internal.
|
damiensawyer/cassette,honestegg/cassette,damiensawyer/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,BluewireTechnologies/cassette,honestegg/cassette,andrewdavey/cassette,andrewdavey/cassette,honestegg/cassette,damiensawyer/cassette
|
src/Cassette/HtmlTemplates/HtmlTemplateBundle.cs
|
src/Cassette/HtmlTemplates/HtmlTemplateBundle.cs
|
#region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Cassette is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Web;
using Cassette.BundleProcessing;
namespace Cassette.HtmlTemplates
{
public class HtmlTemplateBundle : Bundle
{
public HtmlTemplateBundle(string applicationRelativePath, bool useDefaultBundleInitializer = true)
: base(applicationRelativePath, useDefaultBundleInitializer)
{
ContentType = "text/html";
Processor = new HtmlTemplatePipeline();
}
public IBundleProcessor<HtmlTemplateBundle> Processor { get; set; }
public IBundleHtmlRenderer<HtmlTemplateBundle> Renderer { get; set; }
internal override void Process(ICassetteApplication application)
{
Processor.Process(this, application);
}
internal override IHtmlString Render()
{
return Renderer.Render(this);
}
internal string GetTemplateId(IAsset asset)
{
var path = asset.SourceFile.FullPath
.Substring(Path.Length + 1)
.Replace(System.IO.Path.DirectorySeparatorChar, '-')
.Replace(System.IO.Path.AltDirectorySeparatorChar, '-');
return System.IO.Path.GetFileNameWithoutExtension(path);
}
}
}
|
#region License
/*
Copyright 2011 Andrew Davey
This file is part of Cassette.
Cassette is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Cassette is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Cassette. If not, see http://www.gnu.org/licenses/.
*/
#endregion
using System.Web;
using Cassette.BundleProcessing;
namespace Cassette.HtmlTemplates
{
public class HtmlTemplateBundle : Bundle
{
public HtmlTemplateBundle(string applicationRelativePath, bool useDefaultBundleInitializer = true)
: base(applicationRelativePath, useDefaultBundleInitializer)
{
ContentType = "text/html";
Processor = new HtmlTemplatePipeline();
}
public IBundleProcessor<HtmlTemplateBundle> Processor { get; set; }
public IBundleHtmlRenderer<HtmlTemplateBundle> Renderer { get; set; }
internal override void Process(ICassetteApplication application)
{
Processor.Process(this, application);
}
internal override IHtmlString Render()
{
return Renderer.Render(this);
}
public string GetTemplateId(IAsset asset)
{
var path = asset.SourceFile.FullPath
.Substring(Path.Length + 1)
.Replace(System.IO.Path.DirectorySeparatorChar, '-')
.Replace(System.IO.Path.AltDirectorySeparatorChar, '-');
return System.IO.Path.GetFileNameWithoutExtension(path);
}
}
}
|
mit
|
C#
|
801c3b24246c2c5eed8e30be58b2d21d838112e6
|
Disable release of ComObject on finalizer by default (using backward compatible behavior)
|
jwollen/SharpDX,waltdestler/SharpDX,Ixonos-USA/SharpDX,wyrover/SharpDX,VirusFree/SharpDX,VirusFree/SharpDX,Ixonos-USA/SharpDX,weltkante/SharpDX,shoelzer/SharpDX,RobyDX/SharpDX,weltkante/SharpDX,sharpdx/SharpDX,davidlee80/SharpDX-1,fmarrabal/SharpDX,VirusFree/SharpDX,Ixonos-USA/SharpDX,VirusFree/SharpDX,waltdestler/SharpDX,shoelzer/SharpDX,manu-silicon/SharpDX,PavelBrokhman/SharpDX,TigerKO/SharpDX,jwollen/SharpDX,PavelBrokhman/SharpDX,shoelzer/SharpDX,davidlee80/SharpDX-1,mrvux/SharpDX,shoelzer/SharpDX,dazerdude/SharpDX,davidlee80/SharpDX-1,TechPriest/SharpDX,dazerdude/SharpDX,Ixonos-USA/SharpDX,andrewst/SharpDX,weltkante/SharpDX,RobyDX/SharpDX,fmarrabal/SharpDX,TechPriest/SharpDX,andrewst/SharpDX,andrewst/SharpDX,davidlee80/SharpDX-1,waltdestler/SharpDX,TigerKO/SharpDX,mrvux/SharpDX,wyrover/SharpDX,sharpdx/SharpDX,fmarrabal/SharpDX,dazerdude/SharpDX,manu-silicon/SharpDX,TechPriest/SharpDX,fmarrabal/SharpDX,RobyDX/SharpDX,PavelBrokhman/SharpDX,jwollen/SharpDX,TigerKO/SharpDX,wyrover/SharpDX,manu-silicon/SharpDX,TechPriest/SharpDX,waltdestler/SharpDX,shoelzer/SharpDX,dazerdude/SharpDX,manu-silicon/SharpDX,PavelBrokhman/SharpDX,wyrover/SharpDX,weltkante/SharpDX,TigerKO/SharpDX,mrvux/SharpDX,sharpdx/SharpDX,jwollen/SharpDX,RobyDX/SharpDX
|
Source/SharpDX/Configuration.cs
|
Source/SharpDX/Configuration.cs
|
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using SharpDX.Diagnostics;
namespace SharpDX
{
/// <summary>
/// Global configuration.
/// </summary>
public class Configuration
{
/// <summary>
/// Enables or disables object tracking. Default is disabled (false).
/// </summary>
/// <remarks>
/// Object Tracking is used to track COM object lifecycle creation/dispose. When this option is enabled
/// objects can be tracked using <see cref="ObjectTracker"/>. Using Object tracking has a significant
/// impact on performance and should be used only while debugging.
/// </remarks>
public static bool EnableObjectTracking = false;
/// <summary>
/// Enables or disables release of ComObject on finalizer. Default is disabled (false).
/// </summary>
public static bool EnableReleaseOnFinalizer = false;
/// <summary>
/// Throws a <see cref="CompilationException"/> when a shader or effect compilation error occured. Default is enabled (true).
/// </summary>
public static bool ThrowOnShaderCompileError = true;
}
}
|
// Copyright (c) 2010-2011 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using SharpDX.Diagnostics;
namespace SharpDX
{
/// <summary>
/// Global configuration.
/// </summary>
public class Configuration
{
/// <summary>
/// Enables or disables object tracking. Default is disabled (false).
/// </summary>
/// <remarks>
/// Object Tracking is used to track COM object lifecycle creation/dispose. When this option is enabled
/// objects can be tracked using <see cref="ObjectTracker"/>. Using Object tracking has a significant
/// impact on performance and should be used only while debugging.
/// </remarks>
public static bool EnableObjectTracking = false;
/// <summary>
/// Enables or disables release of ComObject on finalizer. Default is enabled (true).
/// </summary>
public static bool EnableReleaseOnFinalizer = true;
/// <summary>
/// Throws a <see cref="CompilationException"/> when a shader or effect compilation error occured. Default is enabled (true).
/// </summary>
public static bool ThrowOnShaderCompileError = true;
}
}
|
mit
|
C#
|
f754ca50155f40c268b708445d498e6f6760c095
|
make test more resilient to potentially slow runners
|
ntent-ad/Metrics.NET,mnadel/Metrics.NET,etishor/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,Recognos/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET
|
Src/Metrics.Tests/ClockTests.cs
|
Src/Metrics.Tests/ClockTests.cs
|
using System.Threading;
using FluentAssertions;
using Metrics.Utils;
using Xunit;
namespace Metrics.Tests
{
public class ClockTests
{
[Fact]
public void ClockDefaultCanMeasureTime()
{
var startDefault = Clock.Default.Nanoseconds;
var startSystem = Clock.SystemDateTime.Nanoseconds;
Thread.Sleep(20);
var endDefault = Clock.Default.Nanoseconds;
var endSystem = Clock.SystemDateTime.Nanoseconds;
var elapsedDefault = TimeUnit.Nanoseconds.ToMilliseconds(endDefault - startDefault);
var elapsedSystem = TimeUnit.Nanoseconds.ToMilliseconds(endSystem - startSystem);
((double)elapsedDefault).Should().BeApproximately(elapsedSystem, 1);
}
}
}
|
using System.Threading;
using FluentAssertions;
using Metrics.Utils;
using Xunit;
namespace Metrics.Tests
{
public class ClockTests
{
[Fact]
public void ClockDefaultCanMeasureTime()
{
var start = Clock.Default.Nanoseconds;
Thread.Sleep(20);
var end = Clock.Default.Nanoseconds;
var elapsed = TimeUnit.Nanoseconds.ToMilliseconds(end - start);
elapsed.Should().BeInRange(18, 22);
}
[Fact]
public void ClockSystemCanMeasureTime()
{
var start = Clock.SystemDateTime.Nanoseconds;
Thread.Sleep(20);
var end = Clock.SystemDateTime.Nanoseconds;
var elapsed = TimeUnit.Nanoseconds.ToMilliseconds(end - start);
elapsed.Should().BeInRange(18, 22);
}
}
}
|
apache-2.0
|
C#
|
4c3cb15afeab172a89196f1b67a8c9094cb3f2bd
|
use volatile write to set the atomic long value instead of compare exchange. Performance seems a lot better.
|
MetaG8/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,Recognos/Metrics.NET,Recognos/Metrics.NET,mnadel/Metrics.NET,Liwoj/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,ntent-ad/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET
|
Src/Metrics/Utils/AtomicLong.cs
|
Src/Metrics/Utils/AtomicLong.cs
|
#if PADDED_ATOMIC_LONG
using System.Runtime.InteropServices;
#endif
using System.Threading;
namespace Metrics.Utils
{
/// <summary>
/// Atomic long.
/// TBD: implement optimizations behind LongAdder from
/// <a href="https://github.com/dropwizard/metrics/blob/master/metrics-core/src/main/java/com/codahale/metrics/LongAdder.java">metrics-core</a>
/// </summary>
#if PADDED_ATOMIC_LONG
[StructLayout(LayoutKind.Explicit, Size = 64 * 2)]
#endif
public struct AtomicLong
{
#if PADDED_ATOMIC_LONG
[FieldOffset(64)]
#endif
private long value;
public AtomicLong(long value)
{
this.value = value;
}
public long Value
{
get
{
return Thread.VolatileRead(ref this.value);
}
}
public void SetValue(long value)
{
Thread.VolatileWrite(ref this.value, value);
}
public long Add(long value)
{
return Interlocked.Add(ref this.value, value);
}
public long Increment()
{
return Interlocked.Increment(ref this.value);
}
public long Decrement()
{
return Interlocked.Decrement(ref this.value);
}
public long GetAndReset()
{
return GetAndSet(0L);
}
public long GetAndSet(long value)
{
return Interlocked.Exchange(ref this.value, value);
}
public bool CompareAndSet(long expected, long updated)
{
var value = Interlocked.CompareExchange(ref this.value, updated, expected);
return value == expected;
}
}
}
|
#if PADDED_ATOMIC_LONG
using System.Runtime.InteropServices;
#endif
using System.Threading;
namespace Metrics.Utils
{
/// <summary>
/// Atomic long.
/// TBD: implement optimizations behind LongAdder from
/// <a href="https://github.com/dropwizard/metrics/blob/master/metrics-core/src/main/java/com/codahale/metrics/LongAdder.java">metrics-core</a>
/// </summary>
#if PADDED_ATOMIC_LONG
[StructLayout(LayoutKind.Explicit, Size = 64 * 2)]
#endif
public struct AtomicLong
{
#if PADDED_ATOMIC_LONG
[FieldOffset(64)]
#endif
private long value;
public AtomicLong(long value)
{
this.value = value;
}
public long Value
{
get
{
return Interlocked.Read(ref this.value);
}
}
public void SetValue(long value)
{
GetAndSet(value);
}
public long Add(long value)
{
return Interlocked.Add(ref this.value, value);
}
public long Increment()
{
return Interlocked.Increment(ref this.value);
}
public long Decrement()
{
return Interlocked.Decrement(ref this.value);
}
public long GetAndReset()
{
return GetAndSet(0L);
}
public long GetAndSet(long value)
{
return Interlocked.Exchange(ref this.value, value);
}
public bool CompareAndSet(long expected, long updated)
{
var value = Interlocked.CompareExchange(ref this.value, updated, expected);
return value == expected;
}
}
}
|
apache-2.0
|
C#
|
62617537fa55def7e9d631e636c4e396c129665b
|
Change icon from scary bug to box-alt
|
KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,NikRimington/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,rasmuseeg/Umbraco-CMS,rasmuseeg/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS
|
src/Umbraco.Web/Trees/LogViewerTreeController.cs
|
src/Umbraco.Web/Trees/LogViewerTreeController.cs
|
using System.Net.Http.Formatting;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Trees
{
[UmbracoTreeAuthorize(Constants.Trees.LogViewer)]
[Tree(Constants.Applications.Settings, Constants.Trees.LogViewer, null, sortOrder: 9)]
[PluginController("UmbracoTrees")]
[CoreTree(TreeGroup = Constants.Trees.Groups.Settings)]
public class LogViewerTreeController : TreeController
{
protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
//We don't have any child nodes & only use the root node to load a custom UI
return new TreeNodeCollection();
}
protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
//We don't have any menu item options (such as create/delete/reload) & only use the root node to load a custom UI
return null;
}
/// <summary>
/// Helper method to create a root model for a tree
/// </summary>
/// <returns></returns>
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var root = base.CreateRootNode(queryStrings);
//this will load in a custom UI instead of the dashboard for the root node
root.RoutePath = string.Format("{0}/{1}/{2}", Constants.Applications.Settings, Constants.Trees.LogViewer, "overview");
root.Icon = "icon-box-alt";
root.HasChildren = false;
root.MenuUrl = null;
return root;
}
}
}
|
using System.Net.Http.Formatting;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Trees
{
[UmbracoTreeAuthorize(Constants.Trees.LogViewer)]
[Tree(Constants.Applications.Settings, Constants.Trees.LogViewer, null, sortOrder: 9)]
[PluginController("UmbracoTrees")]
[CoreTree(TreeGroup = Constants.Trees.Groups.Settings)]
public class LogViewerTreeController : TreeController
{
protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
//We don't have any child nodes & only use the root node to load a custom UI
return new TreeNodeCollection();
}
protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
//We don't have any menu item options (such as create/delete/reload) & only use the root node to load a custom UI
return null;
}
/// <summary>
/// Helper method to create a root model for a tree
/// </summary>
/// <returns></returns>
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var root = base.CreateRootNode(queryStrings);
//this will load in a custom UI instead of the dashboard for the root node
root.RoutePath = string.Format("{0}/{1}/{2}", Constants.Applications.Settings, Constants.Trees.LogViewer, "overview");
root.Icon = "icon-bug";
root.HasChildren = false;
root.MenuUrl = null;
return root;
}
}
}
|
mit
|
C#
|
91bb1a3a676b7f3b3a70777e571e9200f4ec681c
|
Refactor LengthRowStyleTests
|
JohanLarsson/Gu.Wpf.PropertyGrid
|
Gu.Wpf.PropertyGrid.UiTests/TypedRowTests/LengthRowStyleTests.cs
|
Gu.Wpf.PropertyGrid.UiTests/TypedRowTests/LengthRowStyleTests.cs
|
namespace Gu.Wpf.PropertyGrid.UiTests
{
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public class LengthRowStyleTests
{
private static readonly string WindowName = "LengthRowStyleWindow";
[Test]
public void CorrectValuesAndSuffixes()
{
using (var app = Application.AttachOrLaunch(Info.ExeFileName, WindowName))
{
var window = app.MainWindow;
var defaultRow = window.FindTextBoxRow("default");
Assert.AreEqual("\u00A0mm", defaultRow.Suffix().Text);
Assert.AreEqual("12.3456", defaultRow.Value().Text);
var cmRow = window.FindTextBoxRow("explicit cm");
Assert.AreEqual("\u00A0cm", cmRow.Suffix().Text);
Assert.AreEqual("1.23456", cmRow.Value().Text);
}
}
}
}
|
namespace Gu.Wpf.PropertyGrid.UiTests
{
using NUnit.Framework;
using TestStack.White.UIItems;
public class LengthRowStyleTests : WindowTests
{
protected override string WindowName { get; } = "LengthRowStyleWindow";
[Test]
public void CorrectValuesAndSuffixes()
{
var defaultRow = this.Window.FindRow("default");
Assert.AreEqual("\u00A0mm", defaultRow.Suffix().Text);
Assert.AreEqual("12.3456", defaultRow.Value<TextBox>().Text);
var cmRow = this.Window.FindRow("explicit cm");
Assert.AreEqual("\u00A0cm", cmRow.Suffix().Text);
Assert.AreEqual("1.23456", cmRow.Value<TextBox>().Text);
}
}
}
|
mit
|
C#
|
680dc50b8451fba4990331e186e1769a4da44c96
|
Remove type constraint for ChildrenOfType<T>
|
ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
|
osu.Framework/Testing/TestingExtensions.cs
|
osu.Framework/Testing/TestingExtensions.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 System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Testing
{
public static class TestingExtensions
{
/// <summary>
/// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes.
/// </summary>
public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable)
{
switch (drawable)
{
case T found:
yield return found;
break;
case CompositeDrawable composite:
foreach (var child in composite.InternalChildren)
{
foreach (var found in child.ChildrenOfType<T>())
yield return found;
}
break;
}
}
}
}
|
// 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.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Testing
{
public static class TestingExtensions
{
/// <summary>
/// Find all children recursively of a specific type. As this is expensive and dangerous, it should only be used for testing purposes.
/// </summary>
public static IEnumerable<T> ChildrenOfType<T>(this Drawable drawable) where T : Drawable
{
switch (drawable)
{
case T found:
yield return found;
break;
case CompositeDrawable composite:
foreach (var child in composite.InternalChildren)
{
foreach (var found in child.ChildrenOfType<T>())
yield return found;
}
break;
}
}
}
}
|
mit
|
C#
|
83429d2f221567198f19b1a618f785a260ad578f
|
make cinema incompatible with repel
|
ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu
|
osu.Game.Rulesets.Osu/Mods/OsuModCinema.cs
|
osu.Game.Rulesets.Osu/Mods/OsuModCinema.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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Replays;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModCinema : ModCinema<OsuHitObject>
{
public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModMagnetised), typeof(OsuModAutopilot), typeof(OsuModSpunOut), typeof(OsuModAlternate), typeof(OsuModSingleTap), typeof(OsuModRepel) }).ToArray();
public override ModReplayData CreateReplayData(IBeatmap beatmap, IReadOnlyList<Mod> mods)
=> new ModReplayData(new OsuAutoGenerator(beatmap, mods).Generate(), new ModCreatedUser { Username = "Autoplay" });
}
}
|
// 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Replays;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModCinema : ModCinema<OsuHitObject>
{
public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModMagnetised), typeof(OsuModAutopilot), typeof(OsuModSpunOut), typeof(OsuModAlternate), typeof(OsuModSingleTap) }).ToArray();
public override ModReplayData CreateReplayData(IBeatmap beatmap, IReadOnlyList<Mod> mods)
=> new ModReplayData(new OsuAutoGenerator(beatmap, mods).Generate(), new ModCreatedUser { Username = "Autoplay" });
}
}
|
mit
|
C#
|
c57e68e74e178a611bbd4c4bd4c4a30e10588a74
|
Remove obsoleted RuntimeInfo methods and properties.
|
ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework
|
osu.Framework/RuntimeInfo.cs
|
osu.Framework/RuntimeInfo.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 System;
using System.Runtime.InteropServices;
namespace osu.Framework
{
public static class RuntimeInfo
{
/// <summary>
/// Returns the absolute path of osu.Framework.dll.
/// </summary>
public static string GetFrameworkAssemblyPath() =>
System.Reflection.Assembly.GetAssembly(typeof(RuntimeInfo)).Location;
public static Platform OS { get; }
public static bool IsUnix => OS != Platform.Windows;
public static bool SupportsJIT => OS != Platform.iOS;
public static bool IsDesktop => OS == Platform.Linux || OS == Platform.MacOsx || OS == Platform.Windows;
public static bool IsMobile => OS == Platform.iOS || OS == Platform.Android;
static RuntimeInfo()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
OS = Platform.Windows;
if (osuTK.Configuration.RunningOnIOS)
OS = OS == 0 ? Platform.iOS : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.iOS)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (osuTK.Configuration.RunningOnAndroid)
OS = OS == 0 ? Platform.Android : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.Android)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (OS != Platform.iOS && RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
OS = OS == 0 ? Platform.MacOsx : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.MacOsx)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (OS != Platform.Android && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
OS = OS == 0 ? Platform.Linux : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.Linux)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (OS == 0)
throw new PlatformNotSupportedException("Operating system could not be detected correctly.");
}
public enum Platform
{
Windows = 1,
Linux = 2,
MacOsx = 3,
iOS = 4,
Android = 5
}
}
}
|
// 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;
using System.Runtime.InteropServices;
namespace osu.Framework
{
public static class RuntimeInfo
{
/// <summary>
/// Returns the absolute path of osu.Framework.dll.
/// </summary>
public static string GetFrameworkAssemblyPath() =>
System.Reflection.Assembly.GetAssembly(typeof(RuntimeInfo)).Location;
[Obsolete("Use Environment.Is64Bit*, IntPtr.Size, or RuntimeInformation.*Architecture instead.")] // can be removed 20200430
public static bool Is32Bit => IntPtr.Size == 4;
[Obsolete("Use Environment.Is64Bit*, IntPtr.Size, or RuntimeInformation.*Architecture instead.")] // can be removed 20200430
public static bool Is64Bit => IntPtr.Size == 8;
public static Platform OS { get; }
public static bool IsUnix => OS != Platform.Windows;
[Obsolete("Wine is no longer detected.")] // can be removed 20200430
public static bool IsWine => false;
public static bool SupportsJIT => OS != Platform.iOS;
public static bool IsDesktop => OS == Platform.Linux || OS == Platform.MacOsx || OS == Platform.Windows;
public static bool IsMobile => OS == Platform.iOS || OS == Platform.Android;
static RuntimeInfo()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
OS = Platform.Windows;
if (osuTK.Configuration.RunningOnIOS)
OS = OS == 0 ? Platform.iOS : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.iOS)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (osuTK.Configuration.RunningOnAndroid)
OS = OS == 0 ? Platform.Android : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.Android)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (OS != Platform.iOS && RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
OS = OS == 0 ? Platform.MacOsx : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.MacOsx)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (OS != Platform.Android && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
OS = OS == 0 ? Platform.Linux : throw new InvalidOperationException($"Tried to set OS Platform to {nameof(Platform.Linux)}, but is already {Enum.GetName(typeof(Platform), OS)}");
if (OS == 0)
throw new PlatformNotSupportedException("Operating system could not be detected correctly.");
}
public enum Platform
{
Windows = 1,
Linux = 2,
MacOsx = 3,
iOS = 4,
Android = 5
}
}
}
|
mit
|
C#
|
5e7cffd711ca6b1efa51cb2399d1d5b42ae9073f
|
handle images that fail to download
|
TomPeters/wallr,TomPeters/wallr,TomPeters/wallr
|
Wallr.Core/IImageStream.cs
|
Wallr.Core/IImageStream.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Serilog;
using Wallr.Interfaces;
using Wallr.Platform;
namespace Wallr.Core
{
public interface IImageStream
{
// Should be able to have duplicates in the stream, so need another unique id here
int Capacity { get; }
IReadOnlyList<ImageId> ImageIds { get; }
void PushImage(IImage image);
ImageId PopNextImageId { get; }
}
// Think about threading issues here
public class ImageStream : IImageStream
{
private readonly IPlatform _platform;
private readonly ILogger _logger;
public ImageStream(IPlatform platform, ILogger logger)
{
_platform = platform;
_logger = logger;
ImageIds = new List<ImageId>();
}
public int Capacity => 300;
public IReadOnlyList<ImageId> ImageIds { get; private set; }
public void PushImage(IImage image)
{
_logger.Information("Adding {ImageId} to stream. Images stream: {@ImageStream}", image.ImageId, ImageIds.Select(i => i.LocalImageId.Value));
try
{
_platform.SaveWallpaper(image, _logger);
ImageIds = ImageIds.Concat(new[] {image.ImageId}).ToList();
_logger.Information("Image {ImageId} added to stream. Images stream: {@ImageStream}", image.ImageId,
ImageIds.Select(i => i.LocalImageId.Value));
}
catch (Exception ex)
{
_logger.Error(ex, "Error occurred adding image {ImageId} to stream", image.ImageId);
}
}
public ImageId PopNextImageId
{
get
{
ImageId imageId = ImageIds.First();
ImageIds = ImageIds.Skip(1).ToList();
_logger.Information("Removing {ImageId} to stream. Images stream: {@ImageStream}", imageId, ImageIds.Select(i => i.LocalImageId.Value));
return imageId;
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Serilog;
using Wallr.Interfaces;
using Wallr.Platform;
namespace Wallr.Core
{
public interface IImageStream
{
// Should be able to have duplicates in the stream, so need another unique id here
int Capacity { get; }
IReadOnlyList<ImageId> ImageIds { get; }
void PushImage(IImage image);
ImageId PopNextImageId { get; }
}
// Think about threading issues here
public class ImageStream : IImageStream
{
private readonly IPlatform _platform;
private readonly ILogger _logger;
public ImageStream(IPlatform platform, ILogger logger)
{
_platform = platform;
_logger = logger;
ImageIds = new List<ImageId>();
}
public int Capacity => 300;
public IReadOnlyList<ImageId> ImageIds { get; private set; }
public void PushImage(IImage image)
{
_platform.SaveWallpaper(image, _logger);
ImageIds = ImageIds.Concat(new [] { image.ImageId }).ToList();
_logger.Information("Adding {ImageId} to stream. Images stream: {@ImageStream}", image.ImageId, ImageIds.Select(i => i.LocalImageId.Value));
}
public ImageId PopNextImageId
{
get
{
ImageId imageId = ImageIds.First();
ImageIds = ImageIds.Skip(1).ToList();
_logger.Information("Removing {ImageId} to stream. Images stream: {@ImageStream}", imageId, ImageIds.Select(i => i.LocalImageId.Value));
return imageId;
}
}
}
}
|
mit
|
C#
|
b4be5c5a180d4fa2a299fb7d965a463223c35b27
|
allow overriding dispose calls for Activator derived classes
|
pragmatrix/Konstruktor2
|
Konstruktor2/Activator.cs
|
Konstruktor2/Activator.cs
|
using System;
using System.Diagnostics;
using Konstruktor2.Detail;
namespace Konstruktor2
{
public class Activator<ParamT, ResultT> : IDisposable
where ResultT : class
{
readonly Func<ParamT, Owned<ResultT>> _generator;
Owned<ResultT> _generated_;
ParamT _param;
public ParamT Param
{
get
{
Debug.Assert(IsActive);
return _param;
}
}
public ResultT Instance_
{
get { return IsActive ? _generated_.Value : null; }
}
public bool IsActive
{
get { return _generated_ != null; }
}
public Activator(Func<ParamT, Owned<ResultT>> generator)
{
_generator = generator;
}
public virtual void Dispose()
{
if (IsActive)
deactivate();
}
public void activate(ParamT param)
{
if (IsActive)
deactivate();
if (_disablingRequests != 0)
return;
_param = param;
_generated_ = _generator(param);
activated(param);
Activated.raise(param);
ActivationChanged.raise();
}
public void deactivate()
{
if (_generated_ == null)
return;
Deactivating.raise();
deactivating();
_generated_.Dispose();
_generated_ = null;
_param = default(ParamT);
ActivationChanged.raise();
}
protected virtual void activated(ParamT param)
{
}
protected virtual void deactivating()
{
}
public event Action<ParamT> Activated;
public event Action Deactivating;
public event Action ActivationChanged;
int _disablingRequests;
public IDisposable beginDisable()
{
if (IsActive)
deactivate();
++_disablingRequests;
return new DisposeAction(() => --_disablingRequests);
}
}
}
|
using System;
using System.Diagnostics;
using Konstruktor2.Detail;
namespace Konstruktor2
{
public class Activator<ParamT, ResultT> : IDisposable
where ResultT : class
{
readonly Func<ParamT, Owned<ResultT>> _generator;
Owned<ResultT> _generated_;
ParamT _param;
public ParamT Param
{
get
{
Debug.Assert(IsActive);
return _param;
}
}
public ResultT Instance_
{
get { return IsActive ? _generated_.Value : null; }
}
public bool IsActive
{
get { return _generated_ != null; }
}
public Activator(Func<ParamT, Owned<ResultT>> generator)
{
_generator = generator;
}
public void Dispose()
{
if (IsActive)
deactivate();
}
public void activate(ParamT param)
{
if (IsActive)
deactivate();
if (_disablingRequests != 0)
return;
_param = param;
_generated_ = _generator(param);
activated(param);
Activated.raise(param);
ActivationChanged.raise();
}
public void deactivate()
{
if (_generated_ == null)
return;
Deactivating.raise();
deactivating();
_generated_.Dispose();
_generated_ = null;
_param = default(ParamT);
ActivationChanged.raise();
}
protected virtual void activated(ParamT param)
{
}
protected virtual void deactivating()
{
}
public event Action<ParamT> Activated;
public event Action Deactivating;
public event Action ActivationChanged;
int _disablingRequests;
public IDisposable beginDisable()
{
if (IsActive)
deactivate();
++_disablingRequests;
return new DisposeAction(() => --_disablingRequests);
}
}
}
|
bsd-3-clause
|
C#
|
4a937f69d861339432410dc83ae257f4e996bc5b
|
change ExceptionHelper
|
AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/Abstractions,AspectCore/AspectCore-Framework
|
src/AspectCore.Lite/Common/ExceptionHelper.cs
|
src/AspectCore.Lite/Common/ExceptionHelper.cs
|
using System;
namespace AspectCore.Lite.Common
{
internal static class ExceptionHelper
{
public static void ThrowArgumentNull<T>(T instance , string paramName)
{
if (instance == null)
{
throw new ArgumentNullException(paramName);
}
}
public static void ThrowArgumentNullOrEmpty(string instance , string paramName)
{
if (string.IsNullOrEmpty(instance))
{
throw new ArgumentNullException(paramName);
}
}
public static void ThrowArgument(Func<bool> predicate , string message)
{
if (predicate())
{
throw new ArgumentException(message);
}
}
public static void ThrowArgument(Func<bool> predicate , string message , string paramName)
{
if (predicate())
{
throw new ArgumentException(message , paramName);
}
}
public static void Throw<TException>(Func<bool> predicate , params object[] parameters) where TException : Exception
{
if (predicate())
{
throw (TException)Activator.CreateInstance(typeof(TException) , parameters);
}
}
}
}
|
using System;
namespace AspectCore.Lite.Common
{
public static class ExceptionHelper
{
public static void ThrowArgumentNull<T>(T instance , string paramName)
{
if (instance == null)
{
throw new ArgumentNullException(paramName);
}
}
public static void ThrowArgumentNullOrEmpty(string instance , string paramName)
{
if (string.IsNullOrEmpty(instance))
{
throw new ArgumentNullException(paramName);
}
}
public static void ThrowArgument(Func<bool> predicate , string message)
{
if (predicate())
{
throw new ArgumentException(message);
}
}
public static void ThrowArgument(Func<bool> predicate , string message , string paramName)
{
if (predicate())
{
throw new ArgumentException(message , paramName);
}
}
public static void Throw<TException>(Func<bool> predicate , params object[] parameters) where TException : Exception
{
if (predicate())
{
throw (TException)Activator.CreateInstance(typeof(TException) , parameters);
}
}
}
}
|
mit
|
C#
|
993314cb2046c81cb42845a4241ffc394b096187
|
Fix error if model type 'object' was requested
|
kamsar/Blade
|
Source/Blade/Razor/SitecoreRazorRenderingType.cs
|
Source/Blade/Razor/SitecoreRazorRenderingType.cs
|
using System;
using System.Linq;
using System.Reflection;
using Sitecore.Web.UI;
using System.Collections.Specialized;
using System.Web.UI;
using Blade.Views;
using System.Web.Compilation;
namespace Blade.Razor
{
/// <summary>
/// This is a Sitecore Rendering Type class that tells Sitecore how to handle a Razor view as a Rendering when it comes across one
/// </summary>
/// <remarks>
/// Must be registered in the renderingControls section of the Sitecore configuration. A template that derives from an existing Rendering template
/// must also be created in Sitecore with a name matching the entry in the renderingControls config.
/// </remarks>
public class SitecoreRazorRenderingType : RenderingType
{
public override Control GetControl(NameValueCollection parameters, bool assert)
{
var viewPath = parameters["viewPath"];
var control = GetControl(viewPath);
Sitecore.Diagnostics.Assert.IsNotNull(control, "Resolved Razor control was null");
((WebControl)control).Parameters = parameters["properties"];
return control;
}
/// <summary>
/// Gets a Control that will render a given Razor view path
/// </summary>
public static Control GetControl(string viewPath)
{
Sitecore.Diagnostics.Assert.IsNotNullOrEmpty(viewPath, "ViewPath cannot be empty. The Rendering item in Sitecore needs to have a view path set.");
Type viewType = BuildManager.GetCompiledType(viewPath);
PropertyInfo typedModelProperty = viewType.GetProperties().FirstOrDefault(x => x.PropertyType != typeof (object) && x.Name == "Model");
Type viewModelType = typedModelProperty != null ? typedModelProperty.PropertyType : typeof (object);
var renderingType = typeof(RazorViewShim<>).MakeGenericType(viewModelType);
var shim = (IRazorViewShim)Activator.CreateInstance(renderingType);
shim.ViewPath = viewPath;
return shim as Control;
}
}
}
|
using System;
using System.Linq;
using Sitecore.Web.UI;
using System.Collections.Specialized;
using System.Web.UI;
using Blade.Views;
using System.Web.Compilation;
namespace Blade.Razor
{
/// <summary>
/// This is a Sitecore Rendering Type class that tells Sitecore how to handle a Razor view as a Rendering when it comes across one
/// </summary>
/// <remarks>
/// Must be registered in the renderingControls section of the Sitecore configuration. A template that derives from an existing Rendering template
/// must also be created in Sitecore with a name matching the entry in the renderingControls config.
/// </remarks>
public class SitecoreRazorRenderingType : RenderingType
{
public override Control GetControl(NameValueCollection parameters, bool assert)
{
var viewPath = parameters["viewPath"];
var control = GetControl(viewPath);
Sitecore.Diagnostics.Assert.IsNotNull(control, "Resolved Razor control was null");
((WebControl)control).Parameters = parameters["properties"];
return control;
}
/// <summary>
/// Gets a Control that will render a given Razor view path
/// </summary>
public static Control GetControl(string viewPath)
{
Sitecore.Diagnostics.Assert.IsNotNullOrEmpty(viewPath, "ViewPath cannot be empty. The Rendering item in Sitecore needs to have a view path set.");
Type viewType = BuildManager.GetCompiledType(viewPath);
Type viewModelType = viewType.GetProperties().First(x => x.PropertyType != typeof (object) && x.Name == "Model").PropertyType;
var renderingType = typeof(RazorViewShim<>).MakeGenericType(viewModelType);
var shim = (IRazorViewShim)Activator.CreateInstance(renderingType);
shim.ViewPath = viewPath;
return shim as Control;
}
}
}
|
mit
|
C#
|
3820e9d10ea257d400bd8f260b6387ede1e24dc2
|
Add WPA3 values
|
emoacht/ManagedNativeWifi
|
Source/ManagedNativeWifi/AuthenticationMethod.cs
|
Source/ManagedNativeWifi/AuthenticationMethod.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManagedNativeWifi
{
/// <summary>
/// Authentication method to be used to connect to wireless LAN
/// </summary>
/// <remarks>
/// Equivalent to authentication element in profile XML:
/// https://docs.microsoft.com/en-us/windows/win32/nativewifi/wlan-profileschema-authentication-authencryption-element
/// WPA3 values are found in:
/// https://docs.microsoft.com/en-us/uwp/api/windows.networking.connectivity.networkauthenticationtype
/// </remarks>
public enum AuthenticationMethod
{
/// <summary>
/// None (invalid value)
/// </summary>
None = 0,
/// <summary>
/// Open 802.11 authentication
/// </summary>
Open,
/// <summary>
/// Shared 802.11 authentication
/// </summary>
Shared,
/// <summary>
/// WPA-Enterprise 802.11 authentication
/// </summary>
/// <remarks>WPA in profile XML</remarks>
WPA_Enterprise,
/// <summary>
/// WPA-Personal 802.11 authentication
/// </summary>
/// <remarks>WPAPSK in profile XML</remarks>
WPA_Personal,
/// <summary>
/// WPA2-Enterprise 802.11 authentication
/// </summary>
/// <remarks>WPA2 in profile XML</remarks>
WPA2_Enterprise,
/// <summary>
/// WPA2-Personal 802.11 authentication
/// </summary>
/// <remarks>WPA2PSK in profile XML</remarks>
WPA2_Personal,
/// <summary>
/// WPA3-Enterprise 802.11 authentication
/// </summary>
/// <remarks>WPA3 in profile XML</remarks>
WPA3_Enterprise,
/// <summary>
/// WPA3-Personal 802.11 authentication
/// </summary>
/// <remarks>WPA3SAE in profile XML</remarks>
WPA3_Personal
}
internal static class AuthenticationMethodConverter
{
public static bool TryParse(string source, out AuthenticationMethod authentication)
{
switch (source)
{
case "open":
authentication = AuthenticationMethod.Open;
return true;
case "shared":
authentication = AuthenticationMethod.Shared;
return true;
case "WPA":
authentication = AuthenticationMethod.WPA_Enterprise;
return true;
case "WPAPSK":
authentication = AuthenticationMethod.WPA_Personal;
return true;
case "WPA2":
authentication = AuthenticationMethod.WPA2_Enterprise;
return true;
case "WPA2PSK":
authentication = AuthenticationMethod.WPA2_Personal;
return true;
case "WPA3":
authentication = AuthenticationMethod.WPA3_Enterprise;
return true;
case "WPA3SAE":
authentication = AuthenticationMethod.WPA3_Personal;
return true;
}
authentication = default;
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManagedNativeWifi
{
/// <summary>
/// Authentication method to be used to connect to wireless LAN
/// </summary>
/// <remarks>
/// Equivalent to authentication element in profile XML:
/// https://docs.microsoft.com/en-us/windows/win32/nativewifi/wlan-profileschema-authentication-authencryption-element
/// </remarks>
public enum AuthenticationMethod
{
/// <summary>
/// None (invalid value)
/// </summary>
None = 0,
/// <summary>
/// Open 802.11 authentication
/// </summary>
Open,
/// <summary>
/// Shared 802.11 authentication
/// </summary>
Shared,
/// <summary>
/// WPA-Enterprise 802.11 authentication
/// </summary>
/// <remarks>WPA in profile XML</remarks>
WPA_Enterprise,
/// <summary>
/// WPA-Personal 802.11 authentication
/// </summary>
/// <remarks>WPAPSK in profile XML</remarks>
WPA_Personal,
/// <summary>
/// WPA2-Enterprise 802.11 authentication
/// </summary>
/// <remarks>WPA2 in profile XML</remarks>
WPA2_Enterprise,
/// <summary>
/// WPA2-Personal 802.11 authentication
/// </summary>
/// <remarks>WPA2PSK in profile XML</remarks>
WPA2_Personal
}
internal static class AuthenticationMethodConverter
{
public static bool TryParse(string source, out AuthenticationMethod authentication)
{
switch (source)
{
case "open":
authentication = AuthenticationMethod.Open;
return true;
case "shared":
authentication = AuthenticationMethod.Shared;
return true;
case "WPA":
authentication = AuthenticationMethod.WPA_Enterprise;
return true;
case "WPAPSK":
authentication = AuthenticationMethod.WPA_Personal;
return true;
case "WPA2":
authentication = AuthenticationMethod.WPA2_Enterprise;
return true;
case "WPA2PSK":
authentication = AuthenticationMethod.WPA2_Personal;
return true;
}
authentication = default;
return false;
}
}
}
|
mit
|
C#
|
9b6f7b019a18e31dabc5a0e62eafa1235dccb0b9
|
Update ContextState.cs
|
omidnasri/Orchard,jersiovic/Orchard,jtkech/Orchard,omidnasri/Orchard,johnnyqian/Orchard,Fogolan/OrchardForWork,IDeliverable/Orchard,rtpHarry/Orchard,AdvantageCS/Orchard,AdvantageCS/Orchard,hannan-azam/Orchard,Lombiq/Orchard,LaserSrl/Orchard,mvarblow/Orchard,Fogolan/OrchardForWork,OrchardCMS/Orchard,Dolphinsimon/Orchard,jersiovic/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,rtpHarry/Orchard,sfmskywalker/Orchard,ehe888/Orchard,rtpHarry/Orchard,jagraz/Orchard,Praggie/Orchard,IDeliverable/Orchard,Dolphinsimon/Orchard,Praggie/Orchard,fassetar/Orchard,SzymonSel/Orchard,jersiovic/Orchard,IDeliverable/Orchard,jagraz/Orchard,Dolphinsimon/Orchard,armanforghani/Orchard,fassetar/Orchard,jagraz/Orchard,jimasp/Orchard,ehe888/Orchard,Lombiq/Orchard,rtpHarry/Orchard,jtkech/Orchard,geertdoornbos/Orchard,omidnasri/Orchard,ehe888/Orchard,SzymonSel/Orchard,jimasp/Orchard,hbulzy/Orchard,Lombiq/Orchard,jimasp/Orchard,aaronamm/Orchard,armanforghani/Orchard,gcsuk/Orchard,jagraz/Orchard,aaronamm/Orchard,hannan-azam/Orchard,fassetar/Orchard,omidnasri/Orchard,phillipsj/Orchard,yersans/Orchard,Praggie/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard,geertdoornbos/Orchard,phillipsj/Orchard,Serlead/Orchard,jtkech/Orchard,Serlead/Orchard,yersans/Orchard,ehe888/Orchard,mvarblow/Orchard,SzymonSel/Orchard,hbulzy/Orchard,phillipsj/Orchard,AdvantageCS/Orchard,Lombiq/Orchard,johnnyqian/Orchard,LaserSrl/Orchard,OrchardCMS/Orchard,fassetar/Orchard,armanforghani/Orchard,LaserSrl/Orchard,Fogolan/OrchardForWork,Dolphinsimon/Orchard,jersiovic/Orchard,LaserSrl/Orchard,yersans/Orchard,sfmskywalker/Orchard,jagraz/Orchard,mvarblow/Orchard,jimasp/Orchard,geertdoornbos/Orchard,IDeliverable/Orchard,mvarblow/Orchard,Dolphinsimon/Orchard,OrchardCMS/Orchard,sfmskywalker/Orchard,OrchardCMS/Orchard,yersans/Orchard,phillipsj/Orchard,johnnyqian/Orchard,Praggie/Orchard,fassetar/Orchard,armanforghani/Orchard,phillipsj/Orchard,yersans/Orchard,Fogolan/OrchardForWork,omidnasri/Orchard,aaronamm/Orchard,omidnasri/Orchard,johnnyqian/Orchard,hannan-azam/Orchard,armanforghani/Orchard,jtkech/Orchard,omidnasri/Orchard,SzymonSel/Orchard,rtpHarry/Orchard,aaronamm/Orchard,gcsuk/Orchard,LaserSrl/Orchard,jimasp/Orchard,sfmskywalker/Orchard,hannan-azam/Orchard,Serlead/Orchard,geertdoornbos/Orchard,hbulzy/Orchard,Serlead/Orchard,Serlead/Orchard,sfmskywalker/Orchard,hannan-azam/Orchard,OrchardCMS/Orchard,gcsuk/Orchard,bedegaming-aleksej/Orchard,hbulzy/Orchard,sfmskywalker/Orchard,ehe888/Orchard,hbulzy/Orchard,Praggie/Orchard,aaronamm/Orchard,bedegaming-aleksej/Orchard,gcsuk/Orchard,johnnyqian/Orchard,gcsuk/Orchard,bedegaming-aleksej/Orchard,bedegaming-aleksej/Orchard,jtkech/Orchard,SzymonSel/Orchard,AdvantageCS/Orchard,Fogolan/OrchardForWork,jersiovic/Orchard,bedegaming-aleksej/Orchard,Lombiq/Orchard,mvarblow/Orchard,omidnasri/Orchard,IDeliverable/Orchard,geertdoornbos/Orchard
|
src/Orchard/Environment/State/ContextState.cs
|
src/Orchard/Environment/State/ContextState.cs
|
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Web;
using Orchard.Mvc.Extensions;
namespace Orchard.Environment.State {
/// <summary>
/// Holds some state for the current HttpContext or Logical Context
/// </summary>
/// <typeparam name="T">The type of data to store</typeparam>
public class ContextState<T> where T : class {
private readonly string _name;
private readonly Func<T> _defaultValue;
public ContextState(string name) {
_name = name;
}
public ContextState(string name, Func<T> defaultValue) {
_name = name;
_defaultValue = defaultValue;
}
public T GetState() {
if (HttpContext.Current.IsBackgroundHttpContext()) {
var handle = CallContext.LogicalGetData(_name) as ObjectHandle;
var data = handle != null ? handle.Unwrap() : null;
if (data == null) {
if (_defaultValue != null) {
CallContext.LogicalSetData(_name, new ObjectHandle(data = _defaultValue()));
return data as T;
}
}
return data as T;
}
if (HttpContext.Current.Items[_name] == null) {
HttpContext.Current.Items[_name] = _defaultValue == null ? null : _defaultValue();
}
return HttpContext.Current.Items[_name] as T;
}
public void SetState(T state) {
if (HttpContext.Current.IsBackgroundHttpContext()) {
CallContext.LogicalSetData(_name, new ObjectHandle(state));
}
else {
HttpContext.Current.Items[_name] = state;
}
}
}
}
|
using System;
using System.Runtime.Remoting.Messaging;
using System.Web;
using Orchard.Mvc;
namespace Orchard.Environment.State {
/// <summary>
/// Holds some state for the current HttpContext or thread
/// </summary>
/// <typeparam name="T">The type of data to store</typeparam>
public class ContextState<T> where T : class {
private readonly string _name;
private readonly Func<T> _defaultValue;
public ContextState(string name) {
_name = name;
}
public ContextState(string name, Func<T> defaultValue) {
_name = name;
_defaultValue = defaultValue;
}
public T GetState() {
if (!HttpContextIsValid()) {
var data = CallContext.GetData(_name);
if (data == null) {
if (_defaultValue != null) {
CallContext.SetData(_name, data = _defaultValue());
return data as T;
}
}
return data as T;
}
if (HttpContext.Current.Items[_name] == null) {
HttpContext.Current.Items[_name] = _defaultValue == null ? null : _defaultValue();
}
return HttpContext.Current.Items[_name] as T;
}
public void SetState(T state) {
if (!HttpContextIsValid()) {
CallContext.SetData(_name, state);
}
else {
HttpContext.Current.Items[_name] = state;
}
}
private bool HttpContextIsValid() {
return HttpContext.Current != null && !HttpContext.Current.Items.Contains(MvcModule.IsBackgroundHttpContextKey);
}
}
}
|
bsd-3-clause
|
C#
|
00a5ecb10c338fd877d03071323e837012a9f3fe
|
Add <exception> tags to CreateReader.
|
Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver
|
src/AsmResolver/IO/IBinaryStreamReaderFactory.cs
|
src/AsmResolver/IO/IBinaryStreamReaderFactory.cs
|
using System;
using System.IO;
namespace AsmResolver.IO
{
/// <summary>
/// Provides members for creating new binary streams.
/// </summary>
public interface IBinaryStreamReaderFactory : IDisposable
{
/// <summary>
/// Gets the maximum length a single binary stream reader produced by this factory can have.
/// </summary>
uint MaxLength
{
get;
}
/// <summary>
/// Creates a new binary reader at the provided address.
/// </summary>
/// <param name="address">The raw address to start reading from.</param>
/// <param name="rva">The virtual address (relative to the image base) that is associated to the raw address.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The created reader.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs if <paramref name="address"/> is not a valid address.</exception>
/// <exception cref="EndOfStreamException">Occurs if <paramref name="length"/> is too long.</exception>
BinaryStreamReader CreateReader(ulong address, uint rva, uint length);
}
public static partial class IOExtensions
{
/// <summary>
/// Creates a binary reader for the entire address space.
/// </summary>
/// <param name="factory">The factory to use.</param>
/// <returns>The constructed reader.</returns>
public static BinaryStreamReader CreateReader(this IBinaryStreamReaderFactory factory)
=> factory.CreateReader(0, 0, factory.MaxLength);
}
}
|
using System;
namespace AsmResolver.IO
{
/// <summary>
/// Provides members for creating new binary streams.
/// </summary>
public interface IBinaryStreamReaderFactory : IDisposable
{
/// <summary>
/// Gets the maximum length a single binary stream reader produced by this factory can have.
/// </summary>
uint MaxLength
{
get;
}
/// <summary>
/// Creates a new binary reader at the provided address.
/// </summary>
/// <param name="address">The raw address to start reading from.</param>
/// <param name="rva">The virtual address (relative to the image base) that is associated to the raw address.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The created reader.</returns>
BinaryStreamReader CreateReader(ulong address, uint rva, uint length);
}
public static partial class IOExtensions
{
/// <summary>
/// Creates a binary reader for the entire address space.
/// </summary>
/// <param name="factory">The factory to use.</param>
/// <returns>The constructed reader.</returns>
public static BinaryStreamReader CreateReader(this IBinaryStreamReaderFactory factory)
=> factory.CreateReader(0, 0, factory.MaxLength);
}
}
|
mit
|
C#
|
4e9ea01784d4df1e339ad7a14c1bc2a657baeacd
|
Allow replace separator in crypt helper
|
ifilipenko/Building-Blocks,ifilipenko/Building-Blocks,ifilipenko/Building-Blocks
|
src/BuildingBlocks.CopyManagement/CryptHelper.cs
|
src/BuildingBlocks.CopyManagement/CryptHelper.cs
|
using System.Security.Cryptography;
using System.Text;
namespace BuildingBlocks.CopyManagement
{
public static class CryptHelper
{
public static string ToFingerPrintMd5Hash(this string value, char? separator = '-')
{
var cryptoProvider = new MD5CryptoServiceProvider();
var encoding = new ASCIIEncoding();
var encodedBytes = encoding.GetBytes(value);
var hashBytes = cryptoProvider.ComputeHash(encodedBytes);
var hexString = BytesToHexString(hashBytes, separator);
return hexString;
}
private static string BytesToHexString(byte[] bytes, char? separator)
{
var stringBuilder = new StringBuilder();
for (var i = 0; i < bytes.Length; i++)
{
var b = bytes[i];
var n = (int)b;
var n1 = n & 15;
var n2 = (n >> 4) & 15;
if (n2 > 9)
{
stringBuilder.Append((char) n2 - 10 + 'A');
}
else
{
stringBuilder.Append(n2);
}
if (n1 > 9)
{
stringBuilder.Append((char) n1 - 10 + 'A');
}
else
{
stringBuilder.Append(n1);
}
if (separator.HasValue && ((i + 1) != bytes.Length && (i + 1) % 2 == 0))
{
stringBuilder.Append(separator.Value);
}
}
return stringBuilder.ToString();
}
}
}
|
using System.Security.Cryptography;
using System.Text;
namespace BuildingBlocks.CopyManagement
{
public static class CryptHelper
{
public static string ToFingerPrintMd5Hash(this string value)
{
var cryptoProvider = new MD5CryptoServiceProvider();
var encoding = new ASCIIEncoding();
var encodedBytes = encoding.GetBytes(value);
var hashBytes = cryptoProvider.ComputeHash(encodedBytes);
var hexString = BytesToHexString(hashBytes);
return hexString;
}
private static string BytesToHexString(byte[] bytes)
{
var result = string.Empty;
for (var i = 0; i < bytes.Length; i++)
{
var b = bytes[i];
var n = (int)b;
var n1 = n & 15;
var n2 = (n >> 4) & 15;
if (n2 > 9)
{
result += ((char)(n2 - 10 + 'A')).ToString();
}
else
{
result += n2.ToString();
}
if (n1 > 9)
{
result += ((char)(n1 - 10 + 'A')).ToString();
}
else
{
result += n1.ToString();
}
if ((i + 1) != bytes.Length && (i + 1) % 2 == 0)
{
result += "-";
}
}
return result;
}
}
}
|
apache-2.0
|
C#
|
05df51d8e2e78ebeaad38e3f41c10730195fc3cb
|
Add Options setup registration in DI container
|
mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype
|
src/Glimpse.Agent.Web/GlimpseAgentWebServices.cs
|
src/Glimpse.Agent.Web/GlimpseAgentWebServices.cs
|
using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(null);
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Options
//
yield return describe.Transient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
yield return describe.Singleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
}
}
}
|
using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web.Options;
namespace Glimpse
{
public class GlimpseAgentWebServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Options
//
yield return describe.Singleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
}
}
}
|
mit
|
C#
|
a663b33df7b3734171514757e55a0841b3836a37
|
Update StringExtensions.cs
|
CaptiveAire/Seq.App.YouTrack
|
src/Seq.App.YouTrack/Helpers/StringExtensions.cs
|
src/Seq.App.YouTrack/Helpers/StringExtensions.cs
|
// Copyright 2014-2019 CaptiveAire Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Seq.App.YouTrack.Helpers
{
public static class StringExtensions
{
public static bool IsSet(this string str) => !string.IsNullOrWhiteSpace(str);
public static bool IsNotSet(this string str) => string.IsNullOrWhiteSpace(str);
public static async Task<Stream> ToStream(this string contents)
{
if (contents == null)
throw new ArgumentNullException(nameof(contents));
var ms = new MemoryStream();
using (var streamWriter = new StreamWriter(ms, Encoding.UTF8, 4096, leaveOpen: true))
{
await streamWriter.WriteAsync(contents);
await streamWriter.FlushAsync();
}
ms.Position = 0;
return ms;
}
}
}
|
// Seq.App.YouTrack - Copyright (c) 2019 CaptiveAire
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Seq.App.YouTrack.Helpers
{
public static class StringExtensions
{
public static bool IsSet(this string str) => !string.IsNullOrWhiteSpace(str);
public static bool IsNotSet(this string str) => string.IsNullOrWhiteSpace(str);
public static async Task<Stream> ToStream(this string contents)
{
if (contents == null)
throw new ArgumentNullException(nameof(contents));
var ms = new MemoryStream();
using (var streamWriter = new StreamWriter(ms, Encoding.UTF8, 4096, leaveOpen: true))
{
await streamWriter.WriteAsync(contents);
await streamWriter.FlushAsync();
}
ms.Position = 0;
return ms;
}
}
}
|
apache-2.0
|
C#
|
c04f14f80745bb8a3766487d186deb125aae98e1
|
clean up using user agent service constructor
|
wangkanai/Detection
|
src/Services/Defaults/DefaultUserAgentService.cs
|
src/Services/Defaults/DefaultUserAgentService.cs
|
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Wangkanai.Detection.Models;
namespace Wangkanai.Detection.Services
{
/// <summary>
/// Provides the APIs for query client access device.
/// </summary>
public class DefaultUserAgentService : IUserAgentService
{
/// <summary>
/// Get HttpContext of the application service
/// </summary>
public HttpContext Context { get; }
/// <summary>
/// Get user agnet of the request client
/// </summary>
public UserAgent UserAgent { get; }
public DefaultUserAgentService(IServiceProvider services)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
var context = services.GetRequiredService<IHttpContextAccessor>().HttpContext;
if (context is null)
throw new ArgumentNullException(nameof(context));
Context = context;
UserAgent = CreateUserAgentFromContext(Context);
}
private static UserAgent CreateUserAgentFromContext(HttpContext context)
=> new UserAgent(context.Request.Headers["User-Agent"].FirstOrDefault());
}
}
|
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Wangkanai.Detection.Models;
namespace Wangkanai.Detection.Services
{
/// <summary>
/// Provides the APIs for query client access device.
/// </summary>
public class DefaultUserAgentService : IUserAgentService
{
/// <summary>
/// Get HttpContext of the application service
/// </summary>
public HttpContext Context { get; }
/// <summary>
/// Get user agnet of the request client
/// </summary>
public UserAgent UserAgent { get; }
public DefaultUserAgentService(IServiceProvider services)
{
if (services is null)
throw new ArgumentNullException(nameof(services));
var context = services.GetRequiredService<IHttpContextAccessor>().HttpContext;
if (context is null)
throw new ArgumentNullException(nameof(context));
Context = context;
UserAgent = CreateUserAgentFromContext(Context);
}
[Obsolete]
public DefaultUserAgentService(HttpContext context)
{
if (context is null)
throw new ArgumentNullException(nameof(context));
Context = context;
UserAgent = CreateUserAgentFromContext(Context);
}
private static UserAgent CreateUserAgentFromContext(HttpContext context)
=> new UserAgent(context.Request.Headers["User-Agent"].FirstOrDefault());
}
}
|
apache-2.0
|
C#
|
5050905d6a6c065d3c40291974639b5fe93a2745
|
Add missing documentation
|
seiggy/AsterNET.ARI,seiggy/AsterNET.ARI,skrusty/AsterNET.ARI,skrusty/AsterNET.ARI,seiggy/AsterNET.ARI,skrusty/AsterNET.ARI
|
AsterNET.ARI/StasisEndpoint.cs
|
AsterNET.ARI/StasisEndpoint.cs
|
namespace AsterNET.ARI
{
public class StasisEndpoint
{
/// <summary>
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="ssl">Use SSL/TLS for ARI connection</param>
public StasisEndpoint(string host, int port, string username, string password, bool ssl = false)
{
Host = host;
Port = port;
Username = username;
Password = password;
Ssl = ssl;
}
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool Ssl { get; set; }
public string AriEndPoint
{
get {
if (Ssl) {
return string.Format("{0}://{1}:{2}/ari", "https", Host, Port);
} else {
return string.Format("{0}://{1}:{2}/ari", "http", Host, Port);
}
}
}
}
}
|
namespace AsterNET.ARI
{
public class StasisEndpoint
{
/// <summary>
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public StasisEndpoint(string host, int port, string username, string password, bool ssl = false)
{
Host = host;
Port = port;
Username = username;
Password = password;
Ssl = ssl;
}
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool Ssl { get; set; }
public string AriEndPoint
{
get {
if (Ssl) {
return string.Format("{0}://{1}:{2}/ari", "https", Host, Port);
} else {
return string.Format("{0}://{1}:{2}/ari", "http", Host, Port);
}
}
}
}
}
|
mit
|
C#
|
85ba9e230e0d82eb9755827f5e6cce34edf95422
|
Make public
|
vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
|
CSGL.Vulkan/VulkanException.cs
|
CSGL.Vulkan/VulkanException.cs
|
using System;
namespace CSGL.Vulkan {
public class VulkanException : Exception {
public VkResult Result { get; private set; }
public VulkanException(string message) : base(message) { }
public VulkanException(VkResult result, string message) : base(message) {
Result = result;
}
}
}
|
using System;
namespace CSGL.Vulkan {
class VulkanException : Exception {
public VkResult Result { get; private set; }
public VulkanException(string message) : base(message) { }
public VulkanException(VkResult result, string message) : base(message) {
Result = result;
}
}
}
|
mit
|
C#
|
24888165919b6df7899a9cfa05abd82399edfe7e
|
Fix typo in Model-Repositories Service Register
|
Jaskaranbir/InstaPost,Jaskaranbir/InstaPost,Jaskaranbir/InstaPost,Jaskaranbir/InstaPost
|
Api/DIServiceRegister/ModelRepositories.cs
|
Api/DIServiceRegister/ModelRepositories.cs
|
using Api.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Api.DIServiceRegister {
public class ModelRepositories
{
public static void Register(IServiceCollection services) {
services.AddScoped<IAdministratorsRepository, AdministratorsRepository>();
services.AddScoped<IBookmarksRepository, BookmarksRepository>();
services.AddScoped<ICommentsRepository, CommentsRepository>();
services.AddScoped<IFollowersRepository, FollowersRepository>();
services.AddScoped<ILikesRepository, LikesRepository>();
services.AddScoped<ILocationsRepository, LocationsRepository>();
services.AddScoped<IPostsRepository, PostsRepository>();
services.AddScoped<IReportsRepository, ReportsRepository>();
services.AddScoped<ITagsRepository, TagsRepository>();
}
}
}
|
using Api.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Api.DIServiceRegister {
public class Repositories
{
public static void Register(IServiceCollection services) {
services.AddSingleton<IAdministratorsRepository, AdministratorsRepository>();
services.AddSingleton<IBookmarksRepository, BookmarksRepository>();
services.AddSingleton<ICommentsRepository, CommentsRepository>();
services.AddSingleton<IFollowersRepository, FollowersRepository>();
services.AddSingleton<ILikesRepository, LikesRepository>();
services.AddSingleton<ILocationsRepository, LocationsRepository>();
services.AddSingleton<IPostsRepository, IPostsRepository>();
services.AddSingleton<IReportsRepository, ReportsRepository>();
services.AddSingleton<ITagsRepository, TagsRepository>();
}
}
}
|
apache-2.0
|
C#
|
0bfe43c202d19e73a3f183b64e5a0f3c6e59d45e
|
Prepare for CodeMatcher
|
pardeike/Harmony
|
Harmony/CodeInstruction.cs
|
Harmony/CodeInstruction.cs
|
using Harmony.ILCopying;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
namespace Harmony
{
public class CodeInstruction
{
public OpCode opcode;
public object operand;
public List<Label> labels = new List<Label>();
public List<ExceptionBlock> blocks = new List<ExceptionBlock>();
public CodeInstruction(OpCode opcode, object operand = null)
{
this.opcode = opcode;
this.operand = operand;
}
// full copy (be careful with duplicate labels and exception blocks!)
// for normal cases, use Clone()
//
public CodeInstruction(CodeInstruction instruction)
{
opcode = instruction.opcode;
operand = instruction.operand;
labels = instruction.labels.ToArray().ToList();
blocks = instruction.blocks.ToArray().ToList();
}
// copy only opcode and operand
//
public CodeInstruction Clone()
{
var instruction = new CodeInstruction(this);
instruction.labels = new List<Label>();
instruction.blocks = new List<ExceptionBlock>();
return instruction;
}
// copy only operand, use new opcode
//
public CodeInstruction Clone(OpCode opcode)
{
var instruction = Clone();
instruction.opcode = opcode;
return instruction;
}
// copy only opcode, use new operand
//
public CodeInstruction Clone(object operand)
{
var instruction = Clone();
instruction.operand = operand;
return instruction;
}
public override string ToString()
{
var list = new List<string>();
foreach (var label in labels)
list.Add("Label" + label.GetHashCode());
foreach (var block in blocks)
list.Add("EX_" + block.blockType.ToString().Replace("Block", ""));
var extras = list.Count > 0 ? " [" + string.Join(", ", list.ToArray()) + "]" : "";
var operandStr = Emitter.FormatArgument(operand);
if (operandStr != "") operandStr = " " + operandStr;
return opcode + operandStr + extras;
}
}
}
|
using Harmony.ILCopying;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
namespace Harmony
{
public class CodeInstruction
{
public OpCode opcode;
public object operand;
public List<Label> labels = new List<Label>();
public List<ExceptionBlock> blocks = new List<ExceptionBlock>();
public CodeInstruction(OpCode opcode, object operand = null)
{
this.opcode = opcode;
this.operand = operand;
}
public CodeInstruction(CodeInstruction instruction)
{
opcode = instruction.opcode;
operand = instruction.operand;
labels = instruction.labels.ToArray().ToList();
}
public CodeInstruction Clone()
{
return new CodeInstruction(this) { labels = new List<Label>() };
}
public CodeInstruction Clone(OpCode opcode)
{
var instruction = new CodeInstruction(this) { labels = new List<Label>() };
instruction.opcode = opcode;
return instruction;
}
public CodeInstruction Clone(OpCode opcode, object operand)
{
var instruction = new CodeInstruction(this) { labels = new List<Label>() };
instruction.opcode = opcode;
instruction.operand = operand;
return instruction;
}
public override string ToString()
{
var list = new List<string>();
foreach (var label in labels)
list.Add("Label" + label.GetHashCode());
foreach (var block in blocks)
list.Add("EX_" + block.blockType.ToString().Replace("Block", ""));
var extras = list.Count > 0 ? " [" + string.Join(", ", list.ToArray()) + "]" : "";
var operandStr = Emitter.FormatArgument(operand);
if (operandStr != "") operandStr = " " + operandStr;
return opcode + operandStr + extras;
}
}
}
|
mit
|
C#
|
0bd3f17752448faca3d9833f59c9b440104daa89
|
Update IBundleUrlHelper.cs
|
irii/Bundler,irii/Bundler
|
Bundler/Infrastructure/IBundleUrlHelper.cs
|
Bundler/Infrastructure/IBundleUrlHelper.cs
|
using System.Collections.Generic;
namespace Bundler.Infrastructure {
public interface IBundleUrlHelper {
string ToAbsolute(string virtualUrl);
/// <summary>
/// Returns dictionary with all query parameters
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
IDictionary<string, string> ParseQuery(string query);
/// <summary>
/// Encodes the given input to match the url requirements.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
string Encode(string input);
/// <summary>
/// Decodes the encoded input.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
string Decode(string input);
}
}
|
using System.Collections.Generic;
namespace Bundler.Infrastructure {
public interface IBundleUrlHelper {
string ToAbsolute(string virtualUrl);
/// <summary>
/// Returns a case insensetive dictionary with all query parameters
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
IDictionary<string, string> ParseQuery(string query);
/// <summary>
/// Encodes the given input to match the url requirements.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
string Encode(string input);
/// <summary>
/// Decodes the encoded input.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
string Decode(string input);
}
}
|
mit
|
C#
|
3ea4d28cf65b237684eb3c8f1fa4e3f54d6921ff
|
Update ElmahTarget.cs
|
NLog/NLog.Etw,naveensrinivasan/NLog.Etw,304NotModified/NLog.Etw,304NotModified/NLog-Contrib,zbrad/NLog.Etw,NLog/NLog-Contrib
|
NLog.Elmah/ElmahTarget.cs
|
NLog.Elmah/ElmahTarget.cs
|
// Copyright 2013 Kim Christensen, Todd Meinershagen, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
using System;
using System.Web;
using Elmah;
using NLog.Targets;
namespace NLog.Elmah
{
[Target("Elmah")]
public sealed class ElmahTarget : TargetWithLayout
{
private readonly ErrorLog _errorLog;
public bool LogLevelAsType { get; set; }
public ElmahTarget()
: this (ErrorLog.GetDefault(null))
{}
public ElmahTarget(ErrorLog errorLog)
{
_errorLog = errorLog;
LogLevelAsType = false;
}
protected override void Write(LogEventInfo logEvent)
{
var logMessage = Layout.Render(logEvent);
var httpContext = HttpContext.Current;
var error = logEvent.Exception == null ? new Error() : httpContext != null ? new Error(logEvent.Exception, httpContext) : new Error(logEvent.Exception);
var type = error.Exception != null
? error.Exception.GetType().FullName
: LogLevelAsType ? logEvent.Level.Name : string.Empty;
error.Type = type;
error.Message = logMessage;
error.Time = GetCurrentDateTime == null ? logEvent.TimeStamp : GetCurrentDateTime();
error.HostName = Environment.MachineName;
error.Detail = logEvent.Exception == null ? logMessage : logEvent.Exception.StackTrace;
_errorLog.Log(error);
}
public Func<DateTime> GetCurrentDateTime { get; set; }
}
}
|
// Copyright 2013 Kim Christensen, Todd Meinershagen, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
using System;
using Elmah;
using NLog.Targets;
namespace NLog.Elmah
{
[Target("Elmah")]
public sealed class ElmahTarget : TargetWithLayout
{
private readonly ErrorLog _errorLog;
public bool LogLevelAsType { get; set; }
public ElmahTarget()
: this (ErrorLog.GetDefault(null))
{}
public ElmahTarget(ErrorLog errorLog)
{
_errorLog = errorLog;
LogLevelAsType = false;
}
protected override void Write(LogEventInfo logEvent)
{
var logMessage = Layout.Render(logEvent);
var error = logEvent.Exception == null ? new Error() : new Error(logEvent.Exception);
var type = error.Exception != null
? error.Exception.GetType().FullName
: LogLevelAsType ? logEvent.Level.Name : string.Empty;
error.Type = type;
error.Message = logMessage;
error.Time = GetCurrentDateTime == null ? logEvent.TimeStamp : GetCurrentDateTime();
error.HostName = Environment.MachineName;
error.Detail = logEvent.Exception == null ? logMessage : logEvent.Exception.StackTrace;
_errorLog.Log(error);
}
public Func<DateTime> GetCurrentDateTime { get; set; }
}
}
|
apache-2.0
|
C#
|
0cb7a14b682fcddf7683868962de2a43fabeceab
|
Change Football-API's key from testing key to Joker server.
|
tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer
|
DailySoccer2015/ApiApp/Repositories/FootballService.cs
|
DailySoccer2015/ApiApp/Repositories/FootballService.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApiApp.Models;
using System.Net;
using RestSharp;
namespace ApiApp.Repositories
{
/// <summary>
/// ตัวเชื่อมต่อกับฟุตบอลเซอร์วิส
/// </summary>
public class FootballService : IFootballService
{
#region IFootballService members
/// <summary>
/// ดึงข้อมูลแมช์การแข่งขันจากรหัสลีก
/// </summary>
/// <param name="leagueId">รหัสลีก</param>
/// <param name="fromDate">เริ่มดึงจากวันที่</param>
/// <param name="toDate">ดึงถึงวันที่</param>
public IEnumerable<MatchAPIInformation> GetMatchesByLeagueId(string leagueId, DateTime fromDate, DateTime toDate)
{
const string dateFormat = "dd.MM.yyyy";
const string APIKey = "d7946ce1-b897-975e-d462b1899cd6"; // miolynet fot Joker azure
//const string APIKey = "fb8e4d95-d176-b433-7a10ecb4ebe7"; // perawatt fot localhost
const string urlFormat = "/api/?Action=fixtures&APIKey={0}&comp_id={1}&from_date={2}&to_date={3}";
var url = string.Format(urlFormat, APIKey, leagueId, fromDate.ToString(dateFormat), toDate.ToString(dateFormat));
const string ClientBaseURL = "http://football-api.com";
var client = new RestClient(ClientBaseURL);
var request = new RestRequest(url);
var respond = client.Execute<MatchAPIRespond>(request);
var error = respond.Data == null || respond.Data.matches == null;
if (error) return Enumerable.Empty<MatchAPIInformation>();
return respond.Data.matches;
}
#endregion IFootballService members
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApiApp.Models;
using System.Net;
using RestSharp;
namespace ApiApp.Repositories
{
/// <summary>
/// ตัวเชื่อมต่อกับฟุตบอลเซอร์วิส
/// </summary>
public class FootballService : IFootballService
{
#region IFootballService members
/// <summary>
/// ดึงข้อมูลแมช์การแข่งขันจากรหัสลีก
/// </summary>
/// <param name="leagueId">รหัสลีก</param>
/// <param name="fromDate">เริ่มดึงจากวันที่</param>
/// <param name="toDate">ดึงถึงวันที่</param>
public IEnumerable<MatchAPIInformation> GetMatchesByLeagueId(string leagueId, DateTime fromDate, DateTime toDate)
{
const string dateFormat = "dd.MM.yyyy";
//const string APIKey = "d7946ce1-b897-975e-d462b1899cd6"; // miolynet fot Joker azure
const string APIKey = "fb8e4d95-d176-b433-7a10ecb4ebe7"; // perawatt fot localhost
const string urlFormat = "/api/?Action=fixtures&APIKey={0}&comp_id={1}&from_date={2}&to_date={3}";
var url = string.Format(urlFormat, APIKey, leagueId, fromDate.ToString(dateFormat), toDate.ToString(dateFormat));
const string ClientBaseURL = "http://football-api.com";
var client = new RestClient(ClientBaseURL);
var request = new RestRequest(url);
var respond = client.Execute<MatchAPIRespond>(request);
var error = respond.Data == null || respond.Data.matches == null;
if (error) return Enumerable.Empty<MatchAPIInformation>();
return respond.Data.matches;
}
#endregion IFootballService members
}
}
|
mit
|
C#
|
726a976df889dcaca44085de8e312fb5a6c3b11b
|
Improve LinkPickerAttribute
|
Gibe/Gibe.DittoProcessors
|
Gibe.DittoProcessors/Processors/LinkPickerAttribute.cs
|
Gibe.DittoProcessors/Processors/LinkPickerAttribute.cs
|
using Gibe.DittoProcessors.Processors.Models;
using Gibe.UmbracoWrappers;
using Newtonsoft.Json;
using Our.Umbraco.Ditto;
namespace Gibe.DittoProcessors.Processors
{
public class LinkPickerAttribute : DittoProcessorAttribute
{
private readonly IUmbracoWrapper _umbracoWrapper;
public LinkPickerAttribute(IUmbracoWrapper umbracoWrapper)
{
_umbracoWrapper = umbracoWrapper;
}
public override object ProcessValue()
{
if (string.IsNullOrEmpty(Value?.ToString()))
{
return null;
}
var link = JsonConvert.DeserializeObject<LinkPickerModel>(Value.ToString());
if (link.Id != default(int))
{
link.Url = _umbracoWrapper.TypedContent(link.Id).Url;
}
return link;
}
}
}
|
using Gibe.DittoProcessors.Processors.Models;
using Newtonsoft.Json;
using Our.Umbraco.Ditto;
namespace Gibe.DittoProcessors.Processors
{
public class LinkPickerAttribute : DittoProcessorAttribute
{
public override object ProcessValue()
{
if (string.IsNullOrEmpty(Value?.ToString()))
{
return null;
}
return JsonConvert.DeserializeObject<LinkPickerModel>(Value.ToString());
}
}
}
|
mit
|
C#
|
116ab1e112ada6e181ef584301524a2df9de766e
|
Set the current HTTP Context on errors in the middleware
|
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
|
Mindscape.Raygun4Net.AspNet5/RaygunAspNetMiddleware.cs
|
Mindscape.Raygun4Net.AspNet5/RaygunAspNetMiddleware.cs
|
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.DependencyInjection;
namespace Mindscape.Raygun4Net.AspNet5
{
public interface IRaygunSettingsProvider
{
RaygunSettings GetRaygunSettings(RaygunSettings baseSettings);
}
public class RaygunSettingsProvider : IRaygunSettingsProvider
{
private readonly Func<RaygunSettings, RaygunSettings> _customConfig;
public RaygunSettingsProvider(Func<RaygunSettings, RaygunSettings> customConfig)
{
this._customConfig = customConfig;
}
public RaygunSettings GetRaygunSettings(RaygunSettings baseSettings)
{
if(_customConfig != null)
{
return _customConfig(baseSettings);
}
return baseSettings;
}
}
public class RaygunAspNetMiddleware
{
private readonly RequestDelegate _next;
private readonly RaygunSettings _settings;
public RaygunAspNetMiddleware(RequestDelegate next, IOptions<RaygunSettings> settings, IRaygunSettingsProvider customConfig)
{
_next = next;
if(customConfig != null)
{
_settings = customConfig.GetRaygunSettings(settings.Value ?? new RaygunSettings());
}
else
{
_settings = settings.Value ?? new RaygunSettings();
}
}
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next.Invoke(httpContext);
}
catch(Exception e)
{
var client = new RaygunAspNet5Client(_settings);
client.RaygunCurrentRequest(httpContext);
await client.SendInBackground(e);
throw;
}
}
}
public static class IApplicationBuilderExtensions
{
public static IApplicationBuilder UseRaygun(this IApplicationBuilder app)
{
return app.UseMiddleware<RaygunAspNetMiddleware>();
}
public static IServiceCollection AddRaygun(this IServiceCollection services, IConfiguration configuration, Func<RaygunSettings, RaygunSettings> customConfig = null)
{
var settings = configuration.GetSection("RaygunSettings");
services.Configure<RaygunSettings>(settings);
services.AddInstance<IRaygunSettingsProvider>(new RaygunSettingsProvider(customConfig));
return services;
}
}
}
|
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.DependencyInjection;
namespace Mindscape.Raygun4Net.AspNet5
{
public interface IRaygunSettingsProvider
{
RaygunSettings GetRaygunSettings(RaygunSettings baseSettings);
}
public class RaygunSettingsProvider : IRaygunSettingsProvider
{
private readonly Func<RaygunSettings, RaygunSettings> _customConfig;
public RaygunSettingsProvider(Func<RaygunSettings, RaygunSettings> customConfig)
{
this._customConfig = customConfig;
}
public RaygunSettings GetRaygunSettings(RaygunSettings baseSettings)
{
if(_customConfig != null)
{
return _customConfig(baseSettings);
}
return baseSettings;
}
}
public class RaygunAspNetMiddleware
{
private readonly RequestDelegate _next;
private readonly RaygunSettings _settings;
public RaygunAspNetMiddleware(RequestDelegate next, IOptions<RaygunSettings> settings, IRaygunSettingsProvider customConfig)
{
_next = next;
if(customConfig != null)
{
_settings = customConfig.GetRaygunSettings(settings.Value ?? new RaygunSettings());
}
else
{
_settings = settings.Value ?? new RaygunSettings();
}
}
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next.Invoke(httpContext);
}
catch(Exception e)
{
var client = new RaygunAspNet5Client(_settings);
await client.SendInBackground(e);
}
}
}
public static class IApplicationBuilderExtensions
{
public static IApplicationBuilder UseRaygun(this IApplicationBuilder app)
{
return app.UseMiddleware<RaygunAspNetMiddleware>();
}
public static IServiceCollection AddRaygun(this IServiceCollection services, IConfiguration configuration, Func<RaygunSettings, RaygunSettings> customConfig = null)
{
var settings = configuration.GetSection("RaygunSettings");
services.Configure<RaygunSettings>(settings);
services.AddInstance<IRaygunSettingsProvider>(new RaygunSettingsProvider(customConfig));
return services;
}
}
}
|
mit
|
C#
|
8f5d107169315c5c10e815be58c91b480b16d719
|
Add documentation and remove unused using statements
|
peasy/Samples,peasy/Samples,peasy/Samples,ahanusa/facile.net,ahanusa/Peasy.NET,peasy/Peasy.NET
|
Facile.Core/ExecutionResult.cs
|
Facile.Core/ExecutionResult.cs
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Facile.Core
{
/// <summary>
/// Defines the result of a command's execution
/// </summary>
public class ExecutionResult
{
public bool Success { get; set; }
public IEnumerable<ValidationResult> Errors { get; set; }
}
/// <summary>
/// Defines the result of a command's execution and returns a value of T
/// </summary>
public class ExecutionResult<T> : ExecutionResult
{
public T Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facile.Core
{
public class ExecutionResult
{
public bool Success { get; set; }
public IEnumerable<ValidationResult> Errors { get; set; }
}
public class ExecutionResult<T> : ExecutionResult
{
public T Value { get; set; }
}
}
|
mit
|
C#
|
8127526921684e8d32dc985a3fec6ddcbd50860f
|
Fix typo in android ColorExtension
|
Wumpf/chinesecheckers
|
HalmaAndroid/ColorExtension.cs
|
HalmaAndroid/ColorExtension.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.Widget;
namespace HalmaAndroid
{
static class ColorExtension
{
public static Android.Graphics.Color ToAndroid(this Xamarin.Forms.Color color)
{
return new Android.Graphics.Color((byte)(255 * color.R), (byte)(255 * color.G), (byte)(255 * color.B), (byte)(255 * color.A));
}
}
}
|
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.Widget;
namespace HalmaAndroid
{
static class ColorExtension
{
public static Android.Graphics.Color ToAndroid(this Xamarin.Forms.Color color)
{
return new Android.Graphics.Color((byte)(255 * color.R), (byte)(255 * color.G), (byte)(255 * color.B), , (byte)(255 * color.A));
}
}
}
|
mit
|
C#
|
b7bfda498c1b6e553f603921ca7d07b5130f3f1f
|
fix entity without empty constructor
|
remcoros/InspectR,remcoros/InspectR
|
InspectR/Data/InspectorInfo.cs
|
InspectR/Data/InspectorInfo.cs
|
using System;
namespace InspectR.Data
{
public class InspectorInfo
{
public Guid Id { get; protected set; }
public string UniqueKey { get; protected set; }
public bool IsPrivate { get; set; }
public DateTime DateCreated { get; protected set; }
public InspectorInfo()
{
Id = Guid.NewGuid();
UniqueKey = Id.ToString().GetHashCode().ToString("x");
DateCreated = DateTime.Now;
}
}
}
|
using System;
namespace InspectR.Data
{
public class InspectorInfo
{
public Guid Id { get; protected set; }
public string UniqueKey { get; protected set; }
public bool IsPrivate { get; set; }
public DateTime DateCreated { get; protected set; }
public InspectorInfo(bool isPrivate = false)
{
Id = Guid.NewGuid();
UniqueKey = Id.ToString().GetHashCode().ToString("x");
DateCreated = DateTime.Now;
IsPrivate = isPrivate;
}
}
}
|
mit
|
C#
|
b7e9bfa8507cc646d4c7cf6c1b96a3a4135dab66
|
adjust code so that HasTable returns a boolean from the database indicating that the table exists (or not)
|
DBCG/Dataphor,DBCG/Dataphor,n8allan/Dataphor,n8allan/Dataphor,n8allan/Dataphor,n8allan/Dataphor,n8allan/Dataphor,DBCG/Dataphor,DBCG/Dataphor,DBCG/Dataphor,n8allan/Dataphor,DBCG/Dataphor
|
Dataphor/DAE.PGSQL/PGSQLStoreConnection.cs
|
Dataphor/DAE.PGSQL/PGSQLStoreConnection.cs
|
/*
Alphora Dataphor
Copyright 2000-2008 Alphora
This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt
*/
#define USESQLCONNECTION
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
#if USESQLCONNECTION
using Alphora.Dataphor.DAE.Connection;
using Alphora.Dataphor.DAE.Connection.PGSQL;
#else
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
#endif
namespace Alphora.Dataphor.DAE.Store.PGSQL
{
public class PostgreSQLStoreConnection : SQLStoreConnection
{
public PostgreSQLStoreConnection(PostgreSQLStore AStore) : base(AStore) { }
#if USESQLCONNECTION
protected override SQLConnection InternalCreateConnection()
{
return new PostgreSQLConnection(Store.ConnectionString);
}
#else
protected override DbConnection InternalCreateConnection()
{
return new SqlConnection(Store.ConnectionString);
}
#endif
HasTable
public override bool (string ATableName)
{
string LStatement = String.Format("select count(*)>0 from PG_TABLES where TABLENAME = '{0}'", ATableName);
bool LTableExists = (bool) this.ExecuteScalar(LStatement);
return LTableExists;
}
}
}
|
/*
Alphora Dataphor
Copyright 2000-2008 Alphora
This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt
*/
#define USESQLCONNECTION
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
#if USESQLCONNECTION
using Alphora.Dataphor.DAE.Connection;
using Alphora.Dataphor.DAE.Connection.PGSQL;
#else
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
#endif
namespace Alphora.Dataphor.DAE.Store.PGSQL
{
public class PostgreSQLStoreConnection : SQLStoreConnection
{
public PostgreSQLStoreConnection(PostgreSQLStore AStore) : base(AStore) { }
#if USESQLCONNECTION
protected override SQLConnection InternalCreateConnection()
{
return new PostgreSQLConnection(Store.ConnectionString);
}
#else
protected override DbConnection InternalCreateConnection()
{
return new SqlConnection(Store.ConnectionString);
}
#endif
public override bool HasTable(string ATableName)
{
string LStatement = String.Format("select count(*) from PG_TABLES where TABLENAME = '{0}'", ATableName);
var LTablesWithName = (int)this.ExecuteScalar(LStatement);
return (LTablesWithName != 0);
}
}
}
|
bsd-3-clause
|
C#
|
e23348a66003e43c4cdc089405dd524e652a8eda
|
Add semicolon character
|
fredatgithub/UsefulFunctions
|
FonctionsUtiles.Fred.Csharp/Punctuation.cs
|
FonctionsUtiles.Fred.Csharp/Punctuation.cs
|
/*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
namespace FonctionsUtiles.Fred.Csharp
{
public static class Punctuation
{
public const string Comma = ",";
public const string Colon = ":";
public const string SemiColon = ";";
public const string OneSpace = " ";
public const string Dash = "-";
public const string UnderScore = "_";
public const string SignAt = "@";
public const string Ampersand = "&";
public const string SignSharp = "#";
public const string Period = ".";
public const string Backslash = "\\";
public const string Slash = "/";
public const string OpenParenthesis = "(";
public const string CloseParenthesis = ")";
public const string OpenCurlyBrace = "{";
public const string CloseCurlyBrace = "}";
public const string OpenSquareBracket = "[";
public const string CloseSquareBracket = "]";
public const string LessThan = "<";
public const string GreaterThan = ">";
public const string DoubleQuote = "\"";
public const string SimpleQuote = "'";
public const string Tilde = "~";
public const string Pipe = "|";
public const string Plus = "+";
public const string Minus = "-";
public const string Multiply = "*";
public const string Divide = "/";
public const string Dollar = "$";
public const string Pound = "£";
public const string Percent = "%";
public const string QuestionMark = "?";
public const string ExclamationPoint = "!";
public const string Chapter = "§";
public const string Micro = "µ";
public static string CrLf = Environment.NewLine;
public static string Tabulate(ushort numberOfTabulation = 1)
{
string result = string.Empty;
for (int number = 0; number < numberOfTabulation; number++)
{
result += " ";
}
return result;
}
}
}
|
/*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
namespace FonctionsUtiles.Fred.Csharp
{
public static class Punctuation
{
public const string Comma = ",";
public const string Colon = ":";
public const string OneSpace = " ";
public const string Dash = "-";
public const string UnderScore = "_";
public const string SignAt = "@";
public const string Ampersand = "&";
public const string SignSharp = "#";
public const string Period = ".";
public const string Backslash = "\\";
public const string Slash = "/";
public const string OpenParenthesis = "(";
public const string CloseParenthesis = ")";
public const string OpenCurlyBrace = "{";
public const string CloseCurlyBrace = "}";
public const string OpenSquareBracket = "[";
public const string CloseSquareBracket = "]";
public const string LessThan = "<";
public const string GreaterThan = ">";
public const string DoubleQuote = "\"";
public const string SimpleQuote = "'";
public const string Tilde = "~";
public const string Pipe = "|";
public const string Plus = "+";
public const string Minus = "-";
public const string Multiply = "*";
public const string Divide = "/";
public const string Dollar = "$";
public const string Pound = "£";
public const string Percent = "%";
public const string QuestionMark = "?";
public const string ExclamationPoint = "!";
public const string Chapter = "§";
public const string Micro = "µ";
public static string CrLf = Environment.NewLine;
public static string Tabulate(ushort numberOfTabulation = 1)
{
string result = string.Empty;
for (int number = 0; number < numberOfTabulation; number++)
{
result += " ";
}
return result;
}
}
}
|
mit
|
C#
|
a507a06916e803f770fd6971e6c22022977c4d54
|
fix compile error
|
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14
|
Content.Shared/EntryPoint.cs
|
Content.Shared/EntryPoint.cs
|
using System;
using System.Collections.Generic;
using Content.Shared.Maps;
using Robust.Shared.ContentPack;
using Robust.Shared.Interfaces.Map;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
namespace Content.Shared
{
public class EntryPoint : GameShared
{
#pragma warning disable 649
[Dependency] private readonly IPrototypeManager _prototypeManager;
[Dependency] private readonly ITileDefinitionManager _tileDefinitionManager;
#pragma warning restore 649
public override void Init()
{
IoCManager.InjectDependencies(this);
}
public override void PostInit()
{
base.PostInit();
_initTileDefinitions();
}
private void _initTileDefinitions()
{
// Register space first because I'm a hard coding hack.
var spaceDef = _prototypeManager.Index<ContentTileDefinition>("space");
_tileDefinitionManager.Register(spaceDef);
var prototypeList = new List<ContentTileDefinition>();
foreach (var tileDef in _prototypeManager.EnumeratePrototypes<ContentTileDefinition>())
{
if (tileDef.Name == "space")
{
continue;
}
prototypeList.Add(tileDef);
}
// Sort ordinal to ensure it's consistent client and server.
// So that tile IDs match up.
prototypeList.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
foreach (var tileDef in prototypeList)
{
_tileDefinitionManager.Register(tileDef);
}
_tileDefinitionManager.Initialize();
}
}
}
|
using System;
using System.Collections.Generic;
using Content.Shared.Maps;
using Robust.Shared.ContentPack;
using Robust.Shared.Interfaces.Map;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
namespace Content.Shared
{
public class EntryPoint : GameShared
{
#pragma warning disable 649
[Dependency] private readonly IPrototypeManager _prototypeManager;
[Dependency] private readonly ITileDefinitionManager _tileDefinitionManager;
#pragma warning restore 649
public override void Init()
{
IoCManager.InjectDepe ndencies(this);
}
public override void PostInit()
{
base.PostInit();
_initTileDefinitions();
}
private void _initTileDefinitions()
{
// Register space first because I'm a hard coding hack.
var spaceDef = _prototypeManager.Index<ContentTileDefinition>("space");
_tileDefinitionManager.Register(spaceDef);
var prototypeList = new List<ContentTileDefinition>();
foreach (var tileDef in _prototypeManager.EnumeratePrototypes<ContentTileDefinition>())
{
if (tileDef.Name == "space")
{
continue;
}
prototypeList.Add(tileDef);
}
// Sort ordinal to ensure it's consistent client and server.
// So that tile IDs match up.
prototypeList.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
foreach (var tileDef in prototypeList)
{
_tileDefinitionManager.Register(tileDef);
}
_tileDefinitionManager.Initialize();
}
}
}
|
mit
|
C#
|
0f59ff7b4d5c3784ddea590d28c5df412fd56098
|
remove unused methods from MarshalUtils
|
muxi/grpc,jtattermusch/grpc,vjpai/grpc,nicolasnoble/grpc,pszemus/grpc,vjpai/grpc,sreecha/grpc,stanley-cheung/grpc,ejona86/grpc,ctiller/grpc,donnadionne/grpc,donnadionne/grpc,pszemus/grpc,nicolasnoble/grpc,carl-mastrangelo/grpc,nicolasnoble/grpc,ctiller/grpc,stanley-cheung/grpc,ctiller/grpc,ejona86/grpc,sreecha/grpc,sreecha/grpc,jboeuf/grpc,pszemus/grpc,muxi/grpc,pszemus/grpc,sreecha/grpc,nicolasnoble/grpc,pszemus/grpc,ctiller/grpc,nicolasnoble/grpc,sreecha/grpc,vjpai/grpc,vjpai/grpc,nicolasnoble/grpc,sreecha/grpc,ctiller/grpc,ejona86/grpc,grpc/grpc,jtattermusch/grpc,nicolasnoble/grpc,jboeuf/grpc,jtattermusch/grpc,nicolasnoble/grpc,carl-mastrangelo/grpc,jboeuf/grpc,donnadionne/grpc,firebase/grpc,stanley-cheung/grpc,jboeuf/grpc,jboeuf/grpc,donnadionne/grpc,muxi/grpc,jboeuf/grpc,sreecha/grpc,grpc/grpc,stanley-cheung/grpc,firebase/grpc,nicolasnoble/grpc,stanley-cheung/grpc,muxi/grpc,vjpai/grpc,ejona86/grpc,jboeuf/grpc,ejona86/grpc,carl-mastrangelo/grpc,donnadionne/grpc,carl-mastrangelo/grpc,jtattermusch/grpc,muxi/grpc,pszemus/grpc,firebase/grpc,jtattermusch/grpc,sreecha/grpc,stanley-cheung/grpc,carl-mastrangelo/grpc,firebase/grpc,donnadionne/grpc,firebase/grpc,donnadionne/grpc,jtattermusch/grpc,firebase/grpc,stanley-cheung/grpc,sreecha/grpc,muxi/grpc,donnadionne/grpc,ctiller/grpc,vjpai/grpc,carl-mastrangelo/grpc,firebase/grpc,ejona86/grpc,muxi/grpc,jtattermusch/grpc,carl-mastrangelo/grpc,sreecha/grpc,ctiller/grpc,jtattermusch/grpc,ejona86/grpc,ctiller/grpc,jboeuf/grpc,grpc/grpc,stanley-cheung/grpc,donnadionne/grpc,grpc/grpc,donnadionne/grpc,grpc/grpc,jtattermusch/grpc,firebase/grpc,grpc/grpc,grpc/grpc,grpc/grpc,vjpai/grpc,vjpai/grpc,pszemus/grpc,pszemus/grpc,muxi/grpc,firebase/grpc,stanley-cheung/grpc,stanley-cheung/grpc,grpc/grpc,nicolasnoble/grpc,muxi/grpc,carl-mastrangelo/grpc,ctiller/grpc,carl-mastrangelo/grpc,firebase/grpc,grpc/grpc,vjpai/grpc,pszemus/grpc,carl-mastrangelo/grpc,pszemus/grpc,carl-mastrangelo/grpc,sreecha/grpc,stanley-cheung/grpc,carl-mastrangelo/grpc,donnadionne/grpc,vjpai/grpc,ejona86/grpc,grpc/grpc,ctiller/grpc,ctiller/grpc,firebase/grpc,grpc/grpc,ejona86/grpc,jboeuf/grpc,ejona86/grpc,ctiller/grpc,jboeuf/grpc,jboeuf/grpc,muxi/grpc,vjpai/grpc,muxi/grpc,muxi/grpc,ejona86/grpc,jboeuf/grpc,jtattermusch/grpc,nicolasnoble/grpc,ejona86/grpc,pszemus/grpc,nicolasnoble/grpc,vjpai/grpc,sreecha/grpc,jtattermusch/grpc,firebase/grpc,stanley-cheung/grpc,donnadionne/grpc,jtattermusch/grpc,pszemus/grpc
|
src/csharp/Grpc.Core/Internal/MarshalUtils.cs
|
src/csharp/Grpc.Core/Internal/MarshalUtils.cs
|
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Grpc.Core.Internal
{
/// <summary>
/// Useful methods for native/managed marshalling.
/// </summary>
internal static class MarshalUtils
{
static readonly Encoding EncodingUTF8 = System.Text.Encoding.UTF8;
/// <summary>
/// Converts <c>IntPtr</c> pointing to a UTF-8 encoded byte array to <c>string</c>.
/// </summary>
public static string PtrToStringUTF8(IntPtr ptr, int len)
{
if (len == 0)
{
return "";
}
// TODO(jtattermusch): once Span dependency is added,
// use Span-based API to decode the string without copying the buffer.
var bytes = new byte[len];
Marshal.Copy(ptr, bytes, 0, len);
return EncodingUTF8.GetString(bytes);
}
/// <summary>
/// Returns byte array containing UTF-8 encoding of given string.
/// </summary>
public static byte[] GetBytesUTF8(string str)
{
return EncodingUTF8.GetBytes(str);
}
/// <summary>
/// Get string from a UTF8 encoded byte array.
/// </summary>
public static string GetStringUTF8(byte[] bytes)
{
return EncodingUTF8.GetString(bytes);
}
}
}
|
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Grpc.Core.Internal
{
/// <summary>
/// Useful methods for native/managed marshalling.
/// </summary>
internal static class MarshalUtils
{
static readonly Encoding EncodingUTF8 = System.Text.Encoding.UTF8;
static readonly Encoding EncodingASCII = System.Text.Encoding.ASCII;
/// <summary>
/// Converts <c>IntPtr</c> pointing to a UTF-8 encoded byte array to <c>string</c>.
/// </summary>
public static string PtrToStringUTF8(IntPtr ptr, int len)
{
if (len == 0)
{
return "";
}
// TODO(jtattermusch): once Span dependency is added,
// use Span-based API to decode the string without copying the buffer.
var bytes = new byte[len];
Marshal.Copy(ptr, bytes, 0, len);
return EncodingUTF8.GetString(bytes);
}
/// <summary>
/// Returns byte array containing UTF-8 encoding of given string.
/// </summary>
public static byte[] GetBytesUTF8(string str)
{
return EncodingUTF8.GetBytes(str);
}
/// <summary>
/// Get string from a UTF8 encoded byte array.
/// </summary>
public static string GetStringUTF8(byte[] bytes)
{
return EncodingUTF8.GetString(bytes);
}
/// <summary>
/// Returns byte array containing ASCII encoding of given string.
/// </summary>
public static byte[] GetBytesASCII(string str)
{
return EncodingASCII.GetBytes(str);
}
/// <summary>
/// Get string from an ASCII encoded byte array.
/// </summary>
public static string GetStringASCII(byte[] bytes)
{
return EncodingASCII.GetString(bytes);
}
}
}
|
apache-2.0
|
C#
|
5d31729eac7f11c440b55989b3dbf2cdd7073afa
|
Update version number.
|
Damnae/storybrew
|
editor/Properties/AssemblyInfo.cs
|
editor/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.74.*")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.73.*")]
|
mit
|
C#
|
dc3c91bde78c04487811fc0baa21007e5572b9f7
|
Add TODO to handle serialization for null key
|
mattherman/MbDotNet,mattherman/MbDotNet,SuperDrew/MbDotNet
|
MbDotNet/Models/Imposters/HttpsImposter.cs
|
MbDotNet/Models/Imposters/HttpsImposter.cs
|
using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
// TODO Need to not include key in serialization when its null to allow mb to use self-signed certificate.
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
|
using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
|
mit
|
C#
|
2e1d90f3a36b93461305b5d4473d1a0a95794b79
|
Allow constructing touch position input with a touch
|
ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework
|
osu.Framework/Input/StateChanges/TouchPositionInput.cs
|
osu.Framework/Input/StateChanges/TouchPositionInput.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.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input.StateChanges
{
/// <summary>
/// Denotes an absolute change of a provided touch source's position.
/// Any provided touch source should always be in the range <see cref="MouseButton.Touch1"/>-<see cref="MouseButton.Touch10"/>.
/// </summary>
public class TouchPositionInput : IInput
{
/// <summary>
/// The touch source to be modified.
/// </summary>
public readonly MouseButton Source;
/// <summary>
/// The new position to move to.
/// </summary>
public readonly Vector2 Position;
/// <summary>
/// Constructs a <see cref="TouchPositionInput"/> from a <see cref="Touch"/> structure.
/// </summary>
/// <param name="touch">The <see cref="Touch"/> to construct from.</param>
public TouchPositionInput(Touch touch)
: this(touch.Source, touch.Position)
{
}
/// <summary>
/// Constructs a <see cref="TouchPositionInput"/> with a <paramref name="source"/> and a <paramref name="newPosition"/>.
/// </summary>
/// <param name="source">The touch source.</param>
/// <param name="newPosition">The new position to move to.</param>
public TouchPositionInput(MouseButton source, Vector2 newPosition)
{
if (source < MouseButton.Touch1 || source > MouseButton.Touch10)
throw new ArgumentException($"Invalid touch source provided: {source}", nameof(source));
Source = source;
Position = newPosition;
}
public void Apply(InputState state, IInputStateChangeHandler handler)
{
var touch = state.Touch;
Vector2? lastPosition = touch.GetTouchPosition(Source);
if (lastPosition == Position)
return;
touch.TouchPositions[Source] = Position;
handler.HandleInputStateChange(new TouchPositionChangeEvent(state, this, Source, lastPosition ?? Position));
}
}
}
|
// 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.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input.StateChanges
{
/// <summary>
/// Denotes an absolute change of a provided touch source's position.
/// Any provided touch source should always be in the range <see cref="MouseButton.Touch1"/>-<see cref="MouseButton.Touch10"/>.
/// </summary>
public class TouchPositionInput : IInput
{
/// <summary>
/// The touch source to be modified.
/// </summary>
public readonly MouseButton Source;
/// <summary>
/// The new position to move to.
/// </summary>
public readonly Vector2 Position;
public TouchPositionInput(MouseButton source, Vector2 newPosition)
{
if (source < MouseButton.Touch1 || source > MouseButton.Touch10)
throw new ArgumentException($"Invalid touch source provided: {source}", nameof(source));
Source = source;
Position = newPosition;
}
public void Apply(InputState state, IInputStateChangeHandler handler)
{
var touch = state.Touch;
Vector2? lastPosition = touch.GetTouchPosition(Source);
if (lastPosition == Position)
return;
touch.TouchPositions[Source] = Position;
handler.HandleInputStateChange(new TouchPositionChangeEvent(state, this, Source, lastPosition ?? Position));
}
}
}
|
mit
|
C#
|
9cc248ce0f0107a122a0a565ff1200971711efd8
|
Fix build
|
CatenaLogic/JiraCli
|
src/JiraCli/Logging/OutputLogListener.cs
|
src/JiraCli/Logging/OutputLogListener.cs
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OutputLogListener.cs" company="CatenaLogic">
// Copyright (c) 2014 - 2014 CatenaLogic. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace JiraCli.Logging
{
using System;
using Catel.Logging;
public class OutputLogListener : ConsoleLogListener
{
public OutputLogListener()
{
IgnoreCatelLogging = true;
IsDebugEnabled = true;
}
protected override string FormatLogEvent(ILog log, string message, LogEvent logEvent, object extraData, LogData logData, DateTime time)
{
return message;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OutputLogListener.cs" company="CatenaLogic">
// Copyright (c) 2014 - 2014 CatenaLogic. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace JiraCli.Logging
{
using System;
using Catel.Logging;
public class OutputLogListener : ConsoleLogListener
{
public OutputLogListener()
{
IgnoreCatelLogging = true;
IsDebugEnabled = true;
}
protected override string FormatLogEvent(ILog log, string message, LogEvent logEvent, object extraData, DateTime time)
{
return message;
}
}
}
|
mit
|
C#
|
c102e33504c0e25518a4c2b307da25491868f0fe
|
Update NDebug.cs
|
NMSLanX/Natasha
|
Natasha/Engine/Debug/NDebug.cs
|
Natasha/Engine/Debug/NDebug.cs
|
namespace Natasha
{
public static class NDebug
{
public static bool UseLog;
static NDebug() => UseLog = true;
public static void Error(string title,string content)
{
NDebugWriter<NError>.Recoder(title,content);
}
public static void Warning(string title, string content)
{
NDebugWriter<NWarning>.Recoder(title, content);
}
public static void Succeed(string title, string content)
{
NDebugWriter<NSucceed>.Recoder(title, content);
}
}
}
|
namespace Natasha
{
public static class NDebug
{
public static bool UseLog;
public static void Error(string title,string content)
{
NDebugWriter<NError>.Recoder(title,content);
}
public static void Warning(string title, string content)
{
NDebugWriter<NWarning>.Recoder(title, content);
}
public static void Succeed(string title, string content)
{
NDebugWriter<NSucceed>.Recoder(title, content);
}
}
}
|
mpl-2.0
|
C#
|
cc52e3987ad9ce355bb2619e337e47057d7b8738
|
Fix AudioFactory on Linux
|
sillsdev/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,andrew-polk/libpalaso,mccarthyrb/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso
|
SIL.Media/AudioFactory.cs
|
SIL.Media/AudioFactory.cs
|
using System;
#if MONO
using SIL.Media.AlsaAudio;
#endif
namespace SIL.Media
{
public class AudioFactory
{
public static ISimpleAudioSession CreateAudioSession(string filePath)
{
#if MONO
//return new AudioGStreamerSession(filePath);
return new AudioAlsaSession(filePath);
#else
return new AudioIrrKlangSession(filePath);
#endif
}
[Obsolete("This was a unfortunate method name. Use CreateAudioSessionInstead.")]
public static ISimpleAudioSession AudioSession(string filePath)
{
return CreateAudioSession(filePath);
}
}
}
|
using System;
namespace SIL.Media
{
public class AudioFactory
{
public static ISimpleAudioSession CreateAudioSession(string filePath)
{
#if MONO
//return new AudioGStreamerSession(filePath);
return new AudioAlsaSession(filePath);
#else
return new AudioIrrKlangSession(filePath);
#endif
}
[Obsolete("This was a unfortunate method name. Use CreateAudioSessionInstead.")]
public static ISimpleAudioSession AudioSession(string filePath)
{
return CreateAudioSession(filePath);
}
}
}
|
mit
|
C#
|
91d57852b66d0796f1a3799bcd44af7d7ca63949
|
Remove a redundant ToArray call
|
chitoku-k/NowPlayingLib
|
NowPlayingLib/SonyDatabase/MediaManager.cs
|
NowPlayingLib/SonyDatabase/MediaManager.cs
|
using SonyMediaPlayerXLib;
using SonyVzProperty;
using System;
using System.Data.OleDb;
using System.IO;
using System.Linq;
namespace NowPlayingLib.SonyDatabase
{
/// <summary>
/// x-アプリのデータベースから曲情報を取得します。
/// </summary>
public class MediaManager
{
/// <summary>
/// データベースのパス。
/// </summary>
public static readonly string DatabasePath = @"Sony Corporation\Sony MediaPlayerX\Packages\MtData.mdb";
/// <summary>
/// メディア オブジェクトを指定して曲情報を取得します。
/// </summary>
/// <param name="media">メディア オブジェクト。</param>
/// <returns>データベースから得られた</returns>
public static ObjectTable GetMediaEntry(ISmpxMediaDescriptor2 media)
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), DatabasePath);
using (var connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path))
using (var context = new MtDataDataContext(connection))
{
// IQueryable.FirstOrDefault では不正な SQL 文が発行される
return context.ObjectTable.Where(x => x.SpecId == (int)VzObjectCategoryEnum.vzObjectCategory_Music + 1 &&
x.Album == media.packageTitle &&
x.Artist == media.artist &&
x.Genre == media.genre &&
x.Name == media.title).AsEnumerable().FirstOrDefault();
}
}
}
}
|
using SonyMediaPlayerXLib;
using SonyVzProperty;
using System;
using System.Data.OleDb;
using System.IO;
using System.Linq;
namespace NowPlayingLib.SonyDatabase
{
/// <summary>
/// x-アプリのデータベースから曲情報を取得します。
/// </summary>
public class MediaManager
{
/// <summary>
/// データベースのパス。
/// </summary>
public static readonly string DatabasePath = @"Sony Corporation\Sony MediaPlayerX\Packages\MtData.mdb";
/// <summary>
/// メディア オブジェクトを指定して曲情報を取得します。
/// </summary>
/// <param name="media">メディア オブジェクト。</param>
/// <returns>データベースから得られた</returns>
public static ObjectTable GetMediaEntry(ISmpxMediaDescriptor2 media)
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), DatabasePath);
using (var connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path))
using (var context = new MtDataDataContext(connection))
{
return context.ObjectTable.Where(x => x.SpecId == (int)VzObjectCategoryEnum.vzObjectCategory_Music + 1 &&
x.Album == media.packageTitle &&
x.Artist == media.artist &&
x.Genre == media.genre &&
x.Name == media.title).ToArray().FirstOrDefault();
}
}
}
}
|
mit
|
C#
|
c75555c5f7e8f7dc35e66a3111d27dbdacad6286
|
add sub type to component list. fixes #19
|
pburls/dewey
|
Dewey.ListItems/Component.cs
|
Dewey.ListItems/Component.cs
|
using Dewey.State;
using System;
using System.Collections.Generic;
namespace Dewey.ListItems
{
static class ComponentExtensions
{
public static void Write(this Component component)
{
Console.ForegroundColor = (ConsoleColor)ItemColor.ComponentItem;
Console.WriteLine(component.BuildDescription());
}
public static void Write(this Component component, Stack<ItemColor> offsets)
{
offsets.WriteOffsets();
Console.ForegroundColor = (ConsoleColor)ItemColor.ComponentItem;
Console.WriteLine("├ {0}", component.BuildDescription());
}
private static string BuildDescription(this Component component)
{
string type = component.ComponentManifest.Type;
if (!string.IsNullOrWhiteSpace(component.ComponentManifest.SubType))
{
type = string.Format("{0}-{1}", type, component.ComponentManifest.SubType);
}
return string.Format("{0} ({1})", component.ComponentManifest.Name, type);
}
}
}
|
using Dewey.State;
using System;
using System.Collections.Generic;
namespace Dewey.ListItems
{
static class ComponentExtensions
{
public static void Write(this Component component)
{
Console.ForegroundColor = (ConsoleColor)ItemColor.ComponentItem;
Console.WriteLine("{0} ({1})", component.ComponentManifest.Name, component.ComponentManifest.Type);
}
public static void Write(this Component component, Stack<ItemColor> offsets)
{
offsets.WriteOffsets();
Console.ForegroundColor = (ConsoleColor)ItemColor.ComponentItem;
Console.WriteLine("├ {0} ({1})", component.ComponentManifest.Name, component.ComponentManifest.Type);
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.