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 |
|---|---|---|---|---|---|---|---|---|
1358431f1987c556a3be6db439b033a02d33c64c | update program.cs to use default builder | RockSolidKnowledge/Samples.IdentityServer4.AdminUiIntegration,RockSolidKnowledge/Samples.IdentityServer4.AdminUiIntegration,RockSolidKnowledge/Samples.IdentityServer4.AdminUiIntegration | Rsk.Samples.IdentityServer4.AdminUiIntegration/Program.cs | Rsk.Samples.IdentityServer4.AdminUiIntegration/Program.cs | using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Rsk.Samples.IdentityServer4.AdminUiIntegration
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Build().Run();
}
public static IHostBuilder BuildWebHost(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
} | using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace Rsk.Samples.IdentityServer4.AdminUiIntegration
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls("http://*:5003")
.UseIISIntegration()
.UseKestrel()
.Build();
}
}
| apache-2.0 | C# |
1c327e8f171881ffd92a06dd3cfb60668a86f2d2 | remove spaces | kusl/Tree | VisualTree/TreeLibrary/BinarySearchTreeNode.cs | VisualTree/TreeLibrary/BinarySearchTreeNode.cs | namespace TreeLibrary
{
public sealed class BinarySearchTreeNode
{
public BinarySearchTreeNode LeftChild { get; set; }
public BinarySearchTreeNode RightChild { get; set; }
public int? Value { get; set; }
public BinarySearchTreeNode()
{
LeftChild = null;
RightChild = null;
Value = null;
}
public BinarySearchTreeNode(int value)
{
LeftChild = null;
RightChild = null;
Value = value;
}
public bool Equals(int value)
{
return this.Value == value;
}
public bool IsLessThan(int value)
{
return this.Value < value;
}
public bool IsGreaterThan(int value)
{
return this.Value > value;
}
}
}
| namespace TreeLibrary
{
public sealed class BinarySearchTreeNode
{
public BinarySearchTreeNode LeftChild { get; set; }
public BinarySearchTreeNode RightChild { get; set; }
public int? Value { get; set; }
public BinarySearchTreeNode()
{
LeftChild = null;
RightChild = null;
Value = null;
}
public BinarySearchTreeNode(int value)
{
LeftChild = null;
RightChild = null;
Value = value;
}
public bool Equals(int value)
{
return this.Value == value;
}
public bool IsLessThan(int value)
{
return this.Value < value;
}
public bool IsGreaterThan(int value)
{
return this.Value > value;
}
}
}
| agpl-3.0 | C# |
786b0b8b5593c2a17cc8bf273d92db6a9b9c8996 | Fix is expanded | MistyKuu/bitbucket-for-visual-studio,MistyKuu/bitbucket-for-visual-studio | Source/GitClientVS.Contracts/Models/Tree/TreeDirectory.cs | Source/GitClientVS.Contracts/Models/Tree/TreeDirectory.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using ParseDiff;
using ReactiveUI;
namespace GitClientVS.Contracts.Models
{
public class TreeDirectory : ITreeFile, INotifyPropertyChanged
{
private bool _isSelected;
private bool _isExpanded;
public string Name { get; set; }
public List<ITreeFile> Files { get; set; }
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = false;
OnPropertyChanged();
}
}
public bool IsExpanded
{
get { return _isExpanded; }
set
{
_isExpanded = value;
OnPropertyChanged();
}
}
public bool IsAdded { get; set; }
public bool IsRemoved { get; set; }
public FileDiff FileDiff { get; set; }
public Type GetTreeType { get { return this.GetType(); } }
public bool IsSelectable { get; set; }
public long Added { get; set; }
public long Removed { get; set; }
public TreeDirectory(string name)
{
Name = name;
Files = new List<ITreeFile>();
FileDiff = null;
IsSelectable = false;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using ParseDiff;
using ReactiveUI;
namespace GitClientVS.Contracts.Models
{
public class TreeDirectory : ITreeFile, INotifyPropertyChanged
{
private bool _isSelected;
public string Name { get; set; }
public List<ITreeFile> Files { get; set; }
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = false;
OnPropertyChanged();
}
}
public bool IsAdded { get; set; }
public bool IsRemoved { get; set; }
public FileDiff FileDiff { get; set; }
public Type GetTreeType { get { return this.GetType(); } }
public bool IsExpanded { get; set; }
public bool IsSelectable { get; set; }
public long Added { get; set; }
public long Removed { get; set; }
public TreeDirectory(string name)
{
Name = name;
Files = new List<ITreeFile>();
FileDiff = null;
IsSelectable = false;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} | mit | C# |
43fc33118f1daf54736f4e941bf3002caea78aa7 | tidy up | quezlatch/Binky | Binky/Cache.cs | Binky/Cache.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Binky
{
public static class Jobby
{
}
public sealed class Cache<TKey, TValue> : IDisposable
{
int _isProcessingTick;
readonly ConcurrentDictionary<TKey, Item> _dictionary;
readonly Timer _timer;
readonly Func<TKey, TValue> _getUpdateValue;
public Cache(Func<TKey, TValue> getUpdateValue, TimeSpan every, TimeSpan begin, TKey[] keys)
{
var kvp = from key in keys select new KeyValuePair<TKey, Item>(key, Item.New());
_dictionary = new ConcurrentDictionary<TKey, Item>(kvp);
_getUpdateValue = getUpdateValue;
_timer = new Timer(Tick, null, begin, every);
}
public TValue Get(TKey key) => _dictionary.GetOrAdd(key, _ => Item.New()).Completion.Task.Result;
void Tick(object state)
{
if (Interlocked.CompareExchange(ref _isProcessingTick, 1, 0) == 0)
try
{
ThreadSafeTick();
}
finally
{
Interlocked.Exchange(ref _isProcessingTick, 0);
}
}
void ThreadSafeTick()
{
foreach (var kvp in _dictionary)
{
var key = kvp.Key;
var item = kvp.Value;
Task.Run(() =>
{
var result = _getUpdateValue(key);
if (item.Completion.Task.Status == TaskStatus.RanToCompletion)
{
item.Completion = new TaskCompletionSource<TValue>();
}
item.Completion.SetResult(result);
});
}
}
public void Dispose()
{
_timer.Dispose();
}
// is class not struct so we can mutate Completion
public class Item
{
public TaskCompletionSource<TValue> Completion;
public static Item New() => new Item
{
Completion = new TaskCompletionSource<TValue>()
};
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Binky
{
public sealed class Cache<TKey, TValue> : IDisposable
{
int Ticking;
readonly ConcurrentDictionary<TKey, Item> _dictionary;
readonly Timer _timer;
readonly Func<TKey, TValue> _getUpdateValue;
public Cache(Func<TKey, TValue> getUpdateValue, TimeSpan every, TimeSpan begin, TKey[] keys)
{
var kvp = from key in keys select new KeyValuePair<TKey, Item>(key, Item.New());
_dictionary = new ConcurrentDictionary<TKey, Item>(kvp);
_getUpdateValue = getUpdateValue;
_timer = new Timer(Tick, null, begin, every);
}
public TValue Get(TKey key) => _dictionary.GetOrAdd(key, _ => Item.New()).Completion.Task.Result;
void Tick(object state)
{
if (Interlocked.CompareExchange(ref Ticking, 1, 0) == 0)
try
{
ThreadSafeTick();
}
finally
{
Interlocked.Exchange(ref Ticking, 0);
}
}
void ThreadSafeTick()
{
foreach (var kvp in _dictionary)
{
var key = kvp.Key;
var item = kvp.Value;
Task.Run(() => _getUpdateValue(key)).ContinueWith(task =>
{
//TODO: probably some complicate concurrency stuff here...
if (item.Completion.Task.Status == TaskStatus.RanToCompletion)
{
item.Completion = new TaskCompletionSource<TValue>();
}
item.Completion.SetResult(task.Result);
});
}
}
public void Dispose()
{
_timer.Dispose();
}
// is class not struct so we can mutate Completion
public class Item
{
public TaskCompletionSource<TValue> Completion;
public static Item New() => new Item
{
Completion = new TaskCompletionSource<TValue>()
};
}
}
}
| mit | C# |
5fa6a9fbfc79f1e97e243754b3c3bb919041a66d | 添加一个 View 属性,该属性在用户控件的内部使用非常有价值。 :+1: | Zongsoft/Zongsoft.Web | src/Components/DataItemContainer.cs | src/Components/DataItemContainer.cs | using System;
using System.Collections.Generic;
using System.Web.UI;
namespace Zongsoft.Web.Controls
{
public class DataItemContainer<TOwner> : Literal, IDataItemContainer where TOwner : CompositeDataBoundControl
{
#region 成员字段
private TOwner _owner;
private object _dataItem;
private int _index;
private int _displayIndex;
#endregion
#region 构造函数
internal DataItemContainer(TOwner owner, object dataItem, int index, string tagName = null, string cssClass = "item") : this(owner, dataItem, index, index, tagName, cssClass)
{
}
internal DataItemContainer(TOwner owner, object dataItem, int index, int displayIndex, string tagName = null, string cssClass = "item") : base(tagName, cssClass)
{
if(owner == null)
throw new ArgumentNullException("owner");
_owner = owner;
_dataItem = dataItem;
_index = index;
_displayIndex = displayIndex;
}
#endregion
#region 公共属性
public TOwner Owner
{
get
{
return _owner;
}
}
/// <summary>
/// 获取当前数据容器所属的视图(用户控件或页面)。
/// </summary>
public TemplateControl View
{
get
{
if(_owner == null)
return null;
return _owner.TemplateControl;
}
}
public object Model
{
get
{
var page = this.Page as System.Web.Mvc.ViewPage;
return page == null ? null : page.Model;
}
}
public object DataSource
{
get
{
return _owner.DataSource;
}
}
public object DataItem
{
get
{
return _dataItem;
}
}
public int Index
{
get
{
return _index;
}
}
public int DisplayIndex
{
get
{
return _displayIndex;
}
}
#endregion
#region 重写属性
public override Control Parent
{
get
{
return base.Parent ?? _owner.Parent;
}
}
public override Page Page
{
get
{
if(base.Page != null)
return base.Page;
return this.Parent == null ? _owner.Page : this.Parent.Page;
}
set
{
base.Page = value;
}
}
#endregion
#region 显式实现
int IDataItemContainer.DataItemIndex
{
get
{
return _index;
}
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Web.UI;
namespace Zongsoft.Web.Controls
{
public class DataItemContainer<TOwner> : Literal, IDataItemContainer where TOwner : CompositeDataBoundControl
{
#region 成员字段
private TOwner _owner;
private object _dataItem;
private int _index;
private int _displayIndex;
#endregion
#region 构造函数
internal DataItemContainer(TOwner owner, object dataItem, int index, string tagName = null, string cssClass = "item") : this(owner, dataItem, index, index, tagName, cssClass)
{
}
internal DataItemContainer(TOwner owner, object dataItem, int index, int displayIndex, string tagName = null, string cssClass = "item") : base(tagName, cssClass)
{
if(owner == null)
throw new ArgumentNullException("owner");
_owner = owner;
_dataItem = dataItem;
_index = index;
_displayIndex = displayIndex;
}
#endregion
#region 公共属性
public TOwner Owner
{
get
{
return _owner;
}
}
public object Model
{
get
{
var page = this.Page as System.Web.Mvc.ViewPage;
return page == null ? null : page.Model;
}
}
public object DataSource
{
get
{
return _owner.DataSource;
}
}
public object DataItem
{
get
{
return _dataItem;
}
}
public int Index
{
get
{
return _index;
}
}
public int DisplayIndex
{
get
{
return _displayIndex;
}
}
#endregion
#region 重写属性
public override Control Parent
{
get
{
return base.Parent ?? _owner.Parent;
}
}
public override Page Page
{
get
{
if(base.Page != null)
return base.Page;
return this.Parent == null ? _owner.Page : this.Parent.Page;
}
set
{
base.Page = value;
}
}
#endregion
#region 显式实现
int IDataItemContainer.DataItemIndex
{
get
{
return _index;
}
}
#endregion
}
}
| lgpl-2.1 | C# |
b4e1b7c76a0644bb0abccd568d20bbfc48900f20 | Update copyright | nunit/nunit3-vs-adapter | src/NUnitTestAdapter/Properties/AssemblyInfo.cs | src/NUnitTestAdapter/Properties/AssemblyInfo.cs | // ****************************************************************
// Copyright (c) 2011 Charlie Poole. All rights reserved.
// ****************************************************************
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NUnit3TestAdapter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("NUnit Software")]
[assembly: AssemblyProduct("NUnit3TestAdapter")]
[assembly: AssemblyCopyright("Copyright © 2011-2016, Charlie Poole")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: Guid("c0aad5e4-b486-49bc-b3e8-31e01be6fefe")]
[assembly: AssemblyVersion("3.6.0.0")]
[assembly: AssemblyFileVersion("3.6.0.0")]
| // ****************************************************************
// Copyright (c) 2011 Charlie Poole. All rights reserved.
// ****************************************************************
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NUnit3TestAdapter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("NUnit Software")]
[assembly: AssemblyProduct("NUnit3TestAdapter")]
[assembly: AssemblyCopyright("Copyright © 2011-2016, NUnit Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: Guid("c0aad5e4-b486-49bc-b3e8-31e01be6fefe")]
[assembly: AssemblyVersion("3.6.0.0")]
[assembly: AssemblyFileVersion("3.6.0.0")]
| mit | C# |
9588cf302179f60a5ad81430caac0523d0509f0c | Make internals in MSTest2 visible for JustMock dll in lite version | telerik/JustMockLite | Telerik.JustMock.MSTest2.Tests/Properties/AssemblyInfo.cs | Telerik.JustMock.MSTest2.Tests/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("MigrateMSTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MigrateMSTest")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
#if LITE_EDITION
[assembly: InternalsVisibleTo("Telerik.JustMock")]
#endif | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("MigrateMSTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MigrateMSTest")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
f11b068dee2b58a0160c138cfcb811e6f18a2ec0 | Allow faster roll speed selection in "Barrel Roll" mod | peppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu | osu.Game.Rulesets.Osu/Mods/OsuModBarrelRoll.cs | osu.Game.Rulesets.Osu/Mods/OsuModBarrelRoll.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.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield, IApplicableToDrawableRuleset<OsuHitObject>
{
[SettingSource("Roll speed", "Rotations per minute")]
public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(0.5)
{
MinValue = 0.02,
MaxValue = 12,
Precision = 0.01,
};
[SettingSource("Direction", "The direction of rotation")]
public Bindable<RotationDirection> Direction { get; } = new Bindable<RotationDirection>(RotationDirection.Clockwise);
public override string Name => "Barrel Roll";
public override string Acronym => "BR";
public override string Description => "The whole playfield is on a wheel!";
public override double ScoreMultiplier => 1;
public override string SettingDescription => $"{SpinSpeed.Value} rpm {Direction.Value.GetDescription().ToLowerInvariant()}";
public void Update(Playfield playfield)
{
playfield.Rotation = (Direction.Value == RotationDirection.Counterclockwise ? -1 : 1) * 360 * (float)(playfield.Time.Current / 60000 * SpinSpeed.Value);
}
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
// scale the playfield to allow all hitobjects to stay within the visible region.
drawableRuleset.Playfield.Scale = new Vector2(OsuPlayfield.BASE_SIZE.Y / OsuPlayfield.BASE_SIZE.X);
}
}
}
| // 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.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModBarrelRoll : Mod, IUpdatableByPlayfield, IApplicableToDrawableRuleset<OsuHitObject>
{
[SettingSource("Roll speed", "Rotations per minute")]
public BindableNumber<double> SpinSpeed { get; } = new BindableDouble(0.5)
{
MinValue = 0.02,
MaxValue = 4,
Precision = 0.01,
};
[SettingSource("Direction", "The direction of rotation")]
public Bindable<RotationDirection> Direction { get; } = new Bindable<RotationDirection>(RotationDirection.Clockwise);
public override string Name => "Barrel Roll";
public override string Acronym => "BR";
public override string Description => "The whole playfield is on a wheel!";
public override double ScoreMultiplier => 1;
public override string SettingDescription => $"{SpinSpeed.Value} rpm {Direction.Value.GetDescription().ToLowerInvariant()}";
public void Update(Playfield playfield)
{
playfield.Rotation = (Direction.Value == RotationDirection.Counterclockwise ? -1 : 1) * 360 * (float)(playfield.Time.Current / 60000 * SpinSpeed.Value);
}
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
// scale the playfield to allow all hitobjects to stay within the visible region.
drawableRuleset.Playfield.Scale = new Vector2(OsuPlayfield.BASE_SIZE.Y / OsuPlayfield.BASE_SIZE.X);
}
}
}
| mit | C# |
46caab6310d74a0b3d7ba36a3edea53aca6b17b0 | Reorder arithmetic operation | ppy/osu,EVAST9919/osu,peppy/osu,Frontear/osuKyzer,2yangk23/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,naoey/osu,smoogipoo/osu,ZLima12/osu,EVAST9919/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,DrabWeb/osu,johnneijzen/osu,johnneijzen/osu,ZLima12/osu,naoey/osu,smoogipooo/osu,NeoAdonis/osu,naoey/osu,peppy/osu-new,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,Nabile-Rahmani/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu | osu.Game.Rulesets.Mania/Mods/ManiaModMirror.cs | osu.Game.Rulesets.Mania/Mods/ManiaModMirror.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using System.Linq;
namespace osu.Game.Rulesets.Mania.Mods
{
public class ManiaModMirror : Mod, IApplicableToRulesetContainer<ManiaHitObject>
{
public override string Name => "Mirror";
public override string ShortenedName => "MR";
public override ModType Type => ModType.Special;
public override double ScoreMultiplier => 1;
public override bool Ranked => true;
public void ApplyToRulesetContainer(RulesetContainer<ManiaHitObject> rulesetContainer)
{
var availableColumns = ((ManiaRulesetContainer)rulesetContainer).Beatmap.TotalColumns;
rulesetContainer.Objects.OfType<ManiaHitObject>().ForEach(h => h.Column = availableColumns - 1 - h.Column);
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using System.Linq;
namespace osu.Game.Rulesets.Mania.Mods
{
public class ManiaModMirror : Mod, IApplicableToRulesetContainer<ManiaHitObject>
{
public override string Name => "Mirror";
public override string ShortenedName => "MR";
public override ModType Type => ModType.Special;
public override double ScoreMultiplier => 1;
public override bool Ranked => true;
public void ApplyToRulesetContainer(RulesetContainer<ManiaHitObject> rulesetContainer)
{
var availableColumns = ((ManiaRulesetContainer)rulesetContainer).Beatmap.TotalColumns;
rulesetContainer.Objects.OfType<ManiaHitObject>().ForEach(h => h.Column = -h.Column + availableColumns - 1);
}
}
}
| mit | C# |
8efd888b134cfbd8019630cfd8903a4fcbb2b65b | remove debug | losetear/nmap,linbozhang/polygon-map-unity | demo/Assets/Camera.cs | demo/Assets/Camera.cs | using UnityEngine;
using System.Collections;
using Assets.Map;
public class Camera : MonoBehaviour
{
public Map Map;
float _mousePosX;
float _mousePosY;
float _scrollSpeed = 0.2f;
float _zoomSpeed = 1f;
Vector2 _mouseLeftClick;
void Update()
{
float deltaX = Input.mousePosition.x - _mousePosX;
float deltaY = Input.mousePosition.y - _mousePosY;
_mousePosX = Input.mousePosition.x;
_mousePosY = Input.mousePosition.y;
if (Input.GetMouseButton(0))
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
_mouseLeftClick = hit.point;
Map.Click(_mouseLeftClick);
}
}
if (Input.GetMouseButton(1))
{
var newX = Mathf.Clamp(transform.parent.position.x + deltaX * _scrollSpeed, 0, Map.Width);
var newY = Mathf.Clamp(transform.parent.position.y + deltaY * _scrollSpeed, 0, Map.Height);
transform.parent.position = new Vector3(newX, newY, transform.parent.position.z);
}
if (Input.GetAxis("Mouse ScrollWheel") < 0 && transform.parent.localPosition.z > -20)
{
transform.parent.Translate(new Vector3(0, 0, -_zoomSpeed));
}
if (Input.GetAxis("Mouse ScrollWheel") > 0 && transform.parent.localPosition.z < -5)
{
transform.parent.Translate(new Vector3(0, 0, _zoomSpeed));
}
}
}
| using UnityEngine;
using System.Collections;
using Assets.Map;
public class Camera : MonoBehaviour
{
public Map Map;
float _mousePosX;
float _mousePosY;
float _scrollSpeed = 0.2f;
float _zoomSpeed = 1f;
Vector2 _mouseLeftClick;
void Update()
{
float deltaX = Input.mousePosition.x - _mousePosX;
float deltaY = Input.mousePosition.y - _mousePosY;
_mousePosX = Input.mousePosition.x;
_mousePosY = Input.mousePosition.y;
if (Input.GetMouseButton(0))
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
_mouseLeftClick = hit.point;
Map.Click(_mouseLeftClick);
}
}
if (Input.GetMouseButton(1))
{
Debug.Log(deltaX);
var newX = Mathf.Clamp(transform.parent.position.x + deltaX * _scrollSpeed, 0, Map.Width);
var newY = Mathf.Clamp(transform.parent.position.y + deltaY * _scrollSpeed, 0, Map.Height);
transform.parent.position = new Vector3(newX, newY, transform.parent.position.z);
}
if (Input.GetAxis("Mouse ScrollWheel") < 0 && transform.parent.localPosition.z > -20)
{
transform.parent.Translate(new Vector3(0, 0, -_zoomSpeed));
}
if (Input.GetAxis("Mouse ScrollWheel") > 0 && transform.parent.localPosition.z < -5)
{
transform.parent.Translate(new Vector3(0, 0, _zoomSpeed));
}
}
}
| mit | C# |
af5d06384ece596659efb6db4ee71a8dfb9e7024 | Rephrase culture-neutral number format helper so that it can successfully compile against both the full .NET Framework and .NET Core. | fixie/fixie | src/Fixie.Tests/TestExtensions.cs | src/Fixie.Tests/TestExtensions.cs | namespace Fixie.Tests
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Fixie.Execution;
public static class TestExtensions
{
const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static MethodInfo GetInstanceMethod(this Type type, string methodName)
{
return type.GetMethod(methodName, InstanceMethods);
}
public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type)
{
return type.GetMethods(InstanceMethods);
}
public static IEnumerable<string> Lines(this RedirectedConsole console)
{
return console.Output.Lines();
}
public static IEnumerable<string> Lines(this string multiline)
{
var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
while (lines.Count > 0 && lines[lines.Count-1] == "")
lines.RemoveAt(lines.Count-1);
return lines;
}
public static string CleanStackTraceLineNumbers(this string stackTrace)
{
//Avoid brittle assertion introduced by stack trace line numbers.
return Regex.Replace(stackTrace, @":line \d+", ":line #");
}
public static string CleanDuration(this string output)
{
//Avoid brittle assertion introduced by test duration.
var decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds");
}
}
} | namespace Fixie.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using Fixie.Execution;
public static class TestExtensions
{
const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static MethodInfo GetInstanceMethod(this Type type, string methodName)
{
return type.GetMethod(methodName, InstanceMethods);
}
public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type)
{
return type.GetMethods(InstanceMethods);
}
public static IEnumerable<string> Lines(this RedirectedConsole console)
{
return console.Output.Lines();
}
public static IEnumerable<string> Lines(this string multiline)
{
var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
while (lines.Count > 0 && lines[lines.Count-1] == "")
lines.RemoveAt(lines.Count-1);
return lines;
}
public static string CleanStackTraceLineNumbers(this string stackTrace)
{
//Avoid brittle assertion introduced by stack trace line numbers.
return Regex.Replace(stackTrace, @":line \d+", ":line #");
}
public static string CleanDuration(this string output)
{
//Avoid brittle assertion introduced by test duration.
var decimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds");
}
}
} | mit | C# |
fe320a2574da0a1b927ac8c58b66b37324e36f09 | improve sample console app | denisroschinenko/vcap-client-v2 | src/IronFoundryConsole/Program.cs | src/IronFoundryConsole/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IronFoundry.VcapClient.V2;
using IronFoundry.VcapClient.V2.Models;
namespace IronFoundryConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter CFv2 data:");
Console.WriteLine("Url:");
var url = Console.ReadLine();
Console.WriteLine("Login:");
var login = Console.ReadLine();
Console.WriteLine("Password");
var password = Console.ReadLine();
var client = new VcapClient(new Uri(url), new StableDataStorage());
client.Login(login ?? "micro@vcap.me", password ?? "micr0@micr0");
Console.WriteLine("--- Organizations: ---");
foreach (var organization in client.GetOrganizations())
{
Console.WriteLine(organization.Entity.Name);
}
Console.WriteLine();
Console.WriteLine("--- Spaces: ---");
foreach (var space in client.GetSpaces())
{
Console.WriteLine(space.Entity.Name);
}
Console.WriteLine();
Console.WriteLine("--- Apps: ---");
foreach (var app in client.GetApplications())
{
Console.WriteLine(app.Entity.Name);
}
Console.WriteLine();
Console.WriteLine("Everything is OK.");
Console.ReadLine();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IronFoundry.VcapClient.V2;
using IronFoundry.VcapClient.V2.Models;
namespace IronFoundryConsole
{
class Program
{
static void Main(string[] args)
{
VcapClient client = new VcapClient(new Uri("http://api.192.168.1.77.xip.io"), new StableDataStorage());
client.Login("micro@vcap.me", "micr0@micr0");
//client.GetApplication("caldecott");
var application = new Application()
{
Name = "Testtesttest",
SpaceGuid = Guid.Parse("96400672-c897-4545-aadd-79181833ca6a"),
StackGuid = Guid.Parse("2becc7fd-db45-461e-9d94-8dc1243e1bf7"),
NumberInstance = 1,
Memory = 128,
DiskQuota = 1024
};
//client.PushApplication(application, @"d:\MvcAltorosApplication\MvcAltorosApplication ");
Console.ReadLine();
}
}
}
| apache-2.0 | C# |
43da36bb32e386595d43f9702aa97d437f3e04c0 | Work on robot software - #13 | henkmollema/MindstormR,henkmollema/MindstormR,henkmollema/MindstormR | src/MindstormR.EV3/Main.cs | src/MindstormR.EV3/Main.cs | using System;
using System.Diagnostics;
using MonoBrickFirmware;
using MonoBrickFirmware.Display.Dialogs;
using MonoBrickFirmware.Display;
using MonoBrickFirmware.Movement;
using System.Threading;
using System.Net;
namespace MonoBrickHelloWorld
{
class MainClass
{
private static int _id;
public static void Main(string[] args)
{
try
{
const string baseUrl = "http://test.henkmollema.nl/robot/";
var sw = Stopwatch.StartNew();
var client = new WebClient();
string s = client.DownloadString(baseUrl + "login");
sw.Stop();
if (!int.TryParse(s, out _id))
{
Info("Invalid ID from the webserver: '{0}'. ({1:n2}s)", true, "Error", s, sw.Elapsed.TotalSeconds);
return;
}
Info("Robot logged in. ID: {0}. ({1:n2}s)", _id, sw.Elapsed.TotalSeconds);
for (int i = 0; i < 5; i++)
{
sw.Restart();
string data = client.DownloadString(baseUrl + 1020 + "/command");
sw.Stop();
Info("Command from robot 1020: '{0}'. ({1:n2})", data, sw.Elapsed.TotalSeconds);
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
private static void Info(string format, params object[] arg)
{
new InfoDialog(string.Format(format, arg), true).Show();
}
private static void Info(string format, bool waitForOk, params object[] arg)
{
new InfoDialog(string.Format(format, arg), waitForOk).Show();
}
private static void Info(string format, bool waitForOk, string title, params object[] arg)
{
new InfoDialog(string.Format(format, arg), waitForOk, title).Show();
}
}
} | using System;
using MonoBrickFirmware;
using MonoBrickFirmware.Display.Dialogs;
using MonoBrickFirmware.Display;
using MonoBrickFirmware.Movement;
using System.Threading;
using System.Net;
namespace MonoBrickHelloWorld
{
class MainClass
{
private static int _id;
public static void Main(string[] args)
{
try
{
string url = "http://test.henkmollema.nl/robot/login";
WebClient client = new WebClient();
string s = client.DownloadString(url);
if (!int.TryParse(s, out _id))
{
new InfoDialog(string.Format("Invalid ID from the webserver: '{0}'.", s), true, "Error").Show();
return;
}
new InfoDialog("Robot id: " + _id, true).Show();
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
}
} | mit | C# |
ac8634448e72602545e0c886403ab185b89d75d6 | make command line host non blocking | lukaskabrt/Orchard2,lukaskabrt/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,yiji/Orchard2,alexbocharov/Orchard2,jtkech/Orchard2,petedavis/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,alexbocharov/Orchard2,xkproject/Orchard2,alexbocharov/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,xkproject/Orchard2,yiji/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,yiji/Orchard2,lukaskabrt/Orchard2,jtkech/Orchard2,jtkech/Orchard2 | src/Orchard.Web/Program.cs | src/Orchard.Web/Program.cs | using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(currentDirectory)
.UseWebRoot(currentDirectory)
.UseStartup<Startup>()
.Build();
using (host)
{
host.Start();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
} | using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(currentDirectory)
.UseWebRoot(currentDirectory)
.UseStartup<Startup>()
.Build();
using (host)
{
host.Run();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
} | bsd-3-clause | C# |
e878ebfc2f00ce48bdfe6710a9d739a8430bb43d | Update Back | IanEarnest/Unity-GUI | Assets/Back.cs | Assets/Back.cs | using UnityEngine;
using System; // system is only used on standalone.
using System.Collections;
public class Back : MonoBehaviour {
Rect backRect = new Rect(Screen.width-80, Screen.height-50, 80, 50);
public GameObject welcomeScript;
static bool isActive;
void Start(){
welcomeScript = new GameObject("Script1");
welcomeScript.AddComponent ("Welcome");
welcomeScript.SetActive (isActive);
}
void OnGUI(){
string menuText = "";
if (!isActive) {
menuText = "Show Menu";
}
if (isActive) {
menuText = "Hide Menu";
}
GUI.BeginGroup (backRect);
if(GUILayout.Button("Exit level")){
Application.LoadLevel("Welcome");
}
if(GUILayout.Button(menuText)){
isActive = !isActive;
welcomeScript.SetActive (isActive);
}
GUI.EndGroup ();
}
}
| using UnityEngine;
using System; // system is only used on standalone.
using System.Collections;
public class Back : MonoBehaviour {
Rect backRect = new Rect(Screen.width-70, Screen.height-30, 70, 30);
Rect backRect2 = new Rect(Screen.width-70, Screen.height-60, 70, 30);
public GameObject welcomeScript;
static bool isActive;
void Start(){
welcomeScript = new GameObject("Script1");
welcomeScript.AddComponent ("Welcome");
welcomeScript.SetActive (isActive);
}
void OnGUI(){
if(GUI.Button(backRect, "Exit level")){
Application.LoadLevel("Welcome");
}
if(GUI.Button(backRect2, "Show menu")){
isActive = !isActive;
welcomeScript.SetActive (isActive);
}
}
}
| mit | C# |
050dcc4f7aadb595d36e06e45a033bc811709bfd | Fix load | H-POPS/Slingshot | CustomFlatRide/FlatRideScript/Slingshot.cs | CustomFlatRide/FlatRideScript/Slingshot.cs |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slingshot : FlatRide
{
public bool getOut;
public SpringJoint UpperLeft;
public SpringJoint UpperRight;
public SpringJoint Bottom;
public float speedDown = .15f;
public float strenghtDown = 20;
public float springVar = 1.5f;
new void Start()
{
UpperRight.spring = 0;
UpperLeft.spring = 0;
Bottom.connectedBody.isKinematic = true;
getOut = true;
}
public override void onStartRide()
{
getOut = false;
base.onStartRide();
foreach (MeshCollider coll in GetComponentsInChildren<MeshCollider>())
{
coll.convex = true;
}
StartCoroutine(Ride());
}
IEnumerator Ride()
{
Bottom.connectedBody.isKinematic = false;
Bottom.spring = 0;
Bottom.damper = 0;
UpperRight.spring = springVar;
UpperLeft.spring = springVar;
yield return new WaitForSeconds(10);
while (Vector3.Distance(Bottom.anchor + Bottom.transform.position, Bottom.connectedBody.transform.position + Bottom.connectedAnchor) > .1f)
{
Bottom.spring = Mathf.Lerp(Bottom.spring, strenghtDown, speedDown / 2 * Time.deltaTime);
Bottom.damper = Mathf.Lerp(Bottom.damper, strenghtDown * 1.4f , speedDown / 2 * Time.deltaTime); ;
UpperRight.spring = Mathf.Lerp(UpperRight.spring, 0, speedDown * Time.deltaTime); ;
UpperLeft.spring = Mathf.Lerp(UpperLeft.spring, 0, speedDown * Time.deltaTime); ;
yield return null;
}
UpperRight.spring = 0;
UpperLeft.spring = 0;
yield return new WaitForSeconds(1);
Bottom.connectedBody.isKinematic = true;
getOut = true;
}
public override void tick(StationController stationController)
{
}
public override bool shouldLetGuestsOut()
{
return getOut;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slingshot : FlatRide
{
public bool getOut;
public SpringJoint UpperLeft;
public SpringJoint UpperRight;
public SpringJoint Bottom;
public float speedDown = .15f;
public float strenghtDown = 20;
public float springVar = 1.5f;
public override void onStartRide()
{
getOut = false;
base.onStartRide();
foreach (MeshCollider coll in GetComponentsInChildren<MeshCollider>())
{
coll.convex = true;
}
StartCoroutine(Ride());
}
IEnumerator Ride()
{
Bottom.connectedBody.isKinematic = false;
Bottom.spring = 0;
Bottom.damper = 0;
UpperRight.spring = springVar;
UpperLeft.spring = springVar;
yield return new WaitForSeconds(10);
while (Vector3.Distance(Bottom.anchor + Bottom.transform.position, Bottom.connectedBody.transform.position + Bottom.connectedAnchor) > .1f)
{
Bottom.spring = Mathf.Lerp(Bottom.spring, strenghtDown, speedDown / 2 * Time.deltaTime);
Bottom.damper = Mathf.Lerp(Bottom.damper, strenghtDown * 1.4f , speedDown / 2 * Time.deltaTime); ;
UpperRight.spring = Mathf.Lerp(UpperRight.spring, 0, speedDown * Time.deltaTime); ;
UpperLeft.spring = Mathf.Lerp(UpperLeft.spring, 0, speedDown * Time.deltaTime); ;
yield return null;
}
UpperRight.spring = 0;
UpperLeft.spring = 0;
yield return new WaitForSeconds(1);
Bottom.connectedBody.isKinematic = true;
getOut = true;
}
public override void tick(StationController stationController)
{
}
public override bool shouldLetGuestsOut()
{
return getOut;
}
}
| mit | C# |
d12c44c21e7421ce499a4622527a8c207b757122 | bump version number | charri/Font-Awesome-WPF,punker76/Font-Awesome-WPF | src/FontAwesome.WPF/Properties/AssemblyInfo.cs | src/FontAwesome.WPF/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Markup;
[assembly: AssemblyTitle("Font Awesome WPF")]
[assembly: AssemblyDescription("Wpf components for the iconic font and CSS toolkit Font-Awesome")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("charri")]
[assembly: AssemblyProduct("FontAwesome.WPF")]
[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("c1ef07d8-c739-421a-a811-278c9341677c")]
// Version: First three numbers is FontAwesome version, the last number specifies code revision
//
[assembly: AssemblyVersion("4.5.0.*")]
[assembly: AssemblyFileVersion("4.5.0.7")]
[assembly: XmlnsPrefix("http://schemas.fontawesome.io/icons/", "fa")]
[assembly: XmlnsDefinition("http://schemas.fontawesome.io/icons/", "FontAwesome.WPF")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Markup;
[assembly: AssemblyTitle("Font Awesome WPF")]
[assembly: AssemblyDescription("Wpf components for the iconic font and CSS toolkit Font-Awesome")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("charri")]
[assembly: AssemblyProduct("FontAwesome.WPF")]
[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("c1ef07d8-c739-421a-a811-278c9341677c")]
// Version: First three numbers is FontAwesome version, the last number specifies code revision
//
[assembly: AssemblyVersion("4.4.0.*")]
[assembly: AssemblyFileVersion("4.4.0.6")]
[assembly: XmlnsPrefix("http://schemas.fontawesome.io/icons/", "fa")]
[assembly: XmlnsDefinition("http://schemas.fontawesome.io/icons/", "FontAwesome.WPF")] | mit | C# |
4bc2c3ecd86288b95b6a778666edc8e9d01c2374 | Fix interface members visibility (#2094) | JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm | ArchiSteamFarm/Helpers/ICrossProcessSemaphore.cs | ArchiSteamFarm/Helpers/ICrossProcessSemaphore.cs | // _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
// |
// Copyright 2015-2020 Łukasz "JustArchi" Domeradzki
// Contact: JustArchi@JustArchi.net
// |
// 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.Threading.Tasks;
using JetBrains.Annotations;
namespace ArchiSteamFarm.Helpers {
[PublicAPI]
public interface ICrossProcessSemaphore {
void Release();
Task WaitAsync();
Task<bool> WaitAsync(int millisecondsTimeout);
}
}
| // _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
// |
// Copyright 2015-2020 Łukasz "JustArchi" Domeradzki
// Contact: JustArchi@JustArchi.net
// |
// 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.Threading.Tasks;
using JetBrains.Annotations;
namespace ArchiSteamFarm.Helpers {
[PublicAPI]
public interface ICrossProcessSemaphore {
internal void Release();
internal Task WaitAsync();
internal Task<bool> WaitAsync(int millisecondsTimeout);
}
}
| apache-2.0 | C# |
a5eea9a6c57336b3f798179f8a1cac8240d92dd4 | Change "Sidebar" "KeepOpenWithModifierKey" option default | danielchalmers/DesktopWidgets | DesktopWidgets/Widgets/Sidebar/Settings.cs | DesktopWidgets/Widgets/Sidebar/Settings.cs | using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Sidebar
{
public class Settings : WidgetSettingsBase
{
[DisplayName("Shortcuts")]
public ObservableCollection<Shortcut> Shortcuts { get; set; }
[Category("Shortcut Style")]
[DisplayName("Icon Position")]
public IconPosition IconPosition { get; set; } = IconPosition.Left;
[Category("Shortcut Style")]
[DisplayName("Tooltip Type")]
public ToolTipType ToolTipType { get; set; } = ToolTipType.None;
[Category("Shortcut Style")]
[DisplayName("Horizontal Alignment")]
public HorizontalAlignment ButtonHorizontalAlignment { get; set; } = HorizontalAlignment.Center;
[Category("Shortcut Style")]
[DisplayName("Vertical Alignment")]
public VerticalAlignment ButtonVerticalAlignment { get; set; } = VerticalAlignment.Center;
[Category("Shortcut Style")]
[DisplayName("Icon Scaling Mode")]
public ImageScalingMode IconScalingMode { get; set; } = ImageScalingMode.LowQuality;
[Category("Shortcut Style")]
[DisplayName("Content Mode")]
public ShortcutContentMode ShortcutContentMode { get; set; } = ShortcutContentMode.Both;
[Category("Style")]
[DisplayName("Orientation")]
public ShortcutOrientation ShortcutOrientation { get; set; } = ShortcutOrientation.Vertical;
[Category("Shortcut Style")]
[DisplayName("Height")]
public int ButtonHeight { get; set; } = 32;
[Category("Behavior (Hideable)")]
[DisplayName("Hide on Shortcut Launch")]
public bool HideOnExecute { get; set; } = true;
[Category("General")]
[DisplayName("Allow Drag Drop Files")]
public bool AllowDropFiles { get; set; } = true;
[DisplayName("Default Shortcuts Mode")]
public DefaultShortcutsMode DefaultShortcutsMode { get; set; } = DefaultShortcutsMode.Preset;
[Category("General")]
[DisplayName("Parse Shortcut Files")]
public bool ParseShortcutFiles { get; set; } = false;
[Category("General")]
[DisplayName("Enable Icon Cache")]
public bool UseIconCache { get; set; } = true;
[Category("Behavior")]
[DisplayName("Keep Open With Modifier Key")]
public ModifierKeys KeepOpenWithModifierKey { get; set; } = ModifierKeys.Control;
}
} | using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Sidebar
{
public class Settings : WidgetSettingsBase
{
[DisplayName("Shortcuts")]
public ObservableCollection<Shortcut> Shortcuts { get; set; }
[Category("Shortcut Style")]
[DisplayName("Icon Position")]
public IconPosition IconPosition { get; set; } = IconPosition.Left;
[Category("Shortcut Style")]
[DisplayName("Tooltip Type")]
public ToolTipType ToolTipType { get; set; } = ToolTipType.None;
[Category("Shortcut Style")]
[DisplayName("Horizontal Alignment")]
public HorizontalAlignment ButtonHorizontalAlignment { get; set; } = HorizontalAlignment.Center;
[Category("Shortcut Style")]
[DisplayName("Vertical Alignment")]
public VerticalAlignment ButtonVerticalAlignment { get; set; } = VerticalAlignment.Center;
[Category("Shortcut Style")]
[DisplayName("Icon Scaling Mode")]
public ImageScalingMode IconScalingMode { get; set; } = ImageScalingMode.LowQuality;
[Category("Shortcut Style")]
[DisplayName("Content Mode")]
public ShortcutContentMode ShortcutContentMode { get; set; } = ShortcutContentMode.Both;
[Category("Style")]
[DisplayName("Orientation")]
public ShortcutOrientation ShortcutOrientation { get; set; } = ShortcutOrientation.Vertical;
[Category("Shortcut Style")]
[DisplayName("Height")]
public int ButtonHeight { get; set; } = 32;
[Category("Behavior (Hideable)")]
[DisplayName("Hide on Shortcut Launch")]
public bool HideOnExecute { get; set; } = true;
[Category("General")]
[DisplayName("Allow Drag Drop Files")]
public bool AllowDropFiles { get; set; } = true;
[DisplayName("Default Shortcuts Mode")]
public DefaultShortcutsMode DefaultShortcutsMode { get; set; } = DefaultShortcutsMode.Preset;
[Category("General")]
[DisplayName("Parse Shortcut Files")]
public bool ParseShortcutFiles { get; set; } = false;
[Category("General")]
[DisplayName("Enable Icon Cache")]
public bool UseIconCache { get; set; } = true;
[Category("Behavior")]
[DisplayName("Keep Open With Modifier Key")]
public ModifierKeys KeepOpenWithModifierKey { get; set; } = ModifierKeys.Shift;
}
} | apache-2.0 | C# |
26b75add730a27519cdcc5ede638682be4d760e2 | Update DiscogsArtist.cs | David-Desmaisons/DiscogsClient | DiscogsClient/Data/Result/DiscogsArtist.cs | DiscogsClient/Data/Result/DiscogsArtist.cs | namespace DiscogsClient.Data.Result
{
public class DiscogsArtist : DiscogsEntity
{
public string name { get; set; }
public string realname { get; set; }
public DiscogsImage[] images { get; set; }
public DiscogsGroupOrBandMember[] members { get; set; }
public DiscogsGroupOrBandMember[] groups { get; set; }
public string[] urls { get; set; }
public string[] namevariations { get; set; }
public string profile { get; set; }
public string releases_url { get; set; }
public string resource_url { get; set; }
public string uri { get; set; }
public string data_quality { get; set; }
}
}
| namespace DiscogsClient.Data.Result
{
public class DiscogsArtist : DiscogsEntity
{
public string name { get; set; }
public DiscogsImage[] images { get; set; }
public DiscogsGroupOrBandMember[] members { get; set; }
public DiscogsGroupOrBandMember[] groups { get; set; }
public string[] urls { get; set; }
public string[] namevariations { get; set; }
public string profile { get; set; }
public string releases_url { get; set; }
public string resource_url { get; set; }
public string uri { get; set; }
public string data_quality { get; set; }
}
}
| mit | C# |
dbc856c632b83eb1580a0189caec821fd5c70851 | Fix build issue | shuhari/Shuhari.Framework | Shuhari.Framework.Common/IO/StreamDecorator.cs | Shuhari.Framework.Common/IO/StreamDecorator.cs | using System.IO;
using Shuhari.Framework.Utils;
namespace Shuhari.Framework.IO
{
/// <summary>
/// Decorate stream, delegate actual work to inner stream, but can also be overriden.
/// Useful for Web filters and so on.
/// </summary>
public class StreamDecorator : Stream
{
/// <summary>
/// Initialize
/// </summary>
/// <param name="innerStream"></param>
public StreamDecorator(Stream innerStream)
{
Expect.IsNotNull(innerStream, nameof(innerStream));
InnerStream = innerStream;
}
/// <summary>
/// Inner stream
/// </summary>
public Stream InnerStream { get; }
/// <inheritdoc />
public override bool CanRead => InnerStream.CanRead;
/// <inheritdoc />
public override bool CanSeek => InnerStream.CanSeek;
/// <inheritdoc />
public override bool CanWrite => InnerStream.CanWrite;
/// <inheritdoc />
public override long Length => InnerStream.Length;
/// <inheritdoc />
public override long Position
{
get { return InnerStream.Position; }
set { InnerStream.Position = value; }
}
/// <inheritdoc />
public override void Flush()
{
InnerStream.Flush();
}
/// <inheritdoc />
public override long Seek(long offset, SeekOrigin origin)
{
return InnerStream.Seek(offset, origin);
}
/// <inheritdoc />
public override void SetLength(long value)
{
InnerStream.SetLength(value);
}
/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count)
{
return InnerStream.Read(buffer, offset, count);
}
/// <inheritdoc />
public override void Write(byte[] buffer, int offset, int count)
{
InnerStream.Write(buffer, offset, count);
}
}
}
| using System.IO;
using Shuhari.Framework.Utils;
namespace Shuhari.Framework.IO
{
/// <summary>
/// Decorate stream, delegate actual work to inner stream, but can also be overriden.
/// Useful for Web filters and so on.
/// </summary>
public class StreamDecorator : Stream
{
/// <summary>
/// Initialize
/// </summary>
/// <param name="innerStream"></param>
public StreamDecorator(Stream innerStream)
{
Expect.IsNotNull(innerStream, nameof(innerStream));
InnerStream = innerStream;
}
/// <summary>
/// Inner stream
/// </summary>
public Stream InnerStream { get; }
/// <inheritdoc />
public override bool CanRead => InnerStream.CanRead;
/// <inheritdoc />
public override bool CanSeek => InnerStream.CanSeek;
/// <inheritdoc />
public override bool CanWrite => InnerStream.CanWrite;
/// <inheritdoc />
public override long Length => InnerStream.Length;
/// <inheritdoc />
public override long Position
{
get => InnerStream.Position;
set => InnerStream.Position = value;
}
/// <inheritdoc />
public override void Flush()
{
InnerStream.Flush();
}
/// <inheritdoc />
public override long Seek(long offset, SeekOrigin origin)
{
return InnerStream.Seek(offset, origin);
}
/// <inheritdoc />
public override void SetLength(long value)
{
InnerStream.SetLength(value);
}
/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count)
{
return InnerStream.Read(buffer, offset, count);
}
/// <inheritdoc />
public override void Write(byte[] buffer, int offset, int count)
{
InnerStream.Write(buffer, offset, count);
}
}
}
| apache-2.0 | C# |
d61ece3a85fb60af9701d0112471b1d9c346df9e | Use extension methods | hahoyer/reni.cs,hahoyer/reni.cs,hahoyer/reni.cs | src/ReniLanguagePackage/ReniLanguagePackage.cs | src/ReniLanguagePackage/ReniLanguagePackage.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using JetBrains.Annotations;
using Microsoft.VisualStudio.Shell;
using ReniUI.Formatting;
namespace HoyerWare.ReniLanguagePackage
{
[ProvideService(typeof(ReniService), ServiceName = "Reni Language Service")]
[ProvideLanguageService(typeof(ReniService), Name, 106)]
[ProvideLanguageExtension(typeof(ReniService), ".reni")]
[Guid("F4FB62CF-3E45-4920-9721-89099113477E")]
[ProvideLanguageEditorOptionPage(typeof(Properties), Name, "Advanced", "", "100")]
[UsedImplicitly]
public sealed class ReniLanguagePackage : Package
{
const string Name = "Reni";
protected override void Initialize()
{
base.Initialize();
var serviceContainer = this as IServiceContainer;
var langService = new ReniService();
langService.SetSite(this);
serviceContainer.AddService(typeof(ReniService), langService, true);
Application.Idle += OnIdle;
}
void OnIdle(object sender, EventArgs e)
=> (GetService(typeof(ReniService)) as ReniService)?.OnIdle(true);
internal IFormatter CreateFormattingProvider()
{
var pd = (Properties) GetDialogPage(typeof(Properties));
return new Configuration
{
MaxLineLength = pd.MaxLineLength,
EmptyLineLimit = pd.EmptyLineLimit
}.
Create();
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using JetBrains.Annotations;
using Microsoft.VisualStudio.Shell;
using ReniUI.Formatting;
namespace HoyerWare.ReniLanguagePackage
{
[ProvideService(typeof(ReniService), ServiceName = "Reni Language Service")]
[ProvideLanguageService(typeof(ReniService), Name, 106)]
[ProvideLanguageExtension(typeof(ReniService), ".reni")]
[Guid("F4FB62CF-3E45-4920-9721-89099113477E")]
[ProvideLanguageEditorOptionPage(typeof(Properties), Name, "Advanced", "", "100")]
[UsedImplicitly]
public sealed class ReniLanguagePackage : Package
{
const string Name = "Reni";
protected override void Initialize()
{
base.Initialize();
var serviceContainer = this as IServiceContainer;
var langService = new ReniService();
langService.SetSite(this);
serviceContainer.AddService(typeof(ReniService), langService, true);
Application.Idle += OnIdle;
}
void OnIdle(object sender, EventArgs e)
=> (GetService(typeof(ReniService)) as ReniService)?.OnIdle(true);
internal IFormatter CreateFormattingProvider()
{
var pd = (Properties) GetDialogPage(typeof(Properties));
return FormatterExtension.Create
(
new Configuration
{
MaxLineLength = pd.MaxLineLength,
EmptyLineLimit = pd.EmptyLineLimit
}
);
}
}
} | mit | C# |
072394f8ca4e9bf653e4b0c4d6453c4be6a88742 | Fix issue in IAttributeRegistry.GetAttribute<T> | vasily-kirichenko/SharpYaml,SiliconStudio/SharpYaml,vasily-kirichenko/SharpYaml | YamlDotNet/Serialization/IAttributeRegistry.cs | YamlDotNet/Serialization/IAttributeRegistry.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace YamlDotNet.Serialization
{
/// <summary>
/// A registry for all attributes.
/// </summary>
public interface IAttributeRegistry
{
/// <summary>
/// Gets the attributes associated with the specified member.
/// </summary>
/// <param name="memberInfo">The reflection member.</param>
/// <param name="inherit">if set to <c>true</c> includes inherited attributes.</param>
/// <returns>An enumeration of <see cref="Attribute"/>.</returns>
List<Attribute> GetAttributes(MemberInfo memberInfo, bool inherit = true);
/// <summary>
/// Registers an attribute for the specified member. Restriction: Attributes registered this way cannot be listed in inherited attributes.
/// </summary>
/// <param name="memberInfo">The member information.</param>
/// <param name="attribute">The attribute.</param>
void Register(MemberInfo memberInfo, Attribute attribute);
}
/// <summary>
/// Extension methods for attribute registry.
/// </summary>
public static class AttributeRegistryExtensions
{
/// <summary>
/// Gets the attributes associated with the specified member.
/// </summary>
/// <typeparam name="T">Type of the attribute</typeparam>
/// <param name="memberInfo">The member information.</param>
/// <param name="inherit">if set to <c>true</c> [inherit].</param>
/// <returns>An enumeration of <see cref="Attribute"/>.</returns>
public static IEnumerable<T> GetAttributes<T>(this IAttributeRegistry attributeRegistry, MemberInfo memberInfo, bool inherit = true) where T : Attribute
{
return attributeRegistry.GetAttributes(memberInfo, inherit).OfType<T>();
}
/// <summary>
/// Gets the first attribute of type T associated with the specified member.
/// </summary>
/// <typeparam name="T">Type of the attribute</typeparam>
/// <param name="memberInfo">The member information.</param>
/// <param name="inherit">if set to <c>true</c> [inherit].</param>
/// <returns>An attribute of type {T} if it was found; otherwise <c>null</c> </returns>
public static T GetAttribute<T>(this IAttributeRegistry attributeRegistry, MemberInfo memberInfo, bool inherit = true) where T : Attribute
{
return attributeRegistry.GetAttributes(memberInfo, inherit).OfType<T>().FirstOrDefault();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace YamlDotNet.Serialization
{
/// <summary>
/// A registry for all attributes.
/// </summary>
public interface IAttributeRegistry
{
/// <summary>
/// Gets the attributes associated with the specified member.
/// </summary>
/// <param name="memberInfo">The reflection member.</param>
/// <param name="inherit">if set to <c>true</c> includes inherited attributes.</param>
/// <returns>An enumeration of <see cref="Attribute"/>.</returns>
List<Attribute> GetAttributes(MemberInfo memberInfo, bool inherit = true);
/// <summary>
/// Registers an attribute for the specified member. Restriction: Attributes registered this way cannot be listed in inherited attributes.
/// </summary>
/// <param name="memberInfo">The member information.</param>
/// <param name="attribute">The attribute.</param>
void Register(MemberInfo memberInfo, Attribute attribute);
}
/// <summary>
/// Extension methods for attribute registry.
/// </summary>
public static class AttributeRegistryExtensions
{
/// <summary>
/// Gets the attributes associated with the specified member.
/// </summary>
/// <typeparam name="T">Type of the attribute</typeparam>
/// <param name="memberInfo">The member information.</param>
/// <param name="inherit">if set to <c>true</c> [inherit].</param>
/// <returns>An enumeration of <see cref="Attribute"/>.</returns>
public static IEnumerable<T> GetAttributes<T>(this IAttributeRegistry attributeRegistry, MemberInfo memberInfo, bool inherit = true) where T : Attribute
{
return attributeRegistry.GetAttributes(memberInfo, inherit).OfType<T>();
}
/// <summary>
/// Gets an attribute associated with the specified member.
/// </summary>
/// <typeparam name="T">Type of the attribute</typeparam>
/// <param name="memberInfo">The member information.</param>
/// <param name="inherit">if set to <c>true</c> [inherit].</param>
/// <returns>An attribute of type {T} if it was found; otherwise <c>null</c> </returns>
public static T GetAttribute<T>(this IAttributeRegistry attributeRegistry, MemberInfo memberInfo, bool inherit = true) where T : Attribute
{
var list = attributeRegistry.GetAttributes(memberInfo, inherit);
if (list.Count > 0)
{
return list[list.Count - 1] as T;
}
return null;
}
}
} | mit | C# |
496626d8a37a8dba29cf060c43ff1e05eea5ef80 | Fix transaction object unused | coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore | src/Miningcore/Persistence/Postgres/Repositories/MinerRepository.cs | src/Miningcore/Persistence/Postgres/Repositories/MinerRepository.cs | using System.Data;
using AutoMapper;
using Dapper;
using Miningcore.Extensions;
using Miningcore.Persistence.Model;
using Miningcore.Persistence.Repositories;
using NLog;
namespace Miningcore.Persistence.Postgres.Repositories;
public class MinerRepository : IMinerRepository
{
public MinerRepository(IMapper mapper)
{
this.mapper = mapper;
}
private readonly IMapper mapper;
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
public async Task<MinerSettings> GetSettingsAsync(IDbConnection con, IDbTransaction tx, string poolId, string address)
{
logger.LogInvoke();
const string query = @"SELECT * FROM miner_settings WHERE poolid = @poolId AND address = @address";
var entity = await con.QuerySingleOrDefaultAsync<Entities.MinerSettings>(query, new {poolId, address}, tx);
return mapper.Map<MinerSettings>(entity);
}
public Task UpdateSettingsAsync(IDbConnection con, IDbTransaction tx, MinerSettings settings)
{
const string query = @"INSERT INTO miner_settings(poolid, address, paymentthreshold, created, updated)
VALUES(@poolid, @address, @paymentthreshold, now(), now())
ON CONFLICT ON CONSTRAINT miner_settings_pkey DO UPDATE
SET paymentthreshold = @paymentthreshold, updated = now()
WHERE miner_settings.poolid = @poolid AND miner_settings.address = @address";
return con.ExecuteAsync(query, settings, tx);
}
}
| using System.Data;
using AutoMapper;
using Dapper;
using Miningcore.Extensions;
using Miningcore.Persistence.Model;
using Miningcore.Persistence.Repositories;
using NLog;
namespace Miningcore.Persistence.Postgres.Repositories;
public class MinerRepository : IMinerRepository
{
public MinerRepository(IMapper mapper)
{
this.mapper = mapper;
}
private readonly IMapper mapper;
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
public async Task<MinerSettings> GetSettingsAsync(IDbConnection con, IDbTransaction tx, string poolId, string address)
{
logger.LogInvoke();
const string query = @"SELECT * FROM miner_settings WHERE poolid = @poolId AND address = @address";
var entity = await con.QuerySingleOrDefaultAsync<Entities.MinerSettings>(query, new {poolId, address});
return mapper.Map<MinerSettings>(entity);
}
public Task UpdateSettingsAsync(IDbConnection con, IDbTransaction tx, MinerSettings settings)
{
const string query = @"INSERT INTO miner_settings(poolid, address, paymentthreshold, created, updated)
VALUES(@poolid, @address, @paymentthreshold, now(), now())
ON CONFLICT ON CONSTRAINT miner_settings_pkey DO UPDATE
SET paymentthreshold = @paymentthreshold, updated = now()
WHERE miner_settings.poolid = @poolid AND miner_settings.address = @address";
return con.ExecuteAsync(query, settings, tx);
}
}
| mit | C# |
0241e3da583625ef2e6c462c9ff6fa0c3be8ab1b | Add a failing test that shows how FakeDb reuses a template from the previously added siblings even when it was not generated | sergeyshushlyapin/Sitecore.FakeDb,pveller/Sitecore.FakeDb,hermanussen/Sitecore.FakeDb | src/Sitecore.FakeDb.Tests/Pipelines/AddDbItem/CreateTemplateTest.cs | src/Sitecore.FakeDb.Tests/Pipelines/AddDbItem/CreateTemplateTest.cs | namespace Sitecore.FakeDb.Tests.Pipelines.AddDbItem
{
using FluentAssertions;
using NSubstitute;
using Sitecore.Data;
using Sitecore.FakeDb.Data.Engines;
using Sitecore.FakeDb.Pipelines.AddDbItem;
using Xunit;
using Xunit.Extensions;
public class CreateTemplateTest
{
private const string NullTemplateId = "{00000000-0000-0000-0000-000000000000}";
private const string SomeTemplateId = "{F445AA3F-2EFC-4E84-9719-B7729C440054}";
private const string SitecoreBranchTemplateId = "{35E75C72-4985-4E09-88C3-0EAC6CD1E64F}";
private readonly CreateTemplate processor;
private readonly DataStorage dataStorage;
public CreateTemplateTest()
{
this.dataStorage = Substitute.For<DataStorage>(Database.GetDatabase("master"));
this.processor = new CreateTemplate();
}
[Theory]
[InlineData(NullTemplateId, SitecoreBranchTemplateId)]
[InlineData(SomeTemplateId, SomeTemplateId)]
public void ShouldSetTemplateIdToBranchTemplateIdIfParentIsBrancesAndNoTemplateIdSet(string originalTemplateId, string expectedNewTemlateId)
{
// arrange
var branchItem = new DbItem("branch item") { ParentID = ItemIDs.BranchesRoot, TemplateID = ID.Parse(originalTemplateId) };
var args = new AddDbItemArgs(branchItem, this.dataStorage);
// act
this.processor.Process(args);
// assert
branchItem.TemplateID.Should().Be(ID.Parse(expectedNewTemlateId));
}
[Fact]
public void ShouldSetBranchIdAndTemplateIdIfBranchResolved()
{
// arrange
var branchId = ID.NewID;
var branch = new DbItem("branch", branchId) { ParentID = ItemIDs.BranchesRoot, TemplateID = TemplateIDs.BranchTemplate };
this.dataStorage.GetFakeItem(branchId).Returns(branch);
var item = new DbItem("item from branch", ID.NewID, branchId);
// act
this.processor.Process(new AddDbItemArgs(item, this.dataStorage));
// assert
item.BranchId.Should().Be(branchId);
}
[Fact]
public void ShouldNotReuseSiblingTemplateIfTemplateIdSpecified()
{
// arrange
var myId = ID.NewID;
// act
using (var db = new Db
{
new DbTemplate("Site Root", myId),
new DbItem("site", ID.NewID, myId)
{
new DbItem("home")
},
new DbItem("outside")
})
{
// assert
var home = db.GetItem("/sitecore/content/site/home");
var outside = db.GetItem("/sitecore/content/outside");
outside.TemplateID.Should().NotBe(myId); // <-- Fails
}
}
}
} | namespace Sitecore.FakeDb.Tests.Pipelines.AddDbItem
{
using FluentAssertions;
using NSubstitute;
using Sitecore.Data;
using Sitecore.FakeDb.Data.Engines;
using Sitecore.FakeDb.Pipelines.AddDbItem;
using Xunit;
using Xunit.Extensions;
public class CreateTemplateTest
{
private const string NullTemplateId = "{00000000-0000-0000-0000-000000000000}";
private const string SomeTemplateId = "{F445AA3F-2EFC-4E84-9719-B7729C440054}";
private const string SitecoreBranchTemplateId = "{35E75C72-4985-4E09-88C3-0EAC6CD1E64F}";
private readonly CreateTemplate processor;
private readonly DataStorage dataStorage;
public CreateTemplateTest()
{
this.dataStorage = Substitute.For<DataStorage>(Database.GetDatabase("master"));
this.processor = new CreateTemplate();
}
[Theory]
[InlineData(NullTemplateId, SitecoreBranchTemplateId)]
[InlineData(SomeTemplateId, SomeTemplateId)]
public void ShouldSetTemplateIdToBranchTemplateIdIfParentIsBrancesAndNoTemplateIdSet(string originalTemplateId, string expectedNewTemlateId)
{
// arrange
var branchItem = new DbItem("branch item") { ParentID = ItemIDs.BranchesRoot, TemplateID = ID.Parse(originalTemplateId) };
var args = new AddDbItemArgs(branchItem, this.dataStorage);
// act
this.processor.Process(args);
// assert
branchItem.TemplateID.Should().Be(ID.Parse(expectedNewTemlateId));
}
[Fact]
public void ShouldSetBranchIdAndTemplateIdIfBranchResolved()
{
// arrange
var branchId = ID.NewID;
var branch = new DbItem("branch", branchId) { ParentID = ItemIDs.BranchesRoot, TemplateID = TemplateIDs.BranchTemplate };
this.dataStorage.GetFakeItem(branchId).Returns(branch);
var item = new DbItem("item from branch", ID.NewID, branchId);
// act
this.processor.Process(new AddDbItemArgs(item, this.dataStorage));
// assert
item.BranchId.Should().Be(branchId);
}
}
} | mit | C# |
86ca19686bd40a184ad322d705fdb0d2bda88f17 | Implement the option to start the app when logging into Windows | IWBWbiz/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner | MultiMiner.Win/ApplicationConfiguration.cs | MultiMiner.Win/ApplicationConfiguration.cs | using Microsoft.Win32;
using MultiMiner.Engine.Configuration;
using System;
using System.IO;
using System.Windows.Forms;
namespace MultiMiner.Win
{
public class ApplicationConfiguration
{
public ApplicationConfiguration()
{
this.StartupMiningDelay = 45;
}
public bool LaunchOnWindowsLogin { get; set; }
public bool StartMiningOnStartup { get; set; }
public int StartupMiningDelay { get; set; }
public bool RestartCrashedMiners { get; set; }
private static string AppDataPath()
{
string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(rootPath, "MultiMiner");
}
private static string DeviceConfigurationsFileName()
{
return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml");
}
public void SaveApplicationConfiguration()
{
ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName());
ApplyLaunchOnWindowsStartup();
}
private void ApplyLaunchOnWindowsStartup()
{
RegistryKey registrykey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (LaunchOnWindowsLogin)
registrykey.SetValue("MultiMiner", Application.ExecutablePath);
else
registrykey.DeleteValue("MultiMiner", false);
}
public void LoadApplicationConfiguration()
{
ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName());
this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin;
this.StartMiningOnStartup = tmp.StartMiningOnStartup;
this.StartupMiningDelay = tmp.StartupMiningDelay;
this.RestartCrashedMiners = tmp.RestartCrashedMiners;
}
}
}
| using MultiMiner.Engine.Configuration;
using System;
using System.IO;
namespace MultiMiner.Win
{
public class ApplicationConfiguration
{
public ApplicationConfiguration()
{
this.StartupMiningDelay = 45;
}
public bool LaunchOnWindowsLogin { get; set; }
public bool StartMiningOnStartup { get; set; }
public int StartupMiningDelay { get; set; }
public bool RestartCrashedMiners { get; set; }
private static string AppDataPath()
{
string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(rootPath, "MultiMiner");
}
private static string DeviceConfigurationsFileName()
{
return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml");
}
public void SaveApplicationConfiguration()
{
ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName());
}
public void LoadApplicationConfiguration()
{
ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName());
this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin;
this.StartMiningOnStartup = tmp.StartMiningOnStartup;
this.StartupMiningDelay = tmp.StartupMiningDelay;
this.RestartCrashedMiners = tmp.RestartCrashedMiners;
}
}
}
| mit | C# |
91b90d10b9b8b1518ee80c7418e44ce4f902340c | Remove old code | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewLocator.cs | WalletWasabi.Fluent/ViewLocator.cs | using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent
{
[StaticViewLocator]
public partial class ViewLocator : IDataTemplate
{
public bool SupportsRecycling => false;
public IControl Build(object data)
{
var type = data.GetType();
if (s_views.TryGetValue(type, out var func))
{
return func?.Invoke();
}
throw new Exception($"Unable to create view for type: {type}");
}
public bool Match(object data)
{
return data is ViewModelBase;
}
}
} | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent
{
[StaticViewLocator]
public partial class ViewLocator : IDataTemplate
{
public bool SupportsRecycling => false;
public IControl Build(object data)
{
var type = data.GetType();
if (s_views.TryGetValue(type, out var func))
{
return func?.Invoke();
}
throw new Exception($"Unable to create view for type: {type}");
/*var name = data.GetType().FullName!.Replace("ViewModel", "View");
var type = Type.GetType(name);
if (type != null)
{
var result = Activator.CreateInstance(type) as Control;
if (result is null)
{
throw new Exception($"Unable to activate type: {type}");
}
return result;
}
else
{
return new TextBlock { Text = "Not Found: " + name };
}*/
}
public bool Match(object data)
{
return data is ViewModelBase;
}
}
} | mit | C# |
656cf0725ad22da1da3a7a39350d8ee928394dad | Add non-args constructor for serialization. | Mikuz/Battlezeppelins,Mikuz/Battlezeppelins | Battlezeppelins/Models/PlayerTable/GameTable.cs | Battlezeppelins/Models/PlayerTable/GameTable.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Battlezeppelins.Models
{
public class GameTable
{
public const int TABLE_ROWS = 10;
public const int TABLE_COLS = 10;
public Game.Role role { get; private set; }
public List<OpenPoint> openPoints { get; private set; }
public List<Zeppelin> zeppelins { get; private set; }
public GameTable() { }
public GameTable(Game.Role role)
{
this.role = role;
this.openPoints = new List<OpenPoint>();
this.zeppelins = new List<Zeppelin>();
}
public void removeZeppelins() {
zeppelins = null;
}
public bool AddZeppelin(Zeppelin newZeppelin)
{
foreach (Zeppelin zeppelin in this.zeppelins)
{
// No multiple zeppelins of the same type
if (zeppelin.type == newZeppelin.type)
return false;
// No colliding zeppelins
if (zeppelin.collides(newZeppelin))
return false;
}
if (newZeppelin.x < 0 ||
newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 ||
newZeppelin.y < 0 ||
newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1)
{
return false;
}
this.zeppelins.Add(newZeppelin);
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Battlezeppelins.Models
{
public class GameTable
{
public const int TABLE_ROWS = 10;
public const int TABLE_COLS = 10;
public Game.Role role { get; private set; }
public List<OpenPoint> openPoints { get; private set; }
public List<Zeppelin> zeppelins { get; private set; }
public GameTable(Game.Role role)
{
this.role = role;
this.openPoints = new List<OpenPoint>();
this.zeppelins = new List<Zeppelin>();
}
public void removeZeppelins() {
zeppelins = null;
}
public bool AddZeppelin(Zeppelin newZeppelin)
{
foreach (Zeppelin zeppelin in this.zeppelins)
{
// No multiple zeppelins of the same type
if (zeppelin.type == newZeppelin.type)
return false;
// No colliding zeppelins
if (zeppelin.collides(newZeppelin))
return false;
}
if (newZeppelin.x < 0 ||
newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 ||
newZeppelin.y < 0 ||
newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1)
{
return false;
}
this.zeppelins.Add(newZeppelin);
return true;
}
}
}
| apache-2.0 | C# |
a34e407999b381770bfe5a98c75758c461ec903d | Create a non-null functionality wrapper in the required test. | SeanFarrow/NBench.VisualStudio | tests/NBench.VisualStudio.TestAdapter.Tests.Unit/NBenchTestDiscoverer/NBenchTestDiscoverer/WhenTheNBenchFunctionalityWRapperIsNotNull.cs | tests/NBench.VisualStudio.TestAdapter.Tests.Unit/NBenchTestDiscoverer/NBenchTestDiscoverer/WhenTheNBenchFunctionalityWRapperIsNotNull.cs | namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer
{
using JustBehave;
using NBench.VisualStudio.TestAdapter;
using NBench.VisualStudio.TestAdapter.Helpers;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Xunit;
public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer>
{
private INBenchFunctionalityWrapper functionalitywrapper;
protected override NBenchTestDiscoverer CreateSystemUnderTest()
{
return new NBenchTestDiscoverer(this.functionalitywrapper);
}
protected override void CustomizeAutoFixture(IFixture fixture)
{
fixture.Customize(new AutoNSubstituteCustomization());
}
protected override void Given()
{
this.functionalitywrapper = this.Fixture.Create<INBenchFunctionalityWrapper>();
}
protected override void When()
{
}
[Fact]
public void TheNBenchTestDiscovererIsNotNull()
{
Assert.NotNull(this.SystemUnderTest);
}
}
} | namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer
{
using JustBehave;
using NBench.VisualStudio.TestAdapter;
using NBench.VisualStudio.TestAdapter.Helpers;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Xunit;
public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer>
{
private INBenchFunctionalityWrapper functionalitywrapper;
protected override NBenchTestDiscoverer CreateSystemUnderTest()
{
return new NBenchTestDiscoverer(this.functionalitywrapper);
}
protected override void CustomizeAutoFixture(IFixture fixture)
{
fixture.Customize(new AutoNSubstituteCustomization());
}
protected override void Given()
{
this.functionalitywrapper = null;
}
protected override void When()
{
}
[Fact]
public void TheNBenchTestDiscovererIsNotNull()
{
Assert.NotNull(this.SystemUnderTest);
}
}
} | apache-2.0 | C# |
504a3fc2af3d8165ca4a55b6c6fd80671e71c259 | fix 1056 point in emal | leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net | JoinRpg.Portal/Views/Account/ConfirmEmail.cshtml | JoinRpg.Portal/Views/Account/ConfirmEmail.cshtml | @{
ViewBag.Title = "Подтверждение Email";
}
<h2>@ViewBag.Title</h2>
<div>
<p>
Спасибо, что подтвердили свой email.
<br/>
@(Html.ActionLink("Нажмите здесь, чтобы войти", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })).
</p>
</div>
| @{
ViewBag.Title = "Подтверждение Email";
}
<h2>@ViewBag.Title.</h2>
<div>
<p>
Спасибо, что подтвердили свой email.
<br/>
@Html.ActionLink("Нажмите здесь, чтобы войти", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })
</p>
</div>
| mit | C# |
6dd0479fd1dd5a3fd39dbe45fcede1ee42babc0f | Add several methods for Windows: IsAdmin | fredatgithub/UsefulFunctions | FonctionsUtiles.Fred.Csharp/FunctionsWindows.cs | FonctionsUtiles.Fred.Csharp/FunctionsWindows.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
namespace FonctionsUtiles.Fred.Csharp
{
public class FunctionsWindows
{
public static bool IsInWinPath(string substring)
{
bool result = false;
string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
if (winPath != null) result = winPath.Contains(substring);
return result;
}
public static string DisplayTitle()
{
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}";
}
public static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static bool IsAdmin()
{
return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
}
public static IEnumerable<Process> GetAllProcesses()
{
Process[] processlist = Process.GetProcesses();
return processlist.ToList();
}
public static bool IsProcessRunningById(Process process)
{
try { Process.GetProcessById(process.Id); }
catch (InvalidOperationException) { return false; }
catch (ArgumentException) { return false; }
return true;
}
public static bool IsProcessRunningByName(string processName)
{
try { Process.GetProcessesByName(processName); }
catch (InvalidOperationException) { return false; }
catch (ArgumentException) { return false; }
return true;
}
public static Process GetProcessByName(string processName)
{
Process result = new Process();
foreach (Process process in GetAllProcesses())
{
if (process.ProcessName == processName)
{
result = process;
break;
}
}
return result;
}
}
} | using System;
using System.Diagnostics;
using System.Reflection;
namespace FonctionsUtiles.Fred.Csharp
{
public class FunctionsWindows
{
public static bool IsInWinPath(string substring)
{
bool result = false;
string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
if (winPath != null) result = winPath.Contains(substring);
return result;
}
public static string DisplayTitle()
{
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}";
}
}
} | mit | C# |
a702aef0c8e5285901f02e50335596b43b941231 | split test method to simplify. | jwChung/Experimentalism,jwChung/Experimentalism | test/Experiment.IdiomsUnitTest/GuardClauseAssertionTestCasesTest.cs | test/Experiment.IdiomsUnitTest/GuardClauseAssertionTestCasesTest.cs | using System;
using System.Linq;
using Ploeh.Albedo.Refraction;
using Xunit;
namespace Jwc.Experiment.Idioms
{
public class GuardClauseAssertionTestCasesTest
{
[Fact]
public void SutIsIdiomaticTestCases()
{
var sut = new GuardClauseAssertionTestCases(GetType());
Assert.IsAssignableFrom<IdiomaticTestCases>(sut);
}
[Fact]
public void ReflectionElementsHasCorrectSources()
{
var type = GetType();
var exceptedMembers = type.GetMembers();
var sut = new GuardClauseAssertionTestCases(type, exceptedMembers);
var actual = sut.ReflectionElements;
var reflectionElements = Assert.IsAssignableFrom<ReflectionElements>(actual);
var fileterMembers = Assert.IsAssignableFrom<FilteringMembers>(reflectionElements.Sources);
var targetMembers = Assert.IsAssignableFrom<TargetMembers>(fileterMembers.TargetMembers);
Assert.Equal(type, targetMembers.Type);
Assert.Equal(Accessibilities.Public, targetMembers.Accessibilities);
Assert.Equal(exceptedMembers, fileterMembers.ExceptedMembers);
}
[Fact]
public void ReflectionElementsHasCorrectRefractions()
{
var sut = new GuardClauseAssertionTestCases(GetType());
var actual = sut.ReflectionElements;
var reflectionElements = Assert.IsAssignableFrom<ReflectionElements>(actual);
Assert.Equal(
new[]
{
typeof(ConstructorInfoElementRefraction<object>),
typeof(PropertyInfoElementRefraction<object>),
typeof(MethodInfoElementRefraction<object>)
}
.OrderBy(t => t.FullName),
reflectionElements.Refractions.Select(r => r.GetType()).OrderBy(t => t.FullName));
}
[Fact]
public void AssertionFactoryIsCorrect()
{
var sut = new GuardClauseAssertionTestCases(GetType());
var actual = sut.AssertionFactory;
Assert.IsType<GuardClauseAssertionFactory>(actual);
}
}
} | using System.Linq;
using Ploeh.Albedo.Refraction;
using Xunit;
namespace Jwc.Experiment.Idioms
{
public class GuardClauseAssertionTestCasesTest
{
[Fact]
public void SutIsIdiomaticTestCases()
{
var sut = new GuardClauseAssertionTestCases(GetType());
Assert.IsAssignableFrom<IdiomaticTestCases>(sut);
}
[Fact]
public void ReflectionElementsIsCorrect()
{
// Fixture setup
var type = GetType();
var exceptedMembers = type.GetMembers();
var sut = new GuardClauseAssertionTestCases(type, exceptedMembers);
// Exercise system
var actual = sut.ReflectionElements;
// Verify outcome
var reflectionElements = Assert.IsAssignableFrom<ReflectionElements>(actual);
var fileterMembers = Assert.IsAssignableFrom<FilteringMembers>(reflectionElements.Sources);
var targetMembers = Assert.IsAssignableFrom<TargetMembers>(fileterMembers.TargetMembers);
Assert.Equal(type, targetMembers.Type);
Assert.Equal(Accessibilities.Public, targetMembers.Accessibilities);
Assert.Equal(exceptedMembers, fileterMembers.ExceptedMembers);
Assert.Equal(
new[]
{
typeof(ConstructorInfoElementRefraction<object>),
typeof(PropertyInfoElementRefraction<object>),
typeof(MethodInfoElementRefraction<object>)
}
.OrderBy(t => t.FullName),
reflectionElements.Refractions.Select(r => r.GetType()).OrderBy(t => t.FullName));
}
[Fact]
public void AssertionFactoryIsCorrect()
{
var sut = new GuardClauseAssertionTestCases(GetType());
var actual = sut.AssertionFactory;
Assert.IsType<GuardClauseAssertionFactory>(actual);
}
}
} | mit | C# |
d2b4f735f03564c67712f67a7b52d301e90a3d43 | add samples to navigation and remove optional tags | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.API/Views/Shared/_Navigation.cshtml | WebAPI.API/Views/Shared/_Navigation.cshtml | <ul class="nav nav-pills nav-stacked">
<li class="nav-header">Endpoints
<li class="active"><a href="#geocoding">Geocoding</a>
<li><a href="#search">Searching</a>
<li><a href="#info">SGID Information</a>
<li class="nav-header">Resources
<li>@Html.ActionLink("Console", "Dashboard", new
{
Controller = "Go"
})
<li>@Html.ActionLink("Register", "Register", new
{
Controller = "Go"
})
<li class="nav-header">Help
<li>@Html.ActionLink("Getting Started Guide", "Startup", new
{
Controller = "Go"
})
<li><a href="https://github.com/agrc/GeocodingSample">Sample Usage</a>
<li><a href="https://github.com/agrc/api.mapserv.utah.gov/issues/new">Report an Issue</a>
<li class="nav-header">About
<li><a href="@Url.Action("Index", "ChangeLog")"><i class="glyphicon glyphicon-barcode"></i> @ViewContext.Controller.GetType().Assembly.GetName().Version.ToString()</a>
<li class="nav-header">© AGRC @DateTime.Now.Year
</ul>
<p>
<img src="@Url.Content("~/Content/images/ravendb-small.png")" alt="ravendb logo" />
</p>
| <ul class="nav nav-pills nav-stacked">
<li class="nav-header">Endpoints
<li class="active"><a href="#geocoding">Geocoding</a>
<li><a href="#search">Searching</a>
<li><a href="#info">SGID Information</a>
<li class="nav-header">Resources
<li>@Html.ActionLink("Console", "Dashboard", new
{
Controller = "Go"
})</li>
<li>@Html.ActionLink("Register", "Register", new
{
Controller = "Go"
})
<li class="nav-header">Help
<li>
@Html.ActionLink("Getting Started Guide", "Startup", new
{
Controller = "Go"
})
<li><a href="https://github.com/agrc/GeocodingSample">Sample Usage</a>
<li><a href="https://github.com/agrc/api.mapserv.utah.gov/issues/new">Report an Issue</a>
<li class="nav-header">About
<li><a href="@Url.Action("Index", "ChangeLog")"><i class="glyphicon glyphicon-barcode"></i> @ViewContext.Controller.GetType().Assembly.GetName().Version.ToString()</a>
<li class="nav-header">© AGRC @DateTime.Now.Year
</ul>
<p>
<img src="@Url.Content("~/Content/images/ravendb-small.png")" alt="ravendb logo" />
</p>
| mit | C# |
ffcbc803a4d1721cc2f4b1f5721f5d74388bef1d | Clean up the Gtk LinkLabelBackend class | lytico/xwt,directhex/xwt,steffenWi/xwt,hwthomas/xwt,mminns/xwt,mminns/xwt,TheBrainTech/xwt,mono/xwt,cra0zy/xwt,akrisiun/xwt,antmicro/xwt,sevoku/xwt,hamekoz/xwt,iainx/xwt,residuum/xwt | Xwt.Gtk/Xwt.GtkBackend/LinkLabelBackend.cs | Xwt.Gtk/Xwt.GtkBackend/LinkLabelBackend.cs | //
// LinkLabelBackend.cs
//
// Author:
// Jérémie Laval <jeremie.laval@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
class LinkLabelBackend : LabelBackend, ILinkLabelBackend
{
Uri uri;
bool ClickEnabled {
get; set;
}
new ILinkLabelEventSink EventSink {
get { return (ILinkLabelEventSink)base.EventSink; }
}
public Uri Uri {
get {
return uri;
}
set {
uri = value;
var text = Label.Text;
string url = string.Format ("<a href=\"{1}\">{0}</a>", text, uri.ToString ());
Label.Markup = url;
}
}
public LinkLabelBackend ()
{
Label.UseMarkup = true;
Label.SetLinkHandler (OpenLink);
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is LinkLabelEvent) {
switch ((LinkLabelEvent) eventId) {
case LinkLabelEvent.Clicked:
ClickEnabled = true;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is LinkLabelEvent) {
switch ((LinkLabelEvent) eventId) {
case LinkLabelEvent.Clicked:
ClickEnabled = false;
break;
}
}
}
void OpenLink (string link)
{
if (ClickEnabled)
Xwt.Engine.Toolkit.Invoke (() => {
EventSink.OnClicked ();
});
}
}
}
| //
// LinkLabelBackend.cs
//
// Author:
// Jérémie Laval <jeremie.laval@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
class LinkLabelBackend : LabelBackend, ILinkLabelBackend
{
Uri uri;
event EventHandler Clicked;
public LinkLabelBackend ()
{
Label.UseMarkup = true;
Label.SetLinkHandler (OpenLink);
}
new ILinkLabelEventSink EventSink {
get { return (ILinkLabelEventSink)base.EventSink; }
}
public Uri Uri {
get {
return uri;
}
set {
uri = value;
var text = Label.Text;
string url = string.Format ("<a href=\"{1}\">{0}</a>", text, uri.ToString ());
Label.Markup = url;
}
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is LinkLabelEvent) {
switch ((LinkLabelEvent) eventId) {
case LinkLabelEvent.Clicked:
Clicked += HandleClicked;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is LinkLabelEvent) {
switch ((LinkLabelEvent) eventId) {
case LinkLabelEvent.Clicked:
Clicked -= HandleClicked;
break;
}
}
}
void HandleClicked (object sender, EventArgs e)
{
Xwt.Engine.Toolkit.Invoke (() => {
EventSink.OnClicked ();
});
}
void OpenLink (string link)
{
if (Clicked != null)
Clicked (this, EventArgs.Empty);
}
}
}
| mit | C# |
12fe6a48f873ebcf1f9f6c6ce544ac1008cc4642 | Update AssemblyInfo.cs | stephanstapel/ZUGFeRD-csharp,stephanstapel/ZUGFeRD-csharp | ZUGFeRDRenderer/Properties/AssemblyInfo.cs | ZUGFeRDRenderer/Properties/AssemblyInfo.cs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("ZUGFeRDRenderer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZUGFeRDRenderer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("dc36d912-5cea-41cc-bc2c-d89e4df19741")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("ZUGFeRDRenderer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZUGFeRDRenderer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("dc36d912-5cea-41cc-bc2c-d89e4df19741")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
78103d07c408c8b275fc4c4b1e230cfc8cf1a7a6 | Fix unit tests | charlenni/Mapsui,charlenni/Mapsui,pauldendulk/Mapsui | Mapsui/Layers/MemoryLayer.cs | Mapsui/Layers/MemoryLayer.cs | using Mapsui.Geometries;
using Mapsui.Providers;
using System.Collections.Generic;
using Mapsui.Fetcher;
using Mapsui.Styles;
namespace Mapsui.Layers
{
/// <summary>
/// A layer to use, when DataSource doesn't fetch anything because it is already in memory
/// </summary>
public class MemoryLayer : BaseLayer
{
/// <summary>
/// Create a new layer
/// </summary>
public MemoryLayer() : this("MemoryLayer") { }
/// <summary>
/// Create layer with name
/// </summary>
/// <param name="layername">Name to use for layer</param>
public MemoryLayer(string layername) : base(layername) { }
public IProvider DataSource { get; set; }
public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution)
{
// Safeguard in case BoundingBox is null, most likely due to no features in layer
if (box == null) { return new List<IFeature>(); }
var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution);
return DataSource.GetFeaturesInView(biggerBox, resolution);
}
public override void RefreshData(BoundingBox extent, double resolution, ChangeType changeType)
{
//The MemoryLayer always has it's data ready so can fire a DataChanged event immediately so that listeners can act on it.
OnDataChanged(new DataChangedEventArgs());
// If a user changed the data in the provider and needs to update the graphics
// DataHasChanged should be called.
}
public override BoundingBox Envelope => DataSource?.GetExtents();
}
}
| using Mapsui.Geometries;
using Mapsui.Providers;
using System.Collections.Generic;
using Mapsui.Styles;
namespace Mapsui.Layers
{
/// <summary>
/// A layer to use, when DataSource doesn't fetch anything because it is already in memory
/// </summary>
public class MemoryLayer : BaseLayer
{
/// <summary>
/// Create a new layer
/// </summary>
public MemoryLayer() : this("MemoryLayer") { }
/// <summary>
/// Create layer with name
/// </summary>
/// <param name="layername">Name to use for layer</param>
public MemoryLayer(string layername) : base(layername) { }
public IProvider DataSource { get; set; }
public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution)
{
// Safeguard in case BoundingBox is null, most likely due to no features in layer
if (box == null) { return new List<IFeature>(); }
var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution);
return DataSource.GetFeaturesInView(biggerBox, resolution);
}
public override void RefreshData(BoundingBox extent, double resolution, ChangeType changeType)
{
// RefreshData needs no implementation for the MemoryLayer
// If a user changed the data in the provider and needs to update the graphics
// DataHasChanged should be called.
}
public override BoundingBox Envelope => DataSource?.GetExtents();
}
}
| mit | C# |
5534bd860e64c30c97f40e621a45a35c882bc837 | Refactor controller (shared code) | noocyte/hurdle-ri | WebAPI.Backend/Controllers/IncidentController.cs | WebAPI.Backend/Controllers/IncidentController.cs | using System;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using WebAPI.Backend.Models;
namespace WebAPI.Backend.Controllers
{
public class IncidentController : ApiController
{
private readonly IncidentRepository _repository;
public IncidentController() // todo ninject
{
_repository = new IncidentRepository(null);
}
[Route("api/incident/{company}/{id}")]
public async Task<IHttpActionResult> Get(string company, string id)
{
var result = await _repository.GetByIdAsync(company, id);
if (!result.Success) return StatusCode(result.Status);
var dto = result.Result;
var incident = Mapper.Map<Incident>(dto);
return Ok(incident);
}
[Route("api/incident/{company}/{id}")]
public async Task<IHttpActionResult> Post(string company, string id, [FromBody] Incident obj)
{
var dto = new IncidentDto(company, id);
return await CreateOrUpdateAsync(obj, dto, _repository.CreateAsync);
}
[Route("api/incident/{company}/{id}")]
public async Task<IHttpActionResult> Patch(string company, string id, [FromBody] Incident obj)
{
var dto = new IncidentDto(company, id) {ETag = "*"};
return await CreateOrUpdateAsync(obj, dto, _repository.UpdateAsync);
}
private async Task<IHttpActionResult> CreateOrUpdateAsync(Incident obj, IncidentDto dto,
Func<IncidentDto, Task<TableResponse<IncidentDto>>> createOrUpdateFunc)
{
Mapper.Map(obj, dto);
var result = await createOrUpdateFunc(dto);
if (result.Success)
return Ok(result.Result);
return StatusCode(result.Status);
}
}
} | using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using WebAPI.Backend.Models;
namespace WebAPI.Backend.Controllers
{
public class IncidentController : ApiController
{
private readonly IncidentRepository _repository;
public IncidentController() // todo ninject
{
_repository = new IncidentRepository(null);
}
[Route("api/incident/{company}/{id}")]
public async Task<IHttpActionResult> Get(string company, string id)
{
var result = await _repository.GetByIdAsync(company, id);
if (!result.Success) return StatusCode(result.Status);
var dto = result.Result;
var incident = Mapper.Map<Incident>(dto);
return Ok(incident);
}
[Route("api/incident/{company}/{id}")]
public async Task<IHttpActionResult> Post(string company, string id, [FromBody] Incident obj)
{
var dto = new IncidentDto(company, id);
Mapper.Map(obj, dto);
var result = await _repository.CreateAsync(dto);
if (result.Success)
return Ok(result.Result);
return StatusCode(result.Status);
}
[Route("api/incident/{company}/{id}")]
public async Task<IHttpActionResult> Patch(string company, string id, [FromBody] Incident obj)
{
var dto = new IncidentDto(company, id) {ETag = "*"};
Mapper.Map(obj, dto);
var result = await _repository.UpdateAsync(dto);
if (result.Success)
return Ok(result.Result);
return StatusCode(result.Status);
}
}
} | mit | C# |
317a3dfdc327ca5dd11dd8cb4363359bf05c0ef4 | Make IgnoreOnAdd member of IPropertyMetadataConfigurator. | ExRam/ExRam.Gremlinq | ExRam.Gremlinq.Core/Models/Metadata/IPropertyMetadataConfigurator.cs | ExRam.Gremlinq.Core/Models/Metadata/IPropertyMetadataConfigurator.cs | using System;
using System.Collections.Immutable;
using System.Linq.Expressions;
using System.Reflection;
namespace ExRam.Gremlinq.Core
{
public interface IPropertyMetadataConfigurator<TElement> : IImmutableDictionary<MemberInfo, PropertyMetadata>
{
IPropertyMetadataConfigurator<TElement> IgnoreOnAdd<TProperty>(Expression<Func<TElement, TProperty>> propertyExpression);
IPropertyMetadataConfigurator<TElement> IgnoreOnUpdate<TProperty>(Expression<Func<TElement, TProperty>> propertyExpression);
IPropertyMetadataConfigurator<TElement> IgnoreAlways<TProperty>(Expression<Func<TElement, TProperty>> propertyExpression);
}
}
| using System;
using System.Collections.Immutable;
using System.Linq.Expressions;
using System.Reflection;
namespace ExRam.Gremlinq.Core
{
public interface IPropertyMetadataConfigurator<TElement> : IImmutableDictionary<MemberInfo, PropertyMetadata>
{
IPropertyMetadataConfigurator<TElement> IgnoreOnUpdate<TProperty>(Expression<Func<TElement, TProperty>> propertyExpression);
IPropertyMetadataConfigurator<TElement> IgnoreAlways<TProperty>(Expression<Func<TElement, TProperty>> propertyExpression);
}
}
| mit | C# |
0d4b0f7e9c2b49df261891406b71deee76bcf506 | Document the IAsyncSceneObjectGroupDeleter methods. | TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim | OpenSim/Region/Framework/Interfaces/IAsyncSceneObjectGroupDeleter.cs | OpenSim/Region/Framework/Interfaces/IAsyncSceneObjectGroupDeleter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.Framework.Interfaces
{
public interface IAsyncSceneObjectGroupDeleter
{
/// <summary>
/// Deletes the given groups to the given user's inventory in the given folderID
/// </summary>
/// <param name="action">The reason these objects are being sent to inventory</param>
/// <param name="folderID">The folder the objects will be added into, if you want the default folder, set this to UUID.Zero</param>
/// <param name="objectGroups">The groups to send to inventory</param>
/// <param name="AgentId">The agent who is deleting the given groups (not the owner of the objects necessarily)</param>
/// <param name="permissionToDelete">If true, the objects will be deleted from the sim as well</param>
/// <param name="permissionToTake">If true, the objects will be added to the user's inventory as well</param>
void DeleteToInventory(DeRezAction action, UUID folderID,
List<ISceneEntity> objectGroups, UUID AgentId,
bool permissionToDelete, bool permissionToTake);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.Framework.Interfaces
{
public interface IAsyncSceneObjectGroupDeleter
{
void DeleteToInventory(DeRezAction action, UUID folderID,
List<ISceneEntity> objectGroups, UUID AgentId,
bool permissionToDelete, bool permissionToTake);
}
}
| bsd-3-clause | C# |
5a89383ed6005d90ecd486fc7de9cdb4c87d9304 | Add additional tests for EnumMatchToBooleanConverter | maxlmo/outlook-matters,maxlmo/outlook-matters,makmu/outlook-matters,makmu/outlook-matters | OutlookMatters.Core.Test/Settings/EnumMatchToBooleanConverterTest.cs | OutlookMatters.Core.Test/Settings/EnumMatchToBooleanConverterTest.cs | using System.Globalization;
using System.Reflection;
using FluentAssertions;
using Microsoft.Office.Interop.Outlook;
using Moq;
using NUnit.Framework;
using OutlookMatters.Core.Settings;
namespace Test.OutlookMatters.Core.Settings
{
[TestFixture]
public class EnumMatchToBooleanConverterTest
{
[Test]
[TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)]
[TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)]
[TestCase(null, MattermostVersion.ApiVersionThree, false)]
[TestCase(MattermostVersion.ApiVersionOne, null, false)]
public void Convert_ConvertsToExpectedResult(object parameter, object value,
bool expectedResult)
{
var classUnderTest = new EnumMatchToBooleanConverter();
var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>());
Assert.That(result, Is.EqualTo(expectedResult));
}
[Test]
[TestCase(true, "ApiVersionOne", MattermostVersion.ApiVersionOne)]
[TestCase(false, "ApiVersionOne", null)]
[TestCase(true, null, null)]
[TestCase(null, "ApiVersionOne", null)]
public void ConvertBack_ConvertsToExpectedResult(object value, object parameter, object expectedResult)
{
var classUnderTest = new EnumMatchToBooleanConverter();
var result = classUnderTest.ConvertBack(value, typeof(MattermostVersion), parameter, It.IsAny<CultureInfo>());
Assert.That(result, Is.EqualTo(expectedResult));
}
}
}
| using System.Globalization;
using System.Reflection;
using FluentAssertions;
using Microsoft.Office.Interop.Outlook;
using Moq;
using NUnit.Framework;
using OutlookMatters.Core.Settings;
namespace Test.OutlookMatters.Core.Settings
{
[TestFixture]
public class EnumMatchToBooleanConverterTest
{
[Test]
[TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)]
[TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)]
[TestCase(null, MattermostVersion.ApiVersionThree, false)]
[TestCase(MattermostVersion.ApiVersionOne, null, false)]
public void Convert_ConvertsToExpectedResult(object parameter, object value,
bool expectedResult)
{
var classUnderTest = new EnumMatchToBooleanConverter();
var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>());
Assert.That(result, Is.EqualTo(expectedResult));
}
}
}
| mit | C# |
2bc17f2941863312957adbd1ee5f19b59056b2b3 | Reset Chutes & Ladders demos to run demo 1 by default | bsstahl/AIDemos,bsstahl/AIDemos | ChutesAndLaddersDemo/Simulation/Chute/Program.cs | ChutesAndLaddersDemo/Simulation/Chute/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChutesAndLadders.GamePlay;
using ChutesAndLadders.Entities;
using System.Diagnostics;
namespace Chute
{
class Program
{
static void Main(string[] args)
{
var board = new GameBoard();
#region Demo 1
board.Demo1a_GreedyAlgorithm();
#endregion
#region Demo 2
// board.Demo2a_RulesEngine();
// board.Demo2b_ImprovedLinear();
#endregion
#region Demo 3
// Only do demo 3b unless there is time left over
// board.Demo3a_GeneticAnalysis();
// board.Demo3b_GeneticEvolution();
// board.Demo3c_GeneticSuperiority();
#endregion
#region Demo 4
// board.Demo4a_ShortestPath();
#endregion
#region Supplemental Demos
// board.SupplementalDemo_SingleGame();
// board.SupplementalDemo_Player1Advantage();
// board.GameActionOutput_SmallSample();
#endregion
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChutesAndLadders.GamePlay;
using ChutesAndLadders.Entities;
using System.Diagnostics;
namespace Chute
{
class Program
{
static void Main(string[] args)
{
var board = new GameBoard();
#region Demo 1
// board.Demo1a_GreedyAlgorithm();
#endregion
#region Demo 2
// board.Demo2a_RulesEngine();
// board.Demo2b_ImprovedLinear();
#endregion
#region Demo 3
// Only do demo 3b unless there is time left over
// board.Demo3a_GeneticAnalysis();
// board.Demo3b_GeneticEvolution();
// board.Demo3c_GeneticSuperiority();
#endregion
#region Demo 4
// board.Demo4a_ShortestPath();
#endregion
#region Supplemental Demos
// board.SupplementalDemo_SingleGame();
// board.SupplementalDemo_Player1Advantage();
board.GameActionOutput_SmallSample();
#endregion
}
}
}
| mit | C# |
1890e818f910c35e530150701c34141c9ea02088 | Remove output on some tests | Dexiom/Dexiom.EPPlusExporter | Dexiom.EPPlusExporterTests/Helpers/TestHelper.cs | Dexiom.EPPlusExporterTests/Helpers/TestHelper.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bogus;
using Dexiom.EPPlusExporter;
using OfficeOpenXml;
namespace Dexiom.EPPlusExporterTests.Helpers
{
public static class TestHelper
{
public static void OpenDocument(ExcelPackage excelPackage)
{
Console.WriteLine("Opening document");
Directory.CreateDirectory("temp");
var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx");
excelPackage.SaveAs(fileInfo);
Process.Start(fileInfo.FullName);
}
public static ExcelPackage FakeAnExistingDocument()
{
var retVal = new ExcelPackage();
var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet");
worksheet.Cells[1, 1].Value = "I am a normal sheet";
worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!";
return retVal;
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bogus;
using Dexiom.EPPlusExporter;
using OfficeOpenXml;
namespace Dexiom.EPPlusExporterTests.Helpers
{
public static class TestHelper
{
public static void OpenDocument(ExcelPackage excelPackage)
{
Console.WriteLine("Opening document");
Directory.CreateDirectory("temp");
var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx");
excelPackage.SaveAs(fileInfo);
Process.Start(fileInfo.FullName);
}
public static ExcelPackage FakeAnExistingDocument()
{
Console.WriteLine("FakeAnExistingDocument");
var retVal = new ExcelPackage();
var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet");
worksheet.Cells[1, 1].Value = "I am a normal sheet";
worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!";
return retVal;
}
}
}
| mit | C# |
adf7c67a0ef94d6ab1b830fd0cc0265888ed239c | improve TheoremAttribute. | jwChung/Experimentalism,jwChung/Experimentalism | src/Experiment.AutoFixture/TheoremAttribute.cs | src/Experiment.AutoFixture/TheoremAttribute.cs | using System;
using System.Linq;
using System.Reflection;
using Jwc.Experiment;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Kernel;
using Ploeh.AutoFixture.Xunit;
namespace Jwc.Experiment
{
/// <summary>
/// 이 attribute는 method위에 선언되어 해당 method가 test case라는 것을
/// 지칭하게 되며, non-parameterized test 뿐 아니라 parameterized test에도
/// 사용될 수 있다.
/// Parameterized test에 대해 이 attribute는 AutoFixture library를 이용하여
/// auto data기능을 제공한다.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class TheoremAttribute : NaiveTheoremAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TheoremAttribute"/> class.
/// </summary>
public TheoremAttribute() : base(CreateTestFixture)
{
}
private static ITestFixture CreateTestFixture(MethodInfo testMethod)
{
var fixture = CreateFixture();
foreach (var parameter in testMethod.GetParameters())
{
Customize(fixture, parameter);
}
return new TestFixtureAdapter(new SpecimenContext(fixture));
}
private static IFixture CreateFixture()
{
return new Fixture();
}
private static void Customize(IFixture fixture, ParameterInfo parameter)
{
if (GetCustomizeAttribute(parameter) == null)
{
return;
}
var customization = GetCustomizeAttribute(parameter).GetCustomization(parameter);
fixture.Customize(customization);
}
private static CustomizeAttribute GetCustomizeAttribute(ParameterInfo parameter)
{
return (CustomizeAttribute)parameter
.GetCustomAttributes(typeof(CustomizeAttribute), false)
.SingleOrDefault();
}
}
} | using System;
using System.Linq;
using System.Reflection;
using Jwc.Experiment;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Kernel;
using Ploeh.AutoFixture.Xunit;
namespace Jwc.Experiment
{
/// <summary>
/// 이 attribute는 method위에 선언되어 해당 method가 test case라는 것을
/// 지칭하게 되며, non-parameterized test 뿐 아니라 parameterized test에도
/// 사용될 수 있다.
/// Parameterized test에 대해 이 attribute는 AutoFixture library를 이용하여
/// auto data기능을 제공한다.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class TheoremAttribute : NaiveTheoremAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TheoremAttribute"/> class.
/// </summary>
public TheoremAttribute() : base(CreateTestFixture)
{
}
private static ITestFixture CreateTestFixture(MethodInfo testMethod)
{
var fixture = new Fixture();
foreach (var parameter in testMethod.GetParameters())
{
var attribute = (CustomizeAttribute)parameter
.GetCustomAttributes(typeof(CustomizeAttribute), false)
.SingleOrDefault();
if (attribute != null)
{
var customization = attribute.GetCustomization(parameter);
fixture.Customize(customization);
}
}
return new TestFixtureAdapter(new SpecimenContext(fixture));
}
}
} | mit | C# |
95eba4dd19d5bfcc933d5243bbbd81dcdabf0afe | Update src/Workspaces/MSBuildTest/MSBuildInstalled.cs | mavasani/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,dotnet/roslyn,weltkante/roslyn,bartdesmet/roslyn,diryboy/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,bartdesmet/roslyn,diryboy/roslyn,mavasani/roslyn,KevinRansom/roslyn,sharwell/roslyn,sharwell/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,KevinRansom/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn | src/Workspaces/MSBuildTest/MSBuildInstalled.cs | src/Workspaces/MSBuildTest/MSBuildInstalled.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild.UnitTests
{
/// <summary>
/// These tests will run with either VS installed or with a .NET (Core) SDK installed. The
/// MSBuild used depends on the TargetFramework of the test project being executed.
/// </summary>
internal sealed class MSBuildInstalled : ExecutionCondition
{
private readonly ExecutionCondition _msBuildInstalled;
public MSBuildInstalled()
: this(minimumVsVersion: new Version(15, 0), minimumSdkVersion: new Version(2, 1))
{
}
/// <summary>
/// These tests will run with either the VS installed or with a .NET (Core) SDK installed. The
/// MSBuild used depends on the TargetFramework of the test project being executed. Include valid
/// minimum versions for both.
/// </summary>
protected MSBuildInstalled(Version minimumVsVersion, Version minimumSdkVersion)
{
_msBuildInstalled =
#if NETCOREAPP
new DotNetSdkMSBuildInstalled(minimumSdkVersion);
#else
new VisualStudioMSBuildInstalled(minimumVsVersion);
#endif
}
public override bool ShouldSkip => _msBuildInstalled.ShouldSkip;
public override string SkipReason => _msBuildInstalled.SkipReason;
}
internal class MSBuild16_2OrHigherInstalled : MSBuildInstalled
{
public MSBuild16_2OrHigherInstalled()
: base(minimumVsVersion: new Version(16, 2), minimumSdkVersion: new Version(3, 1))
{
}
}
internal class MSBuild16_9OrHigherInstalled : MSBuildInstalled
{
public MSBuild16_9OrHigherInstalled()
: base(minimumVsVersion: new Version(16, 9), minimumSdkVersion: new Version(5, 0, 201))
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild.UnitTests
{
/// <summary>
/// These tests will run with either VS installed or with a .NET (Core) SDK installed. The
/// MSBuild used depends on the TargetFramework of the test project being executed.
/// </summary>
internal class MSBuildInstalled : ExecutionCondition
{
private readonly ExecutionCondition _msBuildInstalled;
public MSBuildInstalled()
: this(minimumVsVersion: new Version(15, 0), minimumSdkVersion: new Version(2, 1))
{
}
/// <summary>
/// These tests will run with either the VS installed or with a .NET (Core) SDK installed. The
/// MSBuild used depends on the TargetFramework of the test project being executed. Include valid
/// minimum versions for both.
/// </summary>
protected MSBuildInstalled(Version minimumVsVersion, Version minimumSdkVersion)
{
_msBuildInstalled =
#if NETCOREAPP
new DotNetSdkMSBuildInstalled(minimumSdkVersion);
#else
new VisualStudioMSBuildInstalled(minimumVsVersion);
#endif
}
public override bool ShouldSkip => _msBuildInstalled.ShouldSkip;
public override string SkipReason => _msBuildInstalled.SkipReason;
}
internal class MSBuild16_2OrHigherInstalled : MSBuildInstalled
{
public MSBuild16_2OrHigherInstalled()
: base(minimumVsVersion: new Version(16, 2), minimumSdkVersion: new Version(3, 1))
{
}
}
internal class MSBuild16_9OrHigherInstalled : MSBuildInstalled
{
public MSBuild16_9OrHigherInstalled()
: base(minimumVsVersion: new Version(16, 9), minimumSdkVersion: new Version(5, 0, 201))
{
}
}
}
| mit | C# |
91f324f4f7f1f660fbf966ffddba31c507311d7f | Fix wrong define 7612b6f65cec4620d83117511d38e47a5456b468 | stormleoxia/referencesource,ludovic-henry/referencesource,evincarofautumn/referencesource,directhex/referencesource,esdrubal/referencesource,mono/referencesource | mscorlib/system/threading/threadabortexception.cs | mscorlib/system/threading/threadabortexception.cs | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// <OWNER>[....]</OWNER>
/*=============================================================================
**
** Class: ThreadAbortException
**
**
** Purpose: An exception class which is thrown into a thread to cause it to
** abort. This is a special non-catchable exception and results in
** the thread's death. This is thrown by the VM only and can NOT be
** thrown by any user thread, and subclassing this is useless.
**
**
=============================================================================*/
namespace System.Threading
{
using System;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed class ThreadAbortException : SystemException
{
private ThreadAbortException()
: base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadAbort))
{
SetErrorCode(__HResults.COR_E_THREADABORTED);
}
//required for serialization
internal ThreadAbortException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#if !MOBILE
public Object ExceptionState
{
[System.Security.SecuritySafeCritical] // auto-generated
get {return Thread.CurrentThread.AbortReason;}
}
#endif
}
}
| // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// <OWNER>[....]</OWNER>
/*=============================================================================
**
** Class: ThreadAbortException
**
**
** Purpose: An exception class which is thrown into a thread to cause it to
** abort. This is a special non-catchable exception and results in
** the thread's death. This is thrown by the VM only and can NOT be
** thrown by any user thread, and subclassing this is useless.
**
**
=============================================================================*/
namespace System.Threading
{
using System;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed class ThreadAbortException : SystemException
{
private ThreadAbortException()
: base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadAbort))
{
SetErrorCode(__HResults.COR_E_THREADABORTED);
}
//required for serialization
internal ThreadAbortException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#if !MONO
public Object ExceptionState
{
[System.Security.SecuritySafeCritical] // auto-generated
get {return Thread.CurrentThread.AbortReason;}
}
#endif
}
}
| mit | C# |
d69a43e3e40e435e81bdbada481f1562e1e5cf4d | Add a few new flags to ApplicationOptions + add generic AdditionalFlags | florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho | bindings/src/ApplicationOptions.cs | bindings/src/ApplicationOptions.cs | using System.Text;
namespace Urho
{
/// <summary>
/// Application options, see full description at:
/// http://urho3d.github.io/documentation/1.4/_running.html
/// </summary>
public class ApplicationOptions
{
/// <summary>
/// Desktop only
/// </summary>
public int Width { get; set; } = 0;
/// <summary>
/// Desktop only
/// </summary>
public int Height { get; set; } = 0;
/// <summary>
/// Desktop only
/// </summary>
public bool WindowedMode { get; set; } = true;
/// <summary>
/// Desktop only
/// </summary>
public bool ResizableWindow { get; set; } = false;
/// <summary>
/// With limit enabled: 200 fps for Desktop (and always 60 fps for mobile despite of the flag)
/// </summary>
public bool LimitFps { get; set; } = true;
/// <summary>
/// iOS only
/// </summary>
public OrientationType Orientation { get; set; } = OrientationType.Landscape;
/// <summary>
/// Resource path(s) to use (default: Data, CoreData)
/// </summary>
public string[] ResourcePaths { get; set; } = null;
/// <summary>
/// Resource package files to use (default: empty)
/// </summary>
public string[] ResourcePackagesPaths { get; set; } = null;
public string AdditionalFlags { get; set; } = string.Empty;
public enum OrientationType
{
Landscape,
Portrait
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("args");//it will be skipped by Urho;
if (WindowedMode)
builder.Append(" -w");
if (!LimitFps)
builder.Append(" -nolimit");
if (Width > 0)
builder.AppendFormat(" -x {0}", Width);
if (Height > 0)
builder.AppendFormat(" -y {0}", Height);
if (ResizableWindow)
builder.Append(" -s");
if (ResourcePaths?.Length > 0)
builder.AppendFormat(" -p '{0}'", string.Join(";", ResourcePaths));
if (ResourcePackagesPaths?.Length > 0)
builder.AppendFormat(" -pf '{0}'", string.Join(";", ResourcePackagesPaths));
builder.AppendFormat(" -{0}", Orientation.ToString().ToLower());
return builder + " " + AdditionalFlags;
}
// Some predefined:
public static ApplicationOptions Default { get; } = new ApplicationOptions();
public static ApplicationOptions PortraitDefault { get; } = new ApplicationOptions { Height = 800, Width = 500, Orientation = OrientationType.Portrait };
}
}
| using System.Text;
namespace Urho
{
/// <summary>
/// Application options, see full description at:
/// http://urho3d.github.io/documentation/1.4/_running.html
/// </summary>
public class ApplicationOptions
{
/// <summary>
/// Desktop only
/// </summary>
public int Width { get; set; } = 0;
/// <summary>
/// Desktop only
/// </summary>
public int Height { get; set; } = 0;
/// <summary>
/// Desktop only
/// </summary>
public bool WindowedMode { get; set; } = true;
/// <summary>
/// Desktop only
/// </summary>
public bool ResizableWindow { get; set; } = false;
/// <summary>
/// With limit enabled: 200 fps for Desktop (and always 60 fps for mobile despite of the flag)
/// </summary>
public bool LimitFps { get; set; } = true;
/// <summary>
/// iOS only
/// </summary>
public OrientationType Orientation { get; set; } = OrientationType.Landscape;
public enum OrientationType
{
Landscape,
Portrait
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("args");//it will be skipped by Urho;
if (WindowedMode)
builder.Append(" -w");
if (!LimitFps)
builder.Append(" -nolimit");
if (Width > 0)
builder.AppendFormat(" -x {0}", Width);
if (Height > 0)
builder.AppendFormat(" -y {0}", Height);
if (ResizableWindow)
builder.Append(" -s");
builder.AppendFormat(" -{0}", Orientation.ToString().ToLower());
return builder.ToString();
}
// Some predefined:
public static ApplicationOptions Default { get; } = new ApplicationOptions();
public static ApplicationOptions PortraitDefault { get; } = new ApplicationOptions { Height = 800, Width = 500, Orientation = OrientationType.Portrait };
}
}
| mit | C# |
fa872858b592278b7672c16fbd840825d8ac7a24 | Remove unnecessary check | UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,peppy/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu | osu.Game/Screens/Play/HUD/HitErrorMeters/HitErrorMeter.cs | osu.Game/Screens/Play/HUD/HitErrorMeters/HitErrorMeter.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osuTK.Graphics;
namespace osu.Game.Screens.Play.HUD.HitErrorMeters
{
public abstract class HitErrorMeter : CompositeDrawable
{
protected readonly HitWindows HitWindows;
[Resolved]
private ScoreProcessor processor { get; set; }
[Resolved]
private OsuColour colours { get; set; }
protected HitErrorMeter(HitWindows hitWindows)
{
HitWindows = hitWindows;
}
protected override void LoadComplete()
{
base.LoadComplete();
processor.NewJudgement += onNewJudgement;
}
private void onNewJudgement(JudgementResult result)
{
if (result.HitObject.HitWindows?.WindowFor(HitResult.Miss) == 0)
return;
OnNewJudgement(result);
}
protected abstract void OnNewJudgement(JudgementResult judgement);
protected Color4 GetColourForHitResult(HitResult result)
{
switch (result)
{
case HitResult.Miss:
return colours.Red;
case HitResult.Meh:
return colours.Yellow;
case HitResult.Ok:
return colours.Green;
case HitResult.Good:
return colours.GreenLight;
case HitResult.Great:
return colours.Blue;
default:
return colours.BlueLight;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (processor != null)
processor.NewJudgement -= onNewJudgement;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osuTK.Graphics;
namespace osu.Game.Screens.Play.HUD.HitErrorMeters
{
public abstract class HitErrorMeter : CompositeDrawable
{
protected readonly HitWindows HitWindows;
[Resolved]
private ScoreProcessor processor { get; set; }
[Resolved]
private OsuColour colours { get; set; }
protected HitErrorMeter(HitWindows hitWindows)
{
HitWindows = hitWindows;
}
protected override void LoadComplete()
{
base.LoadComplete();
if (processor != null)
processor.NewJudgement += onNewJudgement;
}
private void onNewJudgement(JudgementResult result)
{
if (result.HitObject.HitWindows?.WindowFor(HitResult.Miss) == 0)
return;
OnNewJudgement(result);
}
protected abstract void OnNewJudgement(JudgementResult judgement);
protected Color4 GetColourForHitResult(HitResult result)
{
switch (result)
{
case HitResult.Miss:
return colours.Red;
case HitResult.Meh:
return colours.Yellow;
case HitResult.Ok:
return colours.Green;
case HitResult.Good:
return colours.GreenLight;
case HitResult.Great:
return colours.Blue;
default:
return colours.BlueLight;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (processor != null)
processor.NewJudgement -= onNewJudgement;
}
}
}
| mit | C# |
af129b3eaba1233654e87b6de4185876933ba033 | Add siblings, will be used in generator branches. | osu-RP/osu-RP,DrabWeb/osu,johnneijzen/osu,ZLima12/osu,EVAST9919/osu,smoogipooo/osu,Frontear/osuKyzer,naoey/osu,ZLima12/osu,peppy/osu-new,Nabile-Rahmani/osu,ppy/osu,DrabWeb/osu,DrabWeb/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,Damnae/osu,UselessToucan/osu,UselessToucan/osu,naoey/osu,ppy/osu,naoey/osu,tacchinotacchi/osu,peppy/osu,peppy/osu,Drezi126/osu,peppy/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu | osu.Game.Rulesets.Mania/Objects/ManiaHitObject.cs | osu.Game.Rulesets.Mania/Objects/ManiaHitObject.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Mania.Objects.Types;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Rulesets.Mania.Objects
{
public abstract class ManiaHitObject : HitObject, IHasColumn
{
public int Column { get; set; }
/// <summary>
/// The number of other <see cref="ManiaHitObject"/> that start at
/// the same time as this hit object.
/// </summary>
public int Siblings { get; set; }
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Mania.Objects.Types;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Rulesets.Mania.Objects
{
public abstract class ManiaHitObject : HitObject, IHasColumn
{
public int Column { get; set; }
}
}
| mit | C# |
c508e75124ee01bda66edea97e904cfd511609d0 | Update CommandHelpService - mark fields as readonly | mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX | Modix.Services/CommandHelp/CommandHelpService.cs | Modix.Services/CommandHelp/CommandHelpService.cs | using System.Collections.Generic;
using System.Linq;
using Discord.Commands;
namespace Modix.Services.CommandHelp
{
public class CommandHelpService
{
private readonly CommandService _commandService;
private List<ModuleHelpData> _cachedHelpData;
public CommandHelpService(CommandService commandService)
{
_commandService = commandService;
}
public List<ModuleHelpData> GetData()
{
if (_cachedHelpData == null)
{
_cachedHelpData = new List<ModuleHelpData>();
foreach (var module in _commandService.Modules)
{
if (module.Attributes.Any(attr => attr is HiddenFromHelpAttribute))
{
continue;
}
_cachedHelpData.Add(ModuleHelpData.FromModuleInfo(module));
}
}
return _cachedHelpData;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Discord.Commands;
namespace Modix.Services.CommandHelp
{
public class CommandHelpService
{
private CommandService _commandService;
private List<ModuleHelpData> _cachedHelpData;
public CommandHelpService(CommandService commandService)
{
_commandService = commandService;
}
public List<ModuleHelpData> GetData()
{
if (_cachedHelpData == null)
{
_cachedHelpData = new List<ModuleHelpData>();
foreach (var module in _commandService.Modules)
{
if (module.Attributes.Any(attr => attr is HiddenFromHelpAttribute))
{
continue;
}
_cachedHelpData.Add(ModuleHelpData.FromModuleInfo(module));
}
}
return _cachedHelpData;
}
}
}
| mit | C# |
69a0fbe7ac2782c787c7cc77e4245157168e695c | use appropriate Building ctor | AlexanderMazaletskiy/ProceduralBuildings,tkaretsos/ProceduralBuildings | Scripts/CityMapController.cs | Scripts/CityMapController.cs | using UnityEngine;
using Thesis;
using System.Linq;
public class CityMapController : MonoBehaviour {
Block block;
void Awake ()
{
ColorManager.Instance.Init();
TextureManager.Instance.Init();
MaterialManager.Instance.Init();
// the point Vector3.zero must _not_ be used
// as starting point and all 4 points must be
// in the first quadrant
block = new Block(new Vector3(1f, 0f, 0f),
new Vector3(0f, 0f, 300f),
new Vector3(500f, 0f, 300f),
new Vector3(500f, 0f, 0f));
block.Bisect();
}
void Update ()
{
foreach (Block b in CityMapManager.Instance.blocks)
{
foreach (BuildingLot l in b.finalLots)
foreach (Edge e in l.edges)
Debug.DrawLine(e.start, e.end, Color.cyan);
foreach (Edge e in b.edges)
Debug.DrawLine(e.start, e.end, Color.green);
}
if (Input.GetKeyUp(KeyCode.B))
{
AddBuildings();
foreach (Block b in CityMapManager.Instance.blocks)
b.Draw();
}
}
private void AddBuildings ()
{
Building building;
foreach (Block b in CityMapManager.Instance.blocks)
foreach (BuildingLot l in b.finalLots)
{
building = new Building(l);
building.buildingMesh.FindVertices();
building.buildingMesh.FindTriangles();
building.buildingMesh.Draw();
building.CombineSubmeshes();
building.gameObject.SetActiveRecursively(true);
}
}
} | using UnityEngine;
using Thesis;
using System.Linq;
public class CityMapController : MonoBehaviour {
Block block;
void Awake ()
{
ColorManager.Instance.Init();
TextureManager.Instance.Init();
MaterialManager.Instance.Init();
// the point Vector3.zero must _not_ be used
// as starting point and all 4 points must be
// in the first quadrant
block = new Block(new Vector3(1f, 0f, 0f),
new Vector3(0f, 0f, 300f),
new Vector3(500f, 0f, 300f),
new Vector3(500f, 0f, 0f));
block.Bisect();
}
void Update ()
{
foreach (Block b in CityMapManager.Instance.blocks)
{
foreach (BuildingLot l in b.finalLots)
foreach (Edge e in l.edges)
Debug.DrawLine(e.start, e.end, Color.cyan);
foreach (Edge e in b.edges)
Debug.DrawLine(e.start, e.end, Color.green);
}
if (Input.GetKeyUp(KeyCode.B))
{
AddBuildings();
foreach (Block b in CityMapManager.Instance.blocks)
b.Draw();
}
}
private void AddBuildings ()
{
Building building;
foreach (Block b in CityMapManager.Instance.blocks)
foreach (BuildingLot l in b.finalLots)
{
building = new Building(l.edges[0].start,
l.edges[1].start,
l.edges[2].start,
l.edges[3].start);
building.buildingMesh.FindVertices();
building.buildingMesh.FindTriangles();
building.buildingMesh.Draw();
building.CombineSubmeshes();
building.gameObject.SetActiveRecursively(true);
}
}
} | mit | C# |
890145fce9df3a0784ea236a0a9f3ff4d98202f8 | fix Playground | Fangh/LoveLetter | Assets/Scripts/Playground.cs | Assets/Scripts/Playground.cs | using UnityEngine;
using System.Collections;
public class Playground : MonoBehaviour {
OvrAvatarHand hand = null;
public bool needHeadset = false;
bool headsetPresent = false;
public bool validGameState = false;
Material mat;
Color errorColor = new Color(1f, 0.3f, 0.3f);
Color validColor = new Color(0.3f, 1, 0.3f);
// Use this for initialization
void Start () {
mat = GetComponent<Renderer>().material;
}
// Update is called once per frame
void Update () {
mat.color = validGameState ? validColor : errorColor;
}
void OnTriggerStay(Collider other)
{
if (hand == null)
{
if (other.GetComponent<OvrAvatarHand>() != null)
{
hand = other.GetComponent<OvrAvatarHand>();
}
}
else
{
if (needHeadset && other.GetComponent<OVRCameraRig>() != null)
{
headsetPresent = (other.GetComponent<OVRCameraRig>() != null);
}
if (other.GetComponent<OvrAvatarHand>() != null)
{
validGameState = needHeadset ? (headsetPresent && checkHand(other.GetComponent<OvrAvatarHand>()) ) : checkHand(other.GetComponent<OvrAvatarHand>());
}
}
}
bool checkHand(OvrAvatarHand unknownHand)
{
return (hand == unknownHand);
}
void OnTriggerExit(Collider other)
{
if (hand != null) {
validGameState = checkHand(other.GetComponent<OvrAvatarHand>());
}
}
} | using UnityEngine;
using System.Collections;
public class Playground : MonoBehaviour {
OvrAvatarHand hand = null;
public bool needHeadset = false;
bool headsetPresent = false;
public bool validGameState = false;
Material mat;
Color errorColor = new Color(1f, 0.3f, 0.3f, 0.1f);
Color validColor = new Color(0.3f, 1, 0.3f, 0.1f);
// Use this for initialization
void Start () {
mat = GetComponent<Renderer>().material;
}
// Update is called once per frame
void Update () {
mat.color = validGameState ? validColor : errorColor;
}
void OnTriggerStay(Collider other)
{
if (hand == null)
{
if (other.GetComponent<OvrAvatarHand>() != null)
{
hand = other.GetComponent<OvrAvatarHand>();
}
}
else
{
if (needHeadset && other.GetComponent<OVRCameraRig>() != null)
{
headsetPresent = other.GetComponent<OVRCameraRig>() != null;
}
if (other.GetComponent<OvrAvatarHand>() != null)
{
validGameState = needHeadset ? (headsetPresent && hand == other.GetComponent<OvrAvatarHand>()) : hand == other.GetComponent<OvrAvatarHand>();
}
}
}
void OnTriggerExit(Collider other)
{
if (hand != null) {
validGameState = (hand == other.GetComponent<OvrAvatarHand>());
}
}
} | unlicense | C# |
9a9606fee075ab63f872098b5e88fa54d58c902d | Remove redundant code | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade/Core/ArchiveContentReader.cs | src/Arkivverket.Arkade/Core/ArchiveContentReader.cs | using System;
using System.IO;
using Arkivverket.Arkade.Resources;
namespace Arkivverket.Arkade.Core
{
public class ArchiveContentReader : IArchiveContentReader
{
public Stream GetContentAsStream(Archive archive)
{
string fileName = archive.GetContentDescriptionFileName();
return GetFileAsStream(fileName);
}
public Stream GetStructureContentAsStream(Archive archive)
{
string fileName = archive.GetStructureDescriptionFileName();
return GetFileAsStream(fileName);
}
public Stream GetContentDescriptionXmlSchemaAsStream(Archive archive)
{
string fileName = archive.GetContentDescriptionXmlSchemaFileName();
return GetFileAsStream(fileName);
}
public Stream GetStructureDescriptionXmlSchemaAsStream(Archive archive)
{
string fileName = archive.GetStructureDescriptionXmlSchemaFileName();
return GetFileAsStream(fileName);
}
public Stream GetMetadataCatalogXmlSchemaAsStream(Archive archive)
{
string fileName = archive.GetMetadataCatalogXmlSchemaFileName();
return GetFileAsStream(fileName);
}
private static Stream GetFileAsStream(string fileName)
{
try
{
return File.OpenRead(fileName);
}
catch (Exception e)
{
string message = string.Format(Messages.FileNotFoundMessage, fileName);
throw new ArkadeException(message, e);
}
}
}
} | using System;
using System.IO;
using Arkivverket.Arkade.Resources;
using Arkivverket.Arkade.Util;
namespace Arkivverket.Arkade.Core
{
public class ArchiveContentReader : IArchiveContentReader
{
public Stream GetContentAsStream(Archive archive)
{
string fileName = archive.GetContentDescriptionFileName();
return GetFileAsStream(fileName);
}
public Stream GetStructureContentAsStream(Archive archive)
{
string fileName = archive.GetStructureDescriptionFileName();
return GetFileAsStream(fileName);
}
public Stream GetContentDescriptionXmlSchemaAsStream(Archive archive)
{
string fileName = archive.GetContentDescriptionXmlSchemaFileName();
return GetFileAsStream(fileName);
}
public Stream GetStructureDescriptionXmlSchemaAsStream(Archive archive)
{
string fileName = archive.GetStructureDescriptionXmlSchemaFileName();
return GetFileAsStream(fileName);
}
public Stream GetMetadataCatalogXmlSchemaAsStream(Archive archive)
{
string fileName = archive.GetMetadataCatalogXmlSchemaFileName();
return GetFileAsStream(fileName);
}
private static Stream GetFileAsStream(string fileName)
{
var fileInfo = new FileInfo(fileName);
try
{
return fileInfo.OpenRead();
}
catch (Exception e)
{
if(fileName.Contains(ArkadeConstants.GetArkadeWorkDirectory().Name))
fileName = fileInfo.Name;
string message = string.Format(Messages.FileNotFoundMessage, fileName);
throw new ArkadeException(message, e);
}
}
}
} | agpl-3.0 | C# |
a9bb7fd7f10d9b9170a5759620c3749357cb42e7 | Make xunit logger warning by default instead of debug | couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net | src/Couchbase.Lite.Tests.Shared/Util/XunitLogger.cs | src/Couchbase.Lite.Tests.Shared/Util/XunitLogger.cs | //
// XunitLogger.cs
//
// Copyright (c) 2017 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.
//
#if !WINDOWS_UWP
using System;
using Couchbase.Lite.Logging;
using Xunit.Abstractions;
namespace Test.Util
{
internal sealed class XunitLogger : ILogger
{
#region Variables
private readonly ITestOutputHelper _output;
#endregion
#region Properties
public LogLevel Level { get; set; } = LogLevel.Warning;
#endregion
#region Constructors
public XunitLogger(ITestOutputHelper output)
{
_output = output;
}
#endregion
#region ILogger
public void Log(LogLevel level, LogDomain domain, string message)
{
if (level < Level) {
return;
}
try {
_output.WriteLine($"{level.ToString().ToUpperInvariant()}) {domain} {message}");
} catch (Exception) {
// _output is busted, the test is probably already finished. Nothing we can do
}
}
#endregion
}
}
#else
using System;
using Couchbase.Lite.DI;
using Couchbase.Lite.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test.Util
{
internal sealed class MSTestLogger : ILogger
{
#region Variables
private readonly TestContext _output;
#endregion
#region Properties
public LogLevel Level { get; set; } = LogLevel.Warning;
#endregion
#region Constructors
public MSTestLogger(TestContext output)
{
_output = output;
}
#endregion
#region ILogger
public void Log(LogLevel level, LogDomain domain, string message)
{
if (level < Level) {
return;
}
_output.WriteLine($"{level.ToString().ToUpperInvariant()}) {domain} {message}");
}
#endregion
}
}
#endif | //
// XunitLogger.cs
//
// Copyright (c) 2017 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.
//
#if !WINDOWS_UWP
using System;
using Couchbase.Lite.Logging;
using Xunit.Abstractions;
namespace Test.Util
{
internal sealed class XunitLogger : ILogger
{
#region Variables
private readonly ITestOutputHelper _output;
#endregion
#region Properties
public LogLevel Level { get; set; }
#endregion
#region Constructors
public XunitLogger(ITestOutputHelper output)
{
_output = output;
}
#endregion
#region ILogger
public void Log(LogLevel level, LogDomain domain, string message)
{
if (level < Level) {
return;
}
try {
_output.WriteLine($"{level.ToString().ToUpperInvariant()}) {domain} {message}");
} catch (Exception) {
// _output is busted, the test is probably already finished. Nothing we can do
}
}
#endregion
}
}
#else
using System;
using Couchbase.Lite.DI;
using Couchbase.Lite.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test.Util
{
internal sealed class MSTestLogger : ILogger
{
#region Variables
private readonly TestContext _output;
#endregion
#region Constructors
public MSTestLogger(TestContext output)
{
_output = output;
}
#endregion
public void Log(LogLevel level, LogDomain domain, string message)
{
if (level < Level) {
return;
}
_output.WriteLine($"{level.ToString().ToUpperInvariant()}) {domain} {message}");
}
}
}
#endif | apache-2.0 | C# |
2e95db5f602037cdcb53d2db7dac75708dade96f | update AssemblyInfo | romansp/MiniProfiler.Elasticsearch | src/MiniProfiler.Elasticsearch/Properties/AssemblyInfo.cs | src/MiniProfiler.Elasticsearch/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("MiniProfiler.Elasticsearch")]
[assembly: AssemblyDescription("Elasticsearch extensions for StackExchange.Profiling - http://miniprofiler.com")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("romansp")]
[assembly: AssemblyProduct("StackExchange.Profiling.Elasticsearch")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("ed1db334-f263-4470-9be0-1c1e04c57fd5")]
[assembly: AssemblyVersion("3.2")]
[assembly: AssemblyFileVersion("3.2")] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("MiniProfiler.Elasticsearch")]
[assembly: AssemblyDescription("Elasticsearch extensions for StackExchange.Profiling - http://miniprofiler.com")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("romansp")]
[assembly: AssemblyProduct("StackExchange.Profiling.Elasticsearch")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("ed1db334-f263-4470-9be0-1c1e04c57fd5")]
[assembly: AssemblyVersion("3.1.1.140")]
[assembly: AssemblyFileVersion("3.1.1.140")] | mit | C# |
4bdbc50719b6d87211b54ce5f7f01b6fa5cf1f47 | fix SL builds | zbrad/NLog,littlesmilelove/NLog,zbrad/NLog,babymechanic/NLog,FeodorFitsner/NLog,campbeb/NLog,ajayanandgit/NLog,czema/NLog,sean-gilliam/NLog,breyed/NLog,luigiberrettini/NLog,ajayanandgit/NLog,bryjamus/NLog,michaeljbaird/NLog,AndreGleichner/NLog,RichiCoder1/NLog,bjornbouetsmith/NLog,RRUZ/NLog,MoaidHathot/NLog,rajeshgande/NLog,kevindaub/NLog,RRUZ/NLog,RichiCoder1/NLog,304NotModified/NLog,bjornbouetsmith/NLog,luigiberrettini/NLog,vbfox/NLog,hubo0831/NLog,tetrodoxin/NLog,littlesmilelove/NLog,MartinTherriault/NLog,tmusico/NLog,ilya-g/NLog,ilya-g/NLog,matteobruni/NLog,breyed/NLog,BrutalCode/NLog,Niklas-Peter/NLog,czema/NLog,Niklas-Peter/NLog,czema/NLog,pwelter34/NLog,nazim9214/NLog,UgurAldanmaz/NLog,nazim9214/NLog,ie-zero/NLog,MartinTherriault/NLog,pwelter34/NLog,bhaeussermann/NLog,snakefoot/NLog,tmusico/NLog,NLog/NLog,rajeshgande/NLog,ArsenShnurkov/NLog,tetrodoxin/NLog,matteobruni/NLog,tohosnet/NLog,MoaidHathot/NLog,babymechanic/NLog,AndreGleichner/NLog,BrutalCode/NLog,ie-zero/NLog,vbfox/NLog,kevindaub/NLog,bhaeussermann/NLog,UgurAldanmaz/NLog,hubo0831/NLog,campbeb/NLog,michaeljbaird/NLog,czema/NLog,tohosnet/NLog,FeodorFitsner/NLog,ArsenShnurkov/NLog,bryjamus/NLog | src/NLog/LayoutRenderers/TraceActivityIdLayoutRenderer.cs | src/NLog/LayoutRenderers/TraceActivityIdLayoutRenderer.cs | //
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !SILVERLIGHT4
namespace NLog.LayoutRenderers
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
/// <summary>
/// A renderer that puts into log a System.Diagnostics trace correlation id.
/// </summary>
[LayoutRenderer("activityid")]
public class TraceActivityIdLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Renders the current trace activity ID.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(Guid.Empty.Equals(Trace.CorrelationManager.ActivityId) ?
String.Empty : Trace.CorrelationManager.ActivityId.ToString("D", CultureInfo.InvariantCulture));
}
}
}
#endif | //
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
/// <summary>
/// A renderer that puts into log a System.Diagnostics trace correlation id.
/// </summary>
[LayoutRenderer("activityid")]
public class TraceActivityIdLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Renders the current trace activity ID.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(Guid.Empty.Equals(Trace.CorrelationManager.ActivityId) ?
String.Empty : Trace.CorrelationManager.ActivityId.ToString("D", CultureInfo.InvariantCulture));
}
}
} | bsd-3-clause | C# |
735db74d21fbe0e4318d84fa00baf9d22d1488ce | remove null check already present in RabbitMqMessageBus | mdevilliers/SignalR.RabbitMq,slovely/SignalR.RabbitMq,mdevilliers/SignalR.RabbitMq,slovely/SignalR.RabbitMq | SignalR.RabbitMQ/DependencyResolverExtensions.cs | SignalR.RabbitMQ/DependencyResolverExtensions.cs | using System;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Messaging;
namespace SignalR.RabbitMQ
{
public static class DependencyResolverExtensions
{
public static IDependencyResolver UseRabbitMq(this IDependencyResolver resolver, RabbitMqScaleoutConfiguration configuration)
{
return RegisterBus(resolver, configuration);
}
public static IDependencyResolver UseRabbitMqAdvanced(this IDependencyResolver resolver, RabbitConnectionBase myConnection, RabbitMqScaleoutConfiguration configuration)
{
return RegisterBus(resolver, configuration, myConnection);
}
private static IDependencyResolver RegisterBus(IDependencyResolver resolver, RabbitMqScaleoutConfiguration configuration, RabbitConnectionBase advancedConnectionInstance = null)
{
RabbitMqMessageBus bus = null;
var initialized = false;
var syncLock = new object();
Func<RabbitMqMessageBus> busFactory = () => new RabbitMqMessageBus(resolver, configuration, advancedConnectionInstance);
resolver.Register(typeof (IMessageBus), () => LazyInitializer.EnsureInitialized(ref bus, ref initialized, ref syncLock, busFactory));
return resolver;
}
}
}
| using System;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Messaging;
namespace SignalR.RabbitMQ
{
public static class DependencyResolverExtensions
{
public static IDependencyResolver UseRabbitMq(this IDependencyResolver resolver, RabbitMqScaleoutConfiguration configuration)
{
return RegisterBus(resolver, configuration);
}
public static IDependencyResolver UseRabbitMqAdvanced(this IDependencyResolver resolver, RabbitConnectionBase myConnection, RabbitMqScaleoutConfiguration configuration)
{
return RegisterBus(resolver, configuration, myConnection);
}
private static IDependencyResolver RegisterBus(IDependencyResolver resolver, RabbitMqScaleoutConfiguration configuration, RabbitConnectionBase advancedConnectionInstance = null)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
RabbitMqMessageBus bus = null;
var initialized = false;
var syncLock = new object();
Func<RabbitMqMessageBus> busFactory = () => new RabbitMqMessageBus(resolver, configuration, advancedConnectionInstance);
resolver.Register(typeof (IMessageBus), () => LazyInitializer.EnsureInitialized(ref bus, ref initialized, ref syncLock, busFactory));
return resolver;
}
}
}
| mit | C# |
2c5ceac49ee2ea9f3fbcdd7ae7a1029acdfbba6d | Increment minor version | emoacht/SnowyImageCopy | Source/SnowyImageCopy/Properties/AssemblyInfo.cs | Source/SnowyImageCopy/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Snowy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Snowy")]
[assembly: AssemblyCopyright("Copyright © 2014-2020 emoacht")]
[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("55df0585-a26e-489e-bd94-4e6a50a83e23")]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.2.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
// For unit test
[assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Snowy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Snowy")]
[assembly: AssemblyCopyright("Copyright © 2014-2020 emoacht")]
[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("55df0585-a26e-489e-bd94-4e6a50a83e23")]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.1.0")]
[assembly: AssemblyFileVersion("2.1.1.0")]
// For unit test
[assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
| mit | C# |
4841457c10b1dcc15645c13dc9535b0f05e96696 | Fix exception when typing in a decimal point for a number. | mrward/typescript-addin,chrisber/typescript-addin,mrward/typescript-addin,chrisber/typescript-addin | src/TypeScriptBinding/TypeScriptCompletionItemProvider.cs | src/TypeScriptBinding/TypeScriptCompletionItemProvider.cs | //
// TypeScriptCompletionItemProvider.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (C) 2013 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using ICSharpCode.SharpDevelop.Editor;
using ICSharpCode.SharpDevelop.Editor.CodeCompletion;
using ICSharpCode.TypeScriptBinding.Hosting;
namespace ICSharpCode.TypeScriptBinding
{
public class TypeScriptCompletionItemProvider : AbstractCompletionItemProvider
{
TypeScriptContext context;
bool memberCompletion;
public TypeScriptCompletionItemProvider(TypeScriptContext context)
{
this.context = context;
}
public bool ShowCompletion(ITextEditor editor, bool memberCompletion)
{
this.memberCompletion = memberCompletion;
ICompletionItemList list = GenerateCompletionList(editor);
if (list.Items.Any()) {
editor.ShowCompletionWindow(list);
return true;
}
return false;
}
public override ICompletionItemList GenerateCompletionList(ITextEditor editor)
{
CompletionInfo result = context.GetCompletionItems(
editor.FileName,
editor.Caret.Offset,
editor.Document.Text,
memberCompletion);
var itemList = new DefaultCompletionItemList();
if (result != null) {
itemList.Items.AddRange(result.entries.Select(entry => new TypeScriptCompletionItem(entry)));
}
return itemList;
}
}
}
| //
// TypeScriptCompletionItemProvider.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (C) 2013 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using ICSharpCode.SharpDevelop.Editor;
using ICSharpCode.SharpDevelop.Editor.CodeCompletion;
using ICSharpCode.TypeScriptBinding.Hosting;
namespace ICSharpCode.TypeScriptBinding
{
public class TypeScriptCompletionItemProvider : AbstractCompletionItemProvider
{
TypeScriptContext context;
bool memberCompletion;
public TypeScriptCompletionItemProvider(TypeScriptContext context)
{
this.context = context;
}
public bool ShowCompletion(ITextEditor editor, bool memberCompletion)
{
this.memberCompletion = memberCompletion;
ICompletionItemList list = GenerateCompletionList(editor);
if (list.Items.Any()) {
editor.ShowCompletionWindow(list);
return true;
}
return false;
}
public override ICompletionItemList GenerateCompletionList(ITextEditor editor)
{
CompletionInfo result = context.GetCompletionItems(
editor.FileName,
editor.Caret.Offset,
editor.Document.Text,
memberCompletion);
var itemList = new DefaultCompletionItemList();
itemList.Items.AddRange(result.entries.Select(entry => new TypeScriptCompletionItem(entry)));
return itemList;
}
}
}
| mit | C# |
9e308f42041e0baa1fd4c86c11b9fbb732c96001 | embed and download media as additional UI Hint options | Riksarkivet/iiif-model,digirati-co-uk/iiif-model | Digirati.IxIF/UVExtensions/UserInterfaceHints.cs | Digirati.IxIF/UVExtensions/UserInterfaceHints.cs | using Digirati.IIIF.Model.Types;
using Digirati.IxIF;
using Newtonsoft.Json;
namespace Digirati.IIIF.UVExtensions
{
public class UserInterfaceHints : GenericService
{
public override dynamic Context
{
get { return ExtensionUriPatterns.WdlExtensionsContext; }
}
public override dynamic Profile
{
get { return "http://universalviewer.io/ui-extensions-profile"; }
}
// do we need an extra setting to tell a viewer whether it can "pull through" (import into interface)?
[JsonProperty(Order = 102, PropertyName = "manifestType")]
public string ManifestType { get; set; }
[JsonProperty(Order = 104, PropertyName = "suppressMetadata")]
public string[] SuppressMetadata { get; set; }
[JsonProperty(Order = 110, PropertyName = "allowEmbed")]
public bool AllowEmbed { get; set; }
[JsonProperty(Order = 111, PropertyName = "allowMediaDownload")]
public bool AllowMediaDownload { get; set; }
}
}
| using Digirati.IIIF.Model.Types;
using Digirati.IxIF;
using Newtonsoft.Json;
namespace Digirati.IIIF.UVExtensions
{
public class UserInterfaceHints : GenericService
{
public override dynamic Context
{
get { return ExtensionUriPatterns.WdlExtensionsContext; }
}
public override dynamic Profile
{
get { return "http://universalviewer.io/ui-extensions-profile"; }
}
// do we need an extra setting to tell a viewer whether it can "pull through" (import into interface)?
[JsonProperty(Order = 102, PropertyName = "manifestType")]
public string ManifestType { get; set; }
[JsonProperty(Order = 104, PropertyName = "suppressMetadata")]
public string[] SuppressMetadata { get; set; }
}
}
| mit | C# |
76314fe193306f89b762d12657f57dd9f4748eab | Simplify property name for LineItemMembershipSubject | andyfmiller/LtiLibrary | LtiLibrary.Core/Outcomes/v2/LineItemContainer.cs | LtiLibrary.Core/Outcomes/v2/LineItemContainer.cs | using LtiLibrary.Core.Common;
using Newtonsoft.Json;
namespace LtiLibrary.Core.Outcomes.v2
{
/// <summary>
/// A LineItemContainer defines the endpoint to which clients POST new LineItem resources
/// and from which they GET the list of LineItems associated with a a given learning context.
/// </summary>
public class LineItemContainer : JsonLdObject
{
public LineItemContainer()
{
Type = LtiConstants.LineItemContainerType;
}
/// <summary>
/// Optional indication of which resource is the subject for the members of the container.
/// </summary>
[JsonProperty("membershipSubject")]
public LineItemMembershipSubject MembershipSubject { get; set; }
}
}
| using LtiLibrary.Core.Common;
using Newtonsoft.Json;
namespace LtiLibrary.Core.Outcomes.v2
{
/// <summary>
/// A LineItemContainer defines the endpoint to which clients POST new LineItem resources
/// and from which they GET the list of LineItems associated with a a given learning context.
/// </summary>
public class LineItemContainer : JsonLdObject
{
public LineItemContainer()
{
Type = LtiConstants.LineItemContainerType;
}
/// <summary>
/// Optional indication of which resource is the subject for the members of the container.
/// </summary>
[JsonProperty("membershipSubject")]
public LineItemMembershipSubject LineItemMembershipSubject { get; set; }
}
}
| apache-2.0 | C# |
19102bc48caddb9cd1e129a7364459a8620605e7 | Update TestEngine | yishn/GTPWrapper | GTPWrapperTest/TestEngine.cs | GTPWrapperTest/TestEngine.cs | using GTPWrapper;
using GTPWrapper.DataTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GTPWrapperTest {
public class TestEngine : Engine {
public TestEngine() : base("GTP Test Engine", "1.0") {
this.SupportedCommands.AddRange(new string[] { "error" });
}
protected override Response ExecuteCommand(Command command) {
switch (command.Name) {
case "error":
return new Response(command, "an expected error occurred", true);
}
return base.ExecuteCommand(command);
}
protected override Vertex? GenerateMove(Color color) {
return Vertex.Pass;
}
}
}
| using GTPWrapper;
using GTPWrapper.DataTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GTPWrapperTest {
public class TestEngine : Engine {
public TestEngine() : base("GTP Test Engine", "1.0") {
this.SupportedCommands.AddRange(new string[] { "error" });
}
protected override Response ExecuteCommand(Command command) {
switch (command.Name) {
case "error":
return new Response(command, "an expected error occurred", true);
}
return base.ExecuteCommand(command);
}
}
}
| mit | C# |
a93b22803dfb1384bb7055f0798b0f55f5212985 | Fix wrong property mapping in SearchShard | KodrAus/elasticsearch-net,RossLieberman/NEST,starckgates/elasticsearch-net,gayancc/elasticsearch-net,amyzheng424/elasticsearch-net,CSGOpenSource/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,ststeiger/elasticsearch-net,DavidSSL/elasticsearch-net,jonyadamit/elasticsearch-net,DavidSSL/elasticsearch-net,UdiBen/elasticsearch-net,joehmchan/elasticsearch-net,robertlyson/elasticsearch-net,faisal00813/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,geofeedia/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,elastic/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,geofeedia/elasticsearch-net,starckgates/elasticsearch-net,CSGOpenSource/elasticsearch-net,tkirill/elasticsearch-net,LeoYao/elasticsearch-net,azubanov/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,jonyadamit/elasticsearch-net,LeoYao/elasticsearch-net,junlapong/elasticsearch-net,mac2000/elasticsearch-net,tkirill/elasticsearch-net,robrich/elasticsearch-net,KodrAus/elasticsearch-net,joehmchan/elasticsearch-net,robrich/elasticsearch-net,gayancc/elasticsearch-net,abibell/elasticsearch-net,wawrzyn/elasticsearch-net,amyzheng424/elasticsearch-net,cstlaurent/elasticsearch-net,wawrzyn/elasticsearch-net,starckgates/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,SeanKilleen/elasticsearch-net,adam-mccoy/elasticsearch-net,junlapong/elasticsearch-net,UdiBen/elasticsearch-net,faisal00813/elasticsearch-net,SeanKilleen/elasticsearch-net,TheFireCookie/elasticsearch-net,robertlyson/elasticsearch-net,adam-mccoy/elasticsearch-net,jonyadamit/elasticsearch-net,amyzheng424/elasticsearch-net,LeoYao/elasticsearch-net,ststeiger/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,ststeiger/elasticsearch-net,tkirill/elasticsearch-net,elastic/elasticsearch-net,SeanKilleen/elasticsearch-net,KodrAus/elasticsearch-net,joehmchan/elasticsearch-net,robertlyson/elasticsearch-net,DavidSSL/elasticsearch-net,gayancc/elasticsearch-net,junlapong/elasticsearch-net,geofeedia/elasticsearch-net | src/Nest/Domain/Responses/SearchShardsResponse.cs | src/Nest/Domain/Responses/SearchShardsResponse.cs | using Nest.Domain;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Nest
{
[JsonObject(MemberSerialization.OptIn)]
public interface ISearchShardsResponse : IResponse
{
[JsonProperty("shards")]
IEnumerable<IEnumerable<SearchShard>> Shards { get; }
[JsonProperty("nodes")]
IDictionary<string, SearchNode> Nodes { get; }
}
public class SearchShardsResponse : BaseResponse, ISearchShardsResponse
{
public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; }
public IDictionary<string, SearchNode> Nodes { get; internal set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class SearchNode
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("transport_address")]
public string TransportAddress { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class SearchShard
{
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("primary")]
public bool Primary { get; set; }
[JsonProperty("node")]
public string Node { get; set; }
[JsonProperty("relocating_node")]
public string RelocatingNode { get; set; }
[JsonProperty("shard")]
public int Shard { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
}
} | using System.Collections.Generic;
using Nest.Domain;
using Newtonsoft.Json;
using System.Linq.Expressions;
using System;
using System.Linq;
namespace Nest
{
[JsonObject(MemberSerialization.OptIn)]
public interface ISearchShardsResponse : IResponse
{
[JsonProperty("shards")]
IEnumerable<IEnumerable<SearchShard>> Shards { get; }
[JsonProperty("nodes")]
IDictionary<string, SearchNode> Nodes { get; }
}
public class SearchShardsResponse : BaseResponse, ISearchShardsResponse
{
public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; }
public IDictionary<string, SearchNode> Nodes { get; internal set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class SearchNode
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("transport_address")]
public string TransportAddress { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class SearchShard
{
[JsonProperty("name")]
public string State { get; set;}
[JsonProperty("primary")]
public bool Primary { get; set;}
[JsonProperty("node")]
public string Node { get; set;}
[JsonProperty("relocating_node")]
public string RelocatingNode { get; set;}
[JsonProperty("shard")]
public int Shard { get; set;}
[JsonProperty("index")]
public string Index { get; set;}
}
} | apache-2.0 | C# |
076fc71a503aea40e942cc7de8f2d82f4a733693 | Extend language service for RTL languages | emoacht/Monitorian | Source/Monitorian.Core/Models/LanguageService.cs | Source/Monitorian.Core/Models/LanguageService.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Monitorian.Core.Properties;
namespace Monitorian.Core.Models
{
public class LanguageService
{
public static IReadOnlyCollection<string> Options => new[] { Option };
private const string Option = "/lang";
private static readonly Lazy<CultureInfo> _culture = new(() =>
{
var arguments = AppKeeper.DefinedArguments;
int i = 0;
while (i < arguments.Count - 1)
{
if (string.Equals(arguments[i], Option, StringComparison.OrdinalIgnoreCase))
{
var cultureName = arguments[i + 1];
return CultureInfo.GetCultures(CultureTypes.AllCultures)
.FirstOrDefault(x => string.Equals(x.Name, cultureName, StringComparison.OrdinalIgnoreCase));
}
i++;
}
return null;
});
public static IReadOnlyDictionary<string, string> ResourceDictionary => _resourceDictionary.Value;
private static readonly Lazy<Dictionary<string, string>> _resourceDictionary = new(() =>
{
if (_culture.Value is not null)
{
var resourceSet = new ResourceManager(typeof(Resources)).GetResourceSet(_culture.Value, true, false);
if (resourceSet is not null)
{
return resourceSet.Cast<DictionaryEntry>()
.Where(x => x.Key is string)
.ToDictionary(x => (string)x.Key, x => x.Value?.ToString());
}
}
return new Dictionary<string, string>();
});
public static bool IsResourceRightToLeft => (_culture.Value?.TextInfo.IsRightToLeft is true);
/// <summary>
/// Switches default and current threads' culture.
/// </summary>
/// <returns>True if successfully switches the culture</returns>
public static bool SwitchDefault()
{
var culture = _culture.Value;
if (culture is null)
return false;
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
return Switch();
}
/// <summary>
/// Switches current thread's culture.
/// </summary>
/// <returns>True if successfully switches the culture</returns>
public static bool Switch()
{
var culture = _culture.Value;
if (culture is null)
return false;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
return true;
}
}
} | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Monitorian.Core.Models
{
public class LanguageService
{
public static IReadOnlyCollection<string> Options => new[] { Option };
private const string Option = "/lang";
private static readonly Lazy<CultureInfo> _culture = new(() =>
{
var arguments = AppKeeper.DefinedArguments;
int i = 0;
while (i < arguments.Count - 1)
{
if (string.Equals(arguments[i], Option, StringComparison.OrdinalIgnoreCase))
{
var cultureName = arguments[i + 1];
return CultureInfo.GetCultures(CultureTypes.AllCultures)
.FirstOrDefault(x => string.Equals(x.Name, cultureName, StringComparison.OrdinalIgnoreCase));
}
i++;
}
return null;
});
/// <summary>
/// Switches default and current threads' culture.
/// </summary>
/// <returns>True if successfully switches the culture</returns>
public static bool SwitchDefault()
{
var culture = _culture.Value;
if (culture is null)
return false;
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
return Switch();
}
/// <summary>
/// Switches current thread's culture.
/// </summary>
/// <returns>True if successfully switches the culture</returns>
public static bool Switch()
{
var culture = _culture.Value;
if (culture is null)
return false;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
return true;
}
}
} | mit | C# |
aa5af1544726591c7af87e496f41bd32088be524 | Add Discount property to Line class (#365) | brandonseydel/MailChimp.Net | MailChimp.Net/Models/Line.cs | MailChimp.Net/Models/Line.cs | using System.Collections.Generic;
using Newtonsoft.Json;
namespace MailChimp.Net.Models
{
public class Line
{
public Line()
{
Links = new List<Link>();
}
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("product_id")]
public string ProductId { get; set; }
[JsonProperty("product_title")]
public string ProductTitle { get; set; }
[JsonProperty("product_variant_id")]
public string ProductVariantId { get; set; }
[JsonProperty("product_variant_title")]
public string ProductVariantTitle { get; set; }
[JsonProperty("quantity")]
public int Quantity { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("discount")]
public decimal? Discount { get; set; }
[JsonProperty("_links")]
public IList<Link> Links { get; set; }
}
}
| using System.Collections.Generic;
using Newtonsoft.Json;
namespace MailChimp.Net.Models
{
public class Line
{
public Line()
{
Links = new List<Link>();
}
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("product_id")]
public string ProductId { get; set; }
[JsonProperty("product_title")]
public string ProductTitle { get; set; }
[JsonProperty("product_variant_id")]
public string ProductVariantId { get; set; }
[JsonProperty("product_variant_title")]
public string ProductVariantTitle { get; set; }
[JsonProperty("quantity")]
public int Quantity { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("_links")]
public IList<Link> Links { get; set; }
}
}
| mit | C# |
190d0522fc1180f260608cbe99529c9836b53b78 | Clarify behaviour on non-Windows systems | SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake | src/Snowflake.Support.GraphQLFrameworkQueries/Queries/Filesystem/FilesystemQueries.cs | src/Snowflake.Support.GraphQLFrameworkQueries/Queries/Filesystem/FilesystemQueries.cs | using HotChocolate.Types;
using Microsoft.DotNet.PlatformAbstractions;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual;
using Snowflake.Framework.Remoting.GraphQL.Schema;
using Snowflake.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem
{
public class FilesystemQueries
: ObjectTypeExtension
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor.Name("Query");
descriptor.Field("filesystem")
.Argument("directoryPath",
a => a.Type<OSDirectoryPathType>()
.Description("The path to explore. If this is null, returns a listing of drives on Windows, " +
"or the root directory on a Unix-like system."))
.Resolver(context => {
var path = context.Argument<DirectoryInfo>("directoryPath");
if (path == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return DriveInfo.GetDrives();
if (path == null &&
(RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
|| RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|| RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) return new DirectoryInfo("/");
if (path?.Exists ?? false) return path;
return null;
})
.Type<OSDirectoryContentsInterface>()
.Description("Provides normalized OS-dependent filesystem access." +
"Returns null if the specified path does not exist.");
}
}
}
| using HotChocolate.Types;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual;
using Snowflake.Framework.Remoting.GraphQL.Schema;
using Snowflake.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem
{
public class FilesystemQueries
: ObjectTypeExtension
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor.Name("Query");
descriptor.Field("filesystem")
.Argument("directoryPath", a => a.Type<OSDirectoryPathType>().Description("The path to explore."))
.Resolver(context => {
var path = context.Argument<DirectoryInfo>("directoryPath");
if (path == null) return DriveInfo.GetDrives();
if (path.Exists) return path;
return null;
})
.Type<OSDirectoryContentsInterface>()
.Description("Provides normalized OS-dependent filesystem access." +
"Returns null if the specified path does not exist.");
}
}
}
| mpl-2.0 | C# |
5971e48c60201747ea30b9676f53fd171785fea6 | update orders consts | angeldnd/dap.core.csharp | Scripts/DapCore/DapOrders.cs | Scripts/DapCore/DapOrders.cs | using System;
namespace angeldnd.dap {
public static class DapOrders {
//Reserved for DapCore: <= -100
public const int Property = -130;
public const int Context = -120;
public const int Manner = -110;
}
}
| using System;
namespace angeldnd.dap {
public static class DapOrders {
public const int Property = -1003;
public const int Context = -1002;
public const int Manner = -1001;
}
}
| mit | C# |
303092ee332b4d3104c31cd8b03947ffb8cbceba | set up theme object | kade-robertson/SharpThemes | SharpThemes/Objects/Theme.cs | SharpThemes/Objects/Theme.cs | using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace SharpThemes.Objects
{
class Theme
{
[JsonProperty(PropertyName = "id")]
public uint ID { get; }
[JsonProperty(PropertyName = "name")]
public string Name { get; }
[JsonProperty(PropertyName = "desc")]
public string Description { get; }
[JsonProperty(PropertyName = "by")]
public string CreatedBy { get; }
[JsonProperty(PropertyName = "dl")]
public uint Downloads { get; }
[JsonProperty(PropertyName = "nsfw")]
public bool IsNSFW { get; }
[JsonProperty(PropertyName = "approved")]
public bool IsApproved { get; }
[JsonProperty(PropertyName = "bgm")]
public string BGM { get; }
[JsonProperty(PropertyName = "hasbgm")]
public bool HasBGM { get; }
[JsonProperty(PropertyName = "type")]
public uint Type { get; }
[JsonProperty(PropertyName = "tags")]
public string Tags { get; }
public List<string> TagList {
get {
return Tags.Split(new string[] { ", " }, StringSplitOptions.None).ToList();
}
}
[JsonProperty(PropertyName = "info")]
public ThemeInfo Info { get; }
[JsonProperty(PropertyName = "filesupdated")]
public bool FilesUpdated { get; }
[JsonProperty(PropertyName = "archived")]
public bool IsArchived { get; }
[JsonProperty(PropertyName = "notif")]
public string Notif { get; }
}
}
| using Newtonsoft.Json;
namespace SharpThemes.Objects
{
class Theme
{
public readonly int ID;
public readonly string Name;
public readonly string Description;
public readonly string CreatedBy;
public readonly int Downloads;
public readonly bool IsNSFW;
public readonly bool IsApproved;
public readonly string BGM;
public readonly bool HasBGM;
public readonly int Type;
public readonly string Tags;
public readonly ThemeInfo Info;
public readonly bool FilesUpdated;
public readonly bool IsArchived;
public readonly string Notif;
}
}
| mit | C# |
08d16b0d06240cee4886ead42e4f2e2bf68b1cba | Fix integration tests | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer.IntegrationTests/Infrastructure/InMemoryGeneralOptionsDataAccess.cs | CalDavSynchronizer.IntegrationTests/Infrastructure/InMemoryGeneralOptionsDataAccess.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalDavSynchronizer.Contracts;
using CalDavSynchronizer.DataAccess;
namespace CalDavSynchronizer.IntegrationTests.Infrastructure
{
class InMemoryGeneralOptionsDataAccess : IGeneralOptionsDataAccess
{
private GeneralOptions _options;
public GeneralOptions LoadOptions()
{
return (_options ??
(_options = new GeneralOptions
{
CalDavConnectTimeout = TimeSpan.FromSeconds(10),
MaxReportAgeInDays = 100,
QueryFoldersJustByGetTable = true,
CultureName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name
}))
.Clone();
}
public void SaveOptions(GeneralOptions options)
{
_options = options.Clone();
}
public Version IgnoreUpdatesTilVersion { get; set; }
public int EntityCacheVersion
{
get { return ComponentContainerTestExtension.GetRequiredEntityCacheVersion(); }
set { }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalDavSynchronizer.Contracts;
using CalDavSynchronizer.DataAccess;
namespace CalDavSynchronizer.IntegrationTests.Infrastructure
{
class InMemoryGeneralOptionsDataAccess : IGeneralOptionsDataAccess
{
private GeneralOptions _options;
public GeneralOptions LoadOptions()
{
return (_options ??
(_options = new GeneralOptions
{
CalDavConnectTimeout = TimeSpan.FromSeconds(10),
MaxReportAgeInDays = 100,
QueryFoldersJustByGetTable = true
}))
.Clone();
}
public void SaveOptions(GeneralOptions options)
{
_options = options.Clone();
}
public Version IgnoreUpdatesTilVersion { get; set; }
public int EntityCacheVersion
{
get { return ComponentContainerTestExtension.GetRequiredEntityCacheVersion(); }
set { }
}
}
}
| agpl-3.0 | C# |
f8802b3778ba30219b7415ed7037a2b8f419782c | Increase assembly version to 1.2.0 | gering/Tiny-JSON | Tiny-JSON/Tiny-JSON/AssemblyInfo.cs | Tiny-JSON/Tiny-JSON/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("Tiny-JSON")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Robert Gering")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.2.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 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("Tiny-JSON")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Robert Gering")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.1.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("")]
| mit | C# |
707911acac196e5c97ce6d6f5b95a0dbeb3dcdbc | Tidy up code formatting / variable naming | 2yangk23/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,EVAST9919/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,ZLima12/osu,smoogipoo/osu,ZLima12/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu | osu.Game.Rulesets.Osu/Mods/OsuModAutopilot.cs | osu.Game.Rulesets.Osu/Mods/OsuModAutopilot.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.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.StateChanges;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Replays;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModAutopilot : Mod, IApplicableFailOverride, IUpdatableByPlayfield, IApplicableToDrawableRuleset<OsuHitObject>
{
public override string Name => "Autopilot";
public override string Acronym => "AP";
public override IconUsage Icon => OsuIcon.ModAutopilot;
public override ModType Type => ModType.Automation;
public override string Description => @"Automatic cursor movement - just follow the rhythm.";
public override double ScoreMultiplier => 1;
public override Type[] IncompatibleMods => new[] { typeof(OsuModSpunOut), typeof(ModRelax), typeof(ModSuddenDeath), typeof(ModNoFail), typeof(ModAutoplay) };
public bool AllowFail => false;
private OsuInputManager inputManager;
private List<OsuReplayFrame> replayFrames;
private int currentFrame;
public void Update(Playfield playfield)
{
if (currentFrame == replayFrames.Count - 1) return;
double time = playfield.Time.Current;
// Very naive implementation of autopilot based on proximity to replay frames.
// TODO: this needs to be based on user interactions to better match stable (pausing until judgement is registered).
if (Math.Abs(replayFrames[currentFrame + 1].Time - time) <= Math.Abs(replayFrames[currentFrame].Time - time))
{
currentFrame++;
new MousePositionAbsoluteInput { Position = playfield.ToScreenSpace(replayFrames[currentFrame].Position) }.Apply(inputManager.CurrentState, inputManager);
}
// TODO: Implement the functionality to automatically spin spinners
}
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
// Grab the input manager to disable the user's cursor, and for future use
inputManager = (OsuInputManager)drawableRuleset.KeyBindingInputManager;
inputManager.AllowUserCursorMovement = false;
// Generate the replay frames the cursor should follow
replayFrames = new OsuAutoGenerator(drawableRuleset.Beatmap).Generate().Frames.Cast<OsuReplayFrame>().ToList();
}
}
}
| // 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.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.StateChanges;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Replays;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModAutopilot : Mod, IApplicableFailOverride, IUpdatableByPlayfield, IApplicableToDrawableRuleset<OsuHitObject>
{
public override string Name => "Autopilot";
public override string Acronym => "AP";
public override IconUsage Icon => OsuIcon.ModAutopilot;
public override ModType Type => ModType.Automation;
public override string Description => @"Automatic cursor movement - just follow the rhythm.";
public override double ScoreMultiplier => 1;
public override Type[] IncompatibleMods => new[] { typeof(OsuModSpunOut), typeof(ModRelax), typeof(ModSuddenDeath), typeof(ModNoFail), typeof(ModAutoplay) };
public bool AllowFail => false;
private OsuInputManager inputManager;
private List<OsuReplayFrame> replayFrames;
private int frameIndex;
public void Update(Playfield playfield)
{
// If we are on the last replay frame, no need to do anything
if (frameIndex == replayFrames.Count - 1) return;
// Check if we are closer to the next replay frame then the current one
if (Math.Abs(replayFrames[frameIndex].Time - playfield.Time.Current) >= Math.Abs(replayFrames[frameIndex + 1].Time - playfield.Time.Current))
{
// If we are, move to the next frame, and update the mouse position
frameIndex++;
new MousePositionAbsoluteInput { Position = playfield.ToScreenSpace(replayFrames[frameIndex].Position) }.Apply(inputManager.CurrentState, inputManager);
}
// TODO: Implement the functionality to automatically spin spinners
}
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
// Grab the input manager to disable the user's cursor, and for future use
inputManager = (OsuInputManager)drawableRuleset.KeyBindingInputManager;
inputManager.AllowUserCursorMovement = false;
// Generate the replay frames the cursor should follow
replayFrames = new OsuAutoGenerator(drawableRuleset.Beatmap).Generate().Frames.Cast<OsuReplayFrame>().ToList();
}
}
}
| mit | C# |
4f19ab9a4b536fd8fe85ac7313b281103d4b55ae | fix peverify order | Fody/MethodTimer | Tests/Verifier.cs | Tests/Verifier.cs | using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Framework;
public static class Verifier
{
static string exePath;
static Verifier()
{
var windowsSdk = Environment.ExpandEnvironmentVariables(@"%programfiles(x86)%\Microsoft SDKs\Windows\");
exePath = Directory.EnumerateFiles(windowsSdk, "PEVerify.exe", SearchOption.AllDirectories)
.OrderByDescending(x =>
{
var fileVersionInfo = FileVersionInfo.GetVersionInfo(x);
return new Version(fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart);
})
.FirstOrDefault();
if (exePath == null)
{
throw new Exception("Could not find path to PEVerify");
}
}
public static void Verify(string beforeAssemblyPath, string afterAssemblyPath)
{
var before = Validate(beforeAssemblyPath);
var after = Validate(afterAssemblyPath);
var message = $"Failed processing {Path.GetFileName(afterAssemblyPath)}\r\n{after}";
Assert.AreEqual(TrimLineNumbers(before), TrimLineNumbers(after), message);
}
static string Validate(string assemblyPath2)
{
using (var process = Process.Start(new ProcessStartInfo(exePath, $"\"{assemblyPath2}\"")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}))
{
process.WaitForExit(10000);
return process.StandardOutput.ReadToEnd().Trim().Replace(assemblyPath2, "");
}
}
static string TrimLineNumbers(string foo)
{
return Regex.Replace(foo, "0x.*]", "");
}
} | using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Framework;
public static class Verifier
{
static string exePath;
static Verifier()
{
var windowsSdk = Environment.ExpandEnvironmentVariables(@"%programfiles(x86)%\Microsoft SDKs\Windows\");
exePath = Directory.EnumerateFiles(windowsSdk, "PEVerify.exe", SearchOption.AllDirectories)
.OrderBy(x =>
{
var fileVersionInfo = FileVersionInfo.GetVersionInfo(x);
return new Version(fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart);
})
.FirstOrDefault();
if (exePath == null)
{
throw new Exception("Could not find path to PEVerify");
}
}
public static void Verify(string beforeAssemblyPath, string afterAssemblyPath)
{
var before = Validate(beforeAssemblyPath);
var after = Validate(afterAssemblyPath);
var message = $"Failed processing {Path.GetFileName(afterAssemblyPath)}\r\n{after}";
Assert.AreEqual(TrimLineNumbers(before), TrimLineNumbers(after), message);
}
static string Validate(string assemblyPath2)
{
using (var process = Process.Start(new ProcessStartInfo(exePath, $"\"{assemblyPath2}\"")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}))
{
process.WaitForExit(10000);
return process.StandardOutput.ReadToEnd().Trim().Replace(assemblyPath2, "");
}
}
static string TrimLineNumbers(string foo)
{
return Regex.Replace(foo, "0x.*]", "");
}
} | mit | C# |
39b911d33c7c948fc94e647fa76dc7b59fbdd650 | Update HeightCalculatorFromBones.cs | cwesnow/Net_Fiddle | 2017oct/HeightCalculatorFromBones.cs | 2017oct/HeightCalculatorFromBones.cs | // Original Source Information
// Author: GitGub on Reddit
// Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/
// Refactored using .NET Fiddle - https://dotnetfiddle.net/F8UcJW
using System;
public class Program
{
static Random random = new Random();
enum Bones { Femur, Tibia, Humerus, Radius }
enum Gender { Male, Female}
public static void Main()
{
for(int x = 0; x < 5; x++) {
// Get Randome Values
float length = randomLength();
Bones bone = randomBone();
Gender gender = randomGender();
int age = randomAge();
// Result
Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}",
gender, age, bone, length, calculateHeight(bone, length, gender, age));
}
}
private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age)
{
float height = 0;
switch(bone) {
case Bones.Femur:
height = (gender == Gender.Male) ?
69.089f + (2.238f * boneLength) - age * 0.06f : 61.412f + (2.317f * boneLength) - age * 0.06f;
break;
case Bones.Tibia:
height = (gender == Gender.Male) ?
81.688f + (2.392f * boneLength) - age * 0.06f : 72.572f + (2.533f * boneLength) - age * 0.06f;
break;
case Bones.Humerus:
height = (gender == Gender.Male) ?
height = 73.570f + (2.970f * boneLength) - age * 0.06f : 64.977f + (3.144f * boneLength) - age * 0.06f;
break;
case Bones.Radius:
height = (gender == Gender.Male) ?
80.405f + (3.650f * boneLength) - age * 0.06f : 73.502f + (3.876f * boneLength) - age * 0.06f;
break;
default: break;
}
return height;
}
private static float randomLength() { return (float)random.NextDouble()*3; }
private static Bones randomBone() { return (Bones)random.Next(1,4); }
private static Gender randomGender() { return (Gender)random.Next(0,2); } // 1,2 & 0,1 always gave the same gender
private static int randomAge() { return random.Next(16, 99); }
}
| // Original Source Information
// Author: GitGub on Reddit
// Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/
// Refactored using .NET Fiddle - https://dotnetfiddle.net/F8UcJW
using System;
public class Program
{
static Random random = new Random();
enum Bones { Femur, Tibia, Humerus, Radius }
enum Gender { Male = 1, Female = 2 }
public static void Main()
{
for(int x = 0; x < 5; x++) {
// Get Randome Values
float length = randomLength();
Bones bone = randomBone();
Gender gender = randomGender();
int age = randomAge();
// Result
Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}",
gender, age, bone, length, calculateHeight(bone, length, gender, age));
}
}
private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age)
{
float height = 0;
switch(bone) {
case Bones.Femur:
height = (gender == Gender.Male) ?
69.089f + (2.238f * boneLength) - age * 0.06f : 61.412f + (2.317f * boneLength) - age * 0.06f;
break;
case Bones.Tibia:
height = (gender == Gender.Male) ?
81.688f + (2.392f * boneLength) - age * 0.06f : 72.572f + (2.533f * boneLength) - age * 0.06f;
break;
case Bones.Humerus:
height = (gender == Gender.Male) ?
height = 73.570f + (2.970f * boneLength) - age * 0.06f : 64.977f + (3.144f * boneLength) - age * 0.06f;
break;
case Bones.Radius:
height = (gender == Gender.Male) ?
80.405f + (3.650f * boneLength) - age * 0.06f : 73.502f + (3.876f * boneLength) - age * 0.06f;
break;
default: break;
}
return height;
}
private static float randomLength() { return (float)random.NextDouble()*3; }
private static Bones randomBone() { return (Bones)random.Next(1,4); }
private static Gender randomGender() { return (Gender)random.Next(0,2); } // 1,2 & 0,1 always gave the same gender
private static int randomAge() { return random.Next(16, 99); }
}
| mit | C# |
39dcf8ee4a87041fc90ab19724bb01f2bd4503ba | Rename database | lukecahill/NutritionTracker | food_tracker/DAL/TrackerContext.cs | food_tracker/DAL/TrackerContext.cs | using System.Data.Entity;
namespace food_tracker.DAL {
public class TrackerContext : DbContext {
public TrackerContext() : base("NutritionTracker") {
Configuration.LazyLoadingEnabled = false;
this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
}
public IDbSet<WholeDay> Days { get; set; }
public IDbSet<NutritionItem> Nutrition { get; set; }
}
}
| using System.Data.Entity;
namespace food_tracker.DAL {
public class TrackerContext : DbContext {
public TrackerContext() : base() {
Configuration.LazyLoadingEnabled = false;
this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
}
public IDbSet<WholeDay> Days { get; set; }
public IDbSet<NutritionItem> Nutrition { get; set; }
}
}
| mit | C# |
0a93e602caaf5245da650544f010ad5980963dc2 | Add missing space (#4281) | 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.Server/Speech/Components/SpanishAccentComponent.cs | Content.Server/Speech/Components/SpanishAccentComponent.cs | using Robust.Shared.GameObjects;
namespace Content.Server.Speech.Components
{
[RegisterComponent]
public class SpanishAccentComponent : Component, IAccentComponent
{
public override string Name => "SpanishAccent";
public string Accentuate(string message)
{
// Insert E before every S
message = InsertS(message);
// If a sentence ends with ?, insert a reverse ? at the beginning of the sentence
message = ReplaceQuestionMark(message);
return message;
}
private string InsertS(string message)
{
// Replace every new Word that starts with s/S
var msg = message.Replace(" s", " es").Replace(" S", " Es");
// Still need to check if the beginning of the message starts
if (msg.StartsWith("s"))
{
return msg.Remove(0, 1).Insert(0, "es");
}
else if (msg.StartsWith("S"))
{
return msg.Remove(0, 1).Insert(0, "Es");
}
return msg;
}
private string ReplaceQuestionMark(string message)
{
var sentences = AccentManager.SentenceRegex.Split(message);
var msg = "";
foreach (var s in sentences)
{
if (s.EndsWith("?")) // We've got a question => add ¿ to the beginning
{
// Because we don't split by whitespace, we may have some spaces in front of the sentence.
// So we add the symbol before the first non space char
msg += s.Insert(s.Length - s.TrimStart().Length, "¿");
}
else
{
msg += s;
}
}
return msg;
}
}
}
| using Robust.Shared.GameObjects;
namespace Content.Server.Speech.Components
{
[RegisterComponent]
public class SpanishAccentComponent : Component, IAccentComponent
{
public override string Name => "SpanishAccent";
public string Accentuate(string message)
{
// Insert E before every S
message = InsertS(message);
// If a sentence ends with ?, insert a reverse ? at the beginning of the sentence
message = ReplaceQuestionMark(message);
return message;
}
private string InsertS(string message)
{
// Replace every new Word that starts with s/S
var msg = message.Replace(" s", " es").Replace(" S", "Es");
// Still need to check if the beginning of the message starts
if (msg.StartsWith("s"))
{
return msg.Remove(0, 1).Insert(0, "es");
}
else if (msg.StartsWith("S"))
{
return msg.Remove(0, 1).Insert(0, "Es");
}
return msg;
}
private string ReplaceQuestionMark(string message)
{
var sentences = AccentManager.SentenceRegex.Split(message);
var msg = "";
foreach (var s in sentences)
{
if (s.EndsWith("?")) // We've got a question => add ¿ to the beginning
{
// Because we don't split by whitespace, we may have some spaces in front of the sentence.
// So we add the symbol before the first non space char
msg += s.Insert(s.Length - s.TrimStart().Length, "¿");
}
else
{
msg += s;
}
}
return msg;
}
}
}
| mit | C# |
7750675757dca8bd6b2f8ae2a45dfe26a2e337d7 | Add SoftMaxPlayers to status response for launcher use (#9365) | 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.Server/GameTicking/GameTicker.StatusShell.cs | Content.Server/GameTicking/GameTicker.StatusShell.cs | using System.Text.Json.Nodes;
using Content.Shared.CCVar;
using Robust.Server.ServerStatus;
using Robust.Shared.Configuration;
namespace Content.Server.GameTicking
{
public sealed partial class GameTicker
{
/// <summary>
/// Used for thread safety, given <see cref="IStatusHost.OnStatusRequest"/> is called from another thread.
/// </summary>
private readonly object _statusShellLock = new();
/// <summary>
/// Round start time in UTC, for status shell purposes.
/// </summary>
[ViewVariables]
private DateTime _roundStartDateTime;
/// <summary>
/// For access to CVars in status responses.
/// </summary>
[Dependency] private readonly IConfigurationManager _cfg = default!;
private void InitializeStatusShell()
{
IoCManager.Resolve<IStatusHost>().OnStatusRequest += GetStatusResponse;
}
private void GetStatusResponse(JsonNode jObject)
{
// This method is raised from another thread, so this better be thread safe!
lock (_statusShellLock)
{
jObject["name"] = _baseServer.ServerName;
jObject["players"] = _playerManager.PlayerCount;
jObject["soft_max_players"] = _cfg.GetCVar(CCVars.SoftMaxPlayers);
jObject["run_level"] = (int) _runLevel;
if (_runLevel >= GameRunLevel.InRound)
{
jObject["round_start_time"] = _roundStartDateTime.ToString("o");
}
}
}
}
}
| using System.Text.Json.Nodes;
using Robust.Server.ServerStatus;
namespace Content.Server.GameTicking
{
public sealed partial class GameTicker
{
/// <summary>
/// Used for thread safety, given <see cref="IStatusHost.OnStatusRequest"/> is called from another thread.
/// </summary>
private readonly object _statusShellLock = new();
/// <summary>
/// Round start time in UTC, for status shell purposes.
/// </summary>
[ViewVariables]
private DateTime _roundStartDateTime;
private void InitializeStatusShell()
{
IoCManager.Resolve<IStatusHost>().OnStatusRequest += GetStatusResponse;
}
private void GetStatusResponse(JsonNode jObject)
{
// This method is raised from another thread, so this better be thread safe!
lock (_statusShellLock)
{
jObject["name"] = _baseServer.ServerName;
jObject["players"] = _playerManager.PlayerCount;
jObject["run_level"] = (int) _runLevel;
if (_runLevel >= GameRunLevel.InRound)
{
jObject["round_start_time"] = _roundStartDateTime.ToString("o");
}
}
}
}
}
| mit | C# |
68370edf879934490ec235efd01d28de0ef4798c | Update Source/Libraries/openXDA.Model/Emails/DataSourceSetting.cs | GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA | Source/Libraries/openXDA.Model/Emails/DataSourceSetting.cs | Source/Libraries/openXDA.Model/Emails/DataSourceSetting.cs | //******************************************************************************************************
// DataSourceSetting.cs - Gbtc
//
// Copyright © 2017, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 10/04/2022 - Gabriel Santos
// Generated original version of source code.
//
//******************************************************************************************************
using GSF.Data.Model;
namespace openXDA.Model
{
public abstract class EmailDataSourceSettingBase
{
[PrimaryKey(true)]
public int ID { get; set; }
public string Value { get; set; }
public string Name { get; set; }
}
}
| //******************************************************************************************************
// DataSourceSetting.cs - Gbtc
//
// Copyright © 2017, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 10/04/2022 - Gabriel Santos
// Generated original version of source code.
//
//******************************************************************************************************
using GSF.Data.Model;
namespace openXDA.Model
{
public class DataSourceSetting
{
[PrimaryKey(true)]
public int ID { get; set; }
public string Value { get; set; }
public string Name { get; set; }
}
}
| mit | C# |
212cba560530c3dc100e618c3bdcd4e655d136e4 | Update AdminHelpChat.cs | fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/UI/AdminTools/AdminHelpChat.cs | UnityProject/Assets/Scripts/UI/AdminTools/AdminHelpChat.cs | using UnityEngine;
namespace AdminTools
{
public class AdminHelpChat : MonoBehaviour
{
[SerializeField] private ChatScroll chatScroll = null;
public void CloseWindow()
{
gameObject.SetActive(false);
}
private void OnEnable()
{
chatScroll.OnInputFieldSubmit += OnInputReceived;
}
private void OnDisable()
{
chatScroll.OnInputFieldSubmit -= OnInputReceived;
}
public void AddChatEntry(string message)
{
chatScroll.AddNewChatEntry(new ChatEntryData
{
Message = message
});
}
void OnInputReceived(string message)
{
AdminReplyMessage.Send($"{PlayerManager.CurrentCharacterSettings.Username} replied: " + message);
}
}
} | using UnityEngine;
using DatabaseAPI;
using DiscordWebhook;
namespace AdminTools
{
public class AdminHelpChat : MonoBehaviour
{
[SerializeField] private ChatScroll chatScroll = null;
public void CloseWindow()
{
gameObject.SetActive(false);
}
private void OnEnable()
{
chatScroll.OnInputFieldSubmit += OnInputReceived;
}
private void OnDisable()
{
chatScroll.OnInputFieldSubmit -= OnInputReceived;
}
public void AddChatEntry(string message)
{
chatScroll.AddNewChatEntry(new ChatEntryData
{
Message = message
});
}
void OnInputReceived(string message)
{
AdminReplyMessage.Send($"{PlayerManager.CurrentCharacterSettings.Username} replied: " + message);
}
}
} | agpl-3.0 | C# |
ae5b3d42f15bdf3f7bf79b8cf2537e96ef7ddb1f | Check the result with more precision | lionelrepellin/dojo-from-static-to-service | Business.Tests/UserServiceTests.cs | Business.Tests/UserServiceTests.cs | using DAL;
using Entities;
using Moq;
using NFluent;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business.Tests
{
[TestFixture]
public class UserServiceTests
{
private UserService _userService;
private Mock<IUserRepository> _userRepository;
[SetUp]
public void Initialize()
{
_userRepository = CreateUserRepositoryMock();
_userService = new UserService(_userRepository.Object);
}
[Test]
public void FindDatavivAccessAllowed()
{
var users = _userService.FindDatavivAccessAllowed();
Check.That(users)
.IsNotNull()
.And
.HasElementThatMatches(u => u.DatavivAccessAllowed);
Check.That(users.Extracting("Name"))
.ContainsExactly("Paul", "Pierre");
_userRepository.Verify(r => r.GetAll(), Times.Once);
}
private Mock<IUserRepository> CreateUserRepositoryMock()
{
var users = new List<User>
{
new User { Id = 1, Name = "Pierre", DatavivAccessAllowed = true },
new User { Id = 2, Name = "Paul", DatavivAccessAllowed = true },
new User { Id = 3, Name = "Jacques", DatavivAccessAllowed = false }
};
var repository = new Mock<IUserRepository>();
repository
.Setup(r => r.GetAll())
.Returns(users);
return repository;
}
}
} | using DAL;
using Entities;
using Moq;
using NFluent;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business.Tests
{
[TestFixture]
public class UserServiceTests
{
private UserService _userService;
private Mock<IUserRepository> _userRepository;
[SetUp]
public void Initialize()
{
_userRepository = CreateUserRepositoryMock();
_userService = new UserService(_userRepository.Object);
}
[Test]
public void FindDatavivAccessAllowed()
{
var users = _userService.FindDatavivAccessAllowed();
Check.That(users)
.IsNotNull()
.And
.HasElementThatMatches(u => u.DatavivAccessAllowed);
_userRepository.Verify(r => r.GetAll(), Times.Once);
}
private Mock<IUserRepository> CreateUserRepositoryMock()
{
var users = new List<User>
{
new User { Id = 1, Name = "Pierre", DatavivAccessAllowed = true },
new User { Id = 2, Name = "Paul", DatavivAccessAllowed = true },
new User { Id = 3, Name = "Jacques", DatavivAccessAllowed = false }
};
var repository = new Mock<IUserRepository>();
repository
.Setup(r => r.GetAll())
.Returns(users);
return repository;
}
}
} | mit | C# |
5c8511e3c01e3a7183a00ad1d04db4ea9e122bac | Change try remove key pair method semantics | Ben-Barron/Utility | Utility/Extensions/ConcurrentDictionaryExtensions.cs | Utility/Extensions/ConcurrentDictionaryExtensions.cs | using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Utility.Extensions
{
public static class ConcurrentDictionaryExtensions
{
public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
return dictionary.TryRemove(key, out value);
}
/// <remarks>
/// HACK: is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can.
/// </remarks>
public static bool TryRemove<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
{
return collection.Remove(new KeyValuePair<TKey, TValue>(key, value));
}
}
}
| using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Utility.Extensions
{
public static class ConcurrentDictionaryExtensions
{
public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
return dictionary.TryRemove(key, out value);
}
/// <remarks>
/// This is a hack but is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can (not 100%!)
/// </remarks>
public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
ICollection<KeyValuePair<TKey, TValue>> collection = dictionary;
return collection.Remove(new KeyValuePair<TKey, TValue>(key, value));
}
}
}
| mit | C# |
ea932963c48930f1471c2320f7263bbfc699d5dd | Update SimpleEntryAlert.cs | Clancey/iOSHelpers | iOSHelpers/SimpleEntryAlert.cs | iOSHelpers/SimpleEntryAlert.cs | using System;
using System.Threading.Tasks;
using UIKit;
namespace iOSHelpers
{
public class SimpleEntryAlert : IDisposable
{
readonly string title;
readonly string details;
readonly string placeholder;
private readonly string defaultValue;
private readonly string okString;
private readonly string cancelString;
protected UIAlertController alertController;
public UITextField TextField;
public SimpleEntryAlert(string title, string details = "", string placeholder = "", string defaultValue = "", string okString = "Ok",string cancelString = "Cancel")
{
this.title = title;
this.details = details;
this.placeholder = placeholder;
this.defaultValue = defaultValue;
this.okString = okString;
this.cancelString = cancelString;
alertController = UIAlertController.Create(title, details, UIAlertControllerStyle.Alert);
var cancel = UIAlertAction.Create(cancelString, UIAlertActionStyle.Cancel, (alert) => { tcs.TrySetCanceled(); });
var ok = UIAlertAction.Create(okString, UIAlertActionStyle.Default,
a => { tcs.TrySetResult(TextField.Text); });
alertController.AddTextField(field =>
{
field.Placeholder = placeholder;
field.Text = defaultValue;
TextField = field;
});
alertController.AddAction(ok);
alertController.AddAction(cancel);
}
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
public Task<string> GetInput(UIViewController fromController)
{
fromController.PresentViewControllerAsync(alertController, true);
return tcs.Task;
}
bool isDisposed;
public void Dispose()
{
if(isDisposed)
OnDispose();
isDisposed = true;
}
protected virtual void OnDispose()
{
alertController?.Dispose();
tcs?.TrySetCanceled();
tcs = null;
}
}
} | using System;
using System.Threading.Tasks;
using UIKit;
namespace iOSHelpers
{
public class SimpleEntryAlert : IDisposable
{
readonly string title;
readonly string details;
readonly string placeholder;
private readonly string defaultValue;
private readonly string okString;
private readonly string cancelString;
UIAlertController alertController;
UIAlertView alertView;
public SimpleEntryAlert(string title, string details = "", string placeholder = "", string defaultValue = "", string okString = "Ok",string cancelString = "Cancel")
{
this.title = title;
this.details = details;
this.placeholder = placeholder;
this.defaultValue = defaultValue;
this.okString = okString;
this.cancelString = cancelString;
alertController = UIAlertController.Create(title, details, UIAlertControllerStyle.Alert);
setupAlertController();
}
void setupAlertController()
{
UITextField entryField = null;
var cancel = UIAlertAction.Create(cancelString, UIAlertActionStyle.Cancel, (alert) => { tcs.TrySetCanceled(); });
var ok = UIAlertAction.Create(okString, UIAlertActionStyle.Default,
a => { tcs.TrySetResult(entryField.Text); });
alertController.AddTextField(field =>
{
field.Placeholder = placeholder;
field.Text = defaultValue;
entryField = field;
});
alertController.AddAction(ok);
alertController.AddAction(cancel);
}
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
public Task<string> GetInput(UIViewController fromController)
{
if (alertController != null)
{
fromController.PresentViewControllerAsync(alertController, true);
}
else
{
alertView.Show();
}
return tcs.Task;
}
public void Dispose()
{
alertController?.Dispose();
alertView?.DismissWithClickedButtonIndex(alertView.CancelButtonIndex, true);
alertView?.Dispose();
tcs?.TrySetCanceled();
tcs = null;
}
}
} | apache-2.0 | C# |
bfb17fc521566c59d114d945bcf5f965137ec9be | Add our own vessel to the proto store as when in KSC the flighglobals will be cleared | gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Client/Systems/VesselProtoSys/VesselProtoEvents.cs | Client/Systems/VesselProtoSys/VesselProtoEvents.cs | using LunaClient.Base;
using LunaClient.Systems.Lock;
using LunaClient.VesselUtilities;
using System;
namespace LunaClient.Systems.VesselProtoSys
{
public class VesselProtoEvents: SubSystem<VesselProtoSystem>
{
/// <summary>
/// Sends our vessel just when we start the flight
/// </summary>
public void FlightReady()
{
if (FlightGlobals.ActiveVessel != null)
{
System.MessageSender.SendVesselMessage(FlightGlobals.ActiveVessel, true);
//Add our own vessel to the dictionary aswell
var ownVesselData = VesselSerializer.SerializeVessel(FlightGlobals.ActiveVessel.protoVessel);
if (ownVesselData.Length > 0)
{
var newProtoUpdate = new VesselProtoUpdate(ownVesselData, ownVesselData.Length, FlightGlobals.ActiveVessel.id);
VesselsProtoStore.AllPlayerVessels.AddOrUpdate(FlightGlobals.ActiveVessel.id, newProtoUpdate, (key, existingVal) => newProtoUpdate);
}
}
}
/// <summary>
/// Called when a vessel is modified. We use it to update our own proto dictionary
/// and reflect changes so we don't have to call the "backupvessel" so often
/// We should not send out own vessel data using this event as this is handled in a routine
/// </summary>
public void VesselModified(Vessel data)
{
//Perhaps we are shooting stuff at other uncontrolled vessel...
if (data.id != FlightGlobals.ActiveVessel?.id && !LockSystem.LockQuery.UpdateLockExists(data.id))
{
System.MessageSender.SendVesselMessage(data, false);
if (VesselsProtoStore.AllPlayerVessels.ContainsKey(data.id))
VesselsProtoStore.AllPlayerVessels[data.id].ProtoVessel = data.BackupVessel();
}
}
/// <summary>
/// We use this method to detect when a flag has been planted and we are far away from it.
/// We don't use the onflagplanted event as that is triggered too early and we need to set the id
/// AFTER we filled the plaque in the flag
/// </summary>
/// <param name="data"></param>
public void VesselGoOnRails(Vessel data)
{
if (data.vesselType == VesselType.Flag && data.id == Guid.Empty)
{
data.id = Guid.NewGuid();
data.protoVessel.vesselID = data.id;
System.MessageSender.SendVesselMessage(data, true);
}
}
}
}
| using LunaClient.Base;
using LunaClient.Systems.Lock;
using System;
namespace LunaClient.Systems.VesselProtoSys
{
public class VesselProtoEvents: SubSystem<VesselProtoSystem>
{
/// <summary>
/// Sends our vessel just when we start the flight
/// </summary>
public void FlightReady()
{
System.MessageSender.SendVesselMessage(FlightGlobals.ActiveVessel, true);
}
/// <summary>
/// Called when a vessel is modified. We use it to update our own proto dictionary
/// and reflect changes so we don't have to call the "backupvessel" so often
/// We should not send out own vessel data using this event as this is handled in a routine
/// </summary>
public void VesselModified(Vessel data)
{
//Perhaps we are shooting stuff at other uncontrolled vessel...
if (data.id != FlightGlobals.ActiveVessel?.id && !LockSystem.LockQuery.UpdateLockExists(data.id))
{
System.MessageSender.SendVesselMessage(data, false);
if (VesselsProtoStore.AllPlayerVessels.ContainsKey(data.id))
VesselsProtoStore.AllPlayerVessels[data.id].ProtoVessel = data.BackupVessel();
}
}
/// <summary>
/// We use this method to detect when a flag has been planted and we are far away from it.
/// We don't use the onflagplanted event as that is triggered too early and we need to set the id
/// AFTER we filled the plaque in the flag
/// </summary>
/// <param name="data"></param>
public void VesselGoOnRails(Vessel data)
{
if (data.vesselType == VesselType.Flag && data.id == Guid.Empty)
{
data.id = Guid.NewGuid();
data.protoVessel.vesselID = data.id;
System.MessageSender.SendVesselMessage(data, true);
}
}
}
}
| mit | C# |
3e84eef304435656c9f6047e23fe36b61880d30a | Update AGameManager.cs | Nicolas-Constanty/UnityTools | Assets/UnityTools/MonoBehaviour/AGameManager.cs | Assets/UnityTools/MonoBehaviour/AGameManager.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityTools.DesignPatern;
// ReSharper disable once CheckNamespace
namespace UnityTools
{
public abstract class AGameManager<T, TE> : Singleton<T>
where T : MonoBehaviour
where TE : struct, IConvertible
{
// ReSharper disable once EmptyConstructor
protected AGameManager() {}
protected delegate void GameAction();
protected readonly Dictionary<TE, GameAction> GameStatesUpdateActions = new Dictionary<TE, GameAction>();
protected readonly Dictionary<TE, GameAction> GameStatesFixedUpdateActions = new Dictionary<TE, GameAction>();
protected override void Awake()
{
base.Awake();
bool init = false;
foreach (TE state in Enum.GetValues(typeof(TE)))
{
if (!init)
{
init = true;
}
Type type = typeof(T);
MethodInfo method = type.GetMethod("On" + state + "Game", BindingFlags.NonPublic);
if (method != null)
{
GameStatesUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
method = type.GetMethod("OnFixed" + state + "Game");
if (method != null)
{
GameStatesFixedUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
}
}
public TE CurrentState;
public T GetInstance()
{
return Instance;
}
protected virtual void Update()
{
if (GameStatesUpdateActions.ContainsKey(CurrentState))
GameStatesUpdateActions[CurrentState]();
}
protected virtual void FixedUpdate()
{
if (GameStatesFixedUpdateActions.ContainsKey(CurrentState))
GameStatesFixedUpdateActions[CurrentState]();
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityTools.DesignPatern;
// ReSharper disable once CheckNamespace
namespace UnityTools
{
public abstract class AGameManager<T, TE> : Singleton<T>
where T : MonoBehaviour
where TE : struct, IConvertible
{
// ReSharper disable once EmptyConstructor
protected AGameManager() {}
protected delegate void GameAction();
protected readonly Dictionary<TE, GameAction> GameStatesUpdateActions = new Dictionary<TE, GameAction>();
protected readonly Dictionary<TE, GameAction> GameStatesFixedUpdateActions = new Dictionary<TE, GameAction>();
protected override void Awake()
{
base.Awake();
bool init = false;
foreach (TE state in Enum.GetValues(typeof(TE)))
{
if (!init)
{
init = true;
}
Type type = typeof(T);
MethodInfo method = type.GetMethod("On" + state + "Game");
if (method != null)
{
GameStatesUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
method = type.GetMethod("OnFixed" + state + "Game");
if (method != null)
{
GameStatesFixedUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name);
}
}
}
public TE CurrentState;
public T GetInstance()
{
return Instance;
}
protected virtual void Update()
{
if (GameStatesUpdateActions.ContainsKey(CurrentState))
GameStatesUpdateActions[CurrentState]();
}
protected virtual void FixedUpdate()
{
if (GameStatesFixedUpdateActions.ContainsKey(CurrentState))
GameStatesFixedUpdateActions[CurrentState]();
}
}
} | mit | C# |
ef7436bfd6891557bfb9b97854bdb7d4030ffb03 | Support all http methods | andreArtelt/SimpleRESTServer | SimpleRESTServer/RoutingAttribute.cs | SimpleRESTServer/RoutingAttribute.cs | using System;
using System.Net.Http;
namespace SimpleRESTServer
{
public class RoutingAttribute : Attribute
{
public string Path;
public HttpMethod Method;
public string Role;
/// <summary>
/// Initializes a new instance of the <see cref="SimpleRESTServer.RoutingAttribute"/> class.
/// </summary>
/// <param name="a_strPath">Path of route.</param>
/// <param name="a_strMethod">Http method.</param>
/// <param name="a_strRole">Role required for access.</param>
public RoutingAttribute(string a_strPath, string a_strMethod="GET", string a_strRole="Anonymous")
{
Path = a_strPath;
Role = a_strRole;
if (a_strMethod.Equals("GET"))
Method = HttpMethod.Get;
else if (a_strMethod.Equals("POST"))
Method = HttpMethod.Post;
else if (a_strMethod.Equals("PUT"))
Method = HttpMethod.Put;
else if (a_strMethod.Equals("DELETE"))
Method = HttpMethod.Delete;
else if (a_strMethod.Equals("TRACE"))
Method = HttpMethod.Trace;
else if (a_strMethod.Equals("HEAD"))
Method = HttpMethod.Head;
else
throw new ArgumentException();
}
}
} | using System;
using System.Net.Http;
namespace SimpleRESTServer
{
public class RoutingAttribute : Attribute
{
public string Path;
public HttpMethod Method;
public string Role;
/// <summary>
/// Initializes a new instance of the <see cref="SimpleRESTServer.RoutingAttribute"/> class.
/// </summary>
/// <param name="a_strPath">Path of route.</param>
/// <param name="a_strMethod">Http method.</param>
/// <param name="a_strRole">Role required for access.</param>
public RoutingAttribute(string a_strPath, string a_strMethod="GET", string a_strRole="Anonymous")
{
Path = a_strPath;
Role = a_strRole;
if (a_strMethod.Equals("GET"))
Method = HttpMethod.Get;
else if (a_strMethod.Equals("POST"))
Method = HttpMethod.Post;
else if (a_strMethod.Equals("PUT"))
Method = HttpMethod.Put;
else if (a_strMethod.Equals("DELETE"))
Method = HttpMethod.Delete;
else
throw new ArgumentException();
}
}
} | mit | C# |
53a852bd9318d74493049c9a7c7c50c5d3774268 | Bump version | EricZimmerman/AppCompatCacheParser | AppCompatCacheParser/Properties/AssemblyInfo.cs | AppCompatCacheParser/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("AppCompatCacheParser")]
[assembly: AssemblyDescription("Shimcache parser")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Eric Zimmerman")]
[assembly: AssemblyProduct("AppCompatCacheParser")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("Eric Zimmerman")]
[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("9f0f6b88-7d27-43b9-a729-da94d2358bfd")]
// 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.8.0.0")]
[assembly: AssemblyFileVersion("0.8.0.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AppCompatCacheParser")]
[assembly: AssemblyDescription("Shimcache parser")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Eric Zimmerman")]
[assembly: AssemblyProduct("AppCompatCacheParser")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("Eric Zimmerman")]
[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("9f0f6b88-7d27-43b9-a729-da94d2358bfd")]
// 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.0.8.0")]
[assembly: AssemblyFileVersion("0.0.8.0")] | mit | C# |
325a5cff5326f75e330e944bf293ab3eaf5c17aa | test case | jefking/King.Azure | King.Azure.Integration.Test/Data/FileShareTests.cs | King.Azure.Integration.Test/Data/FileShareTests.cs | namespace King.Azure.Integration.Test.Data
{
using System;
using System.Threading.Tasks;
using King.Azure.Data;
using NUnit.Framework;
[TestFixture]
public class FileShareTests
{
private const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=kingdottest;AccountKey=raLQzql5BzvYrHGPxZKJIFHDe/B0+kTpJwGokbQHX5p6EVbx8xOt6XbPKJsUWdyOMTYYEKAvZ7ImqFIfpLGOJQ==;FileEndpoint=https://kingdottest.file.core.windows.net/";
[Test]
public async Task CreateIfNotExists()
{
var random = new Random();
var storage = new FileShare(string.Format("a{0}b", random.Next()), ConnectionString);
var created = await storage.CreateIfNotExists();
Assert.IsTrue(created);
}
}
} | namespace King.Azure.Integration.Test.Data
{
using King.Azure.Data;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
[TestFixture]
public class FileShareTests
{
private const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=kingtesting;AccountKey=g7WCz6wKVBQR38VkRekJyt9cMejowitMMfkjNZFLnvclph7gKTNb6o2u6YghGyfVTXolMSAhTiMLY+hPqaj5kg==;FileEndpoint=https://kingtesting.file.core.windows.net/";
[Test]
public async Task CreateIfNotExists()
{
var random = new Random();
var storage = new FileShare(string.Format("a{0}b", random.Next()), ConnectionString);
var created = await storage.CreateIfNotExists();
Assert.IsTrue(created);
}
}
} | apache-2.0 | C# |
52a3484a4bcd488423031376abcc4deeaae25190 | Split out 3.5 and 4.0 builds and tests | refractalize/bounce,socialdotcom/bounce,socialdotcom/bounce,sreal/bounce,sreal/bounce,socialdotcom/bounce,sreal/bounce,socialdotcom/bounce,refractalize/bounce,refractalize/bounce | Build/Build.cs | Build/Build.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bounce.Framework;
namespace Build
{
public class Build
{
[Targets]
public static object Targets(IParameters parameters)
{
var v4 = new VisualStudioSolution {SolutionPath = @"Bounce.sln", Configuration = "Debug"};
var v35 = new VisualStudioSolution {SolutionPath = @"Bounce.sln", Configuration = "Debug_3_5" };
var v4Tests = new NUnitTests
{
DllPaths = v4.Projects.Where(p => p.Name.EndsWith("Tests")).Select(p => p.OutputFile),
NUnitConsolePath = @"References\NUnit\nunit-console.exe"
};
var v35Tests = new NUnitTests
{
DllPaths = v35.Projects.Where(p => p.Name.EndsWith("Tests")).Select(p => p.OutputFile),
NUnitConsolePath = @"References\NUnit\nunit-console.exe"
};
Task<IEnumerable<string>> dests = new [] {"sdf"};
dests.SelectTasks(dest => new Copy {ToPath = dest});
const string nugetExe = @"References\NuGet\NuGet.exe";
var nugetPackage = new NuGetPackage
{
NuGetExePath = nugetExe,
Spec = v4.Projects["Bounce.Framework"].ProjectFile.WithDependencyOn(v4Tests, v35Tests, v35),
};
var nugetPush = new NuGetPush
{
ApiKey = parameters.Required<string>("nugetApiKey"),
NuGetExePath = nugetExe,
Package = nugetPackage.Package,
};
return new
{
Net4Binaries = v4,
Net35Binaries = v35,
Net4Tests = v4Tests,
Net35Tests = v35Tests,
Binaries = new All(v4, v35),
Tests = new All(v4Tests, v35Tests),
NuGet = nugetPush,
NuGetPackage = nugetPackage,
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bounce.Framework;
namespace Build
{
public class Build
{
[Targets]
public static object Targets(IParameters parameters)
{
var v4 = new VisualStudioSolution {SolutionPath = @"Bounce.sln", Configuration = "Debug"};
var v35 = new VisualStudioSolution {SolutionPath = @"Bounce.sln", Configuration = "Debug_3_5"};
var tests = new NUnitTests
{
DllPaths = v4.Projects.Where(p => p.Name.EndsWith("Tests")).Select(p => p.OutputFile),
NUnitConsolePath = @"References\NUnit\nunit-console.exe"
};
Task<IEnumerable<string>> dests = new [] {"sdf"};
dests.SelectTasks(dest => new Copy {ToPath = dest});
var nugetExe = @"References\NuGet\NuGet.exe";
var nugetPackage = new NuGetPackage
{
NuGetExePath = nugetExe,
Spec = v4.Projects["Bounce.Framework"].ProjectFile.WithDependencyOn(tests, v35),
};
var nugetPush = new NuGetPush
{
ApiKey = parameters.Required<string>("nugetApiKey"),
NuGetExePath = nugetExe,
Package = nugetPackage.Package,
};
return new
{
Binaries = new All(v4, v35),
Tests = tests,
NuGet = nugetPush,
NuGetPackage = nugetPackage,
};
}
}
}
| bsd-2-clause | C# |
ffad42aaa0bb586c07509d626a99155a15f6697f | Undo accidental 2.0 -> 2.1 renames (dotnet/corert#5981) | ericstj/corefx,mmitche/corefx,ViktorHofer/corefx,BrennanConroy/corefx,mmitche/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,mmitche/corefx,ptoonen/corefx,wtgodbe/corefx,ptoonen/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx,mmitche/corefx,BrennanConroy/corefx,wtgodbe/corefx,mmitche/corefx,mmitche/corefx,Jiayili1/corefx,mmitche/corefx,Jiayili1/corefx,Jiayili1/corefx,wtgodbe/corefx,wtgodbe/corefx,Jiayili1/corefx,BrennanConroy/corefx,shimingsg/corefx,ptoonen/corefx,ericstj/corefx,ViktorHofer/corefx,shimingsg/corefx,Jiayili1/corefx,ptoonen/corefx,shimingsg/corefx,ptoonen/corefx,ViktorHofer/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,Jiayili1/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx,ptoonen/corefx | src/Common/src/CoreLib/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs | src/Common/src/CoreLib/System/Collections/Generic/NonRandomizedStringEqualityComparer.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.Runtime.Serialization;
namespace System.Collections.Generic
{
// NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...>
// We use NonRandomizedStringEqualityComparer as default comparer as it doesnt use the randomized string hashing which
// keeps the performance not affected till we hit collision threshold and then we switch to the comparer which is using
// randomized string hashing.
[Serializable] // Required for compatibility with .NET Core 2.0 as we exposed the NonRandomizedStringEqualityComparer inside the serialization blob
// Needs to be public to support binary serialization compatibility
public sealed class NonRandomizedStringEqualityComparer : EqualityComparer<string>, ISerializable
{
internal static new IEqualityComparer<string> Default { get; } = new NonRandomizedStringEqualityComparer();
private NonRandomizedStringEqualityComparer() { }
// This is used by the serialization engine.
private NonRandomizedStringEqualityComparer(SerializationInfo information, StreamingContext context) { }
public sealed override bool Equals(string x, string y) => string.Equals(x, y);
public sealed override int GetHashCode(string obj) => obj?.GetLegacyNonRandomizedHashCode() ?? 0;
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// We are doing this to stay compatible with .NET Framework.
info.SetType(typeof(GenericEqualityComparer<string>));
}
}
}
| // 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.Runtime.Serialization;
namespace System.Collections.Generic
{
// NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...>
// We use NonRandomizedStringEqualityComparer as default comparer as it doesnt use the randomized string hashing which
// keeps the performance not affected till we hit collision threshold and then we switch to the comparer which is using
// randomized string hashing.
[Serializable] // Required for compatibility with .NET Core 2.1 as we exposed the NonRandomizedStringEqualityComparer inside the serialization blob
// Needs to be public to support binary serialization compatibility
public sealed class NonRandomizedStringEqualityComparer : EqualityComparer<string>, ISerializable
{
internal static new IEqualityComparer<string> Default { get; } = new NonRandomizedStringEqualityComparer();
private NonRandomizedStringEqualityComparer() { }
// This is used by the serialization engine.
private NonRandomizedStringEqualityComparer(SerializationInfo information, StreamingContext context) { }
public sealed override bool Equals(string x, string y) => string.Equals(x, y);
public sealed override int GetHashCode(string obj) => obj?.GetLegacyNonRandomizedHashCode() ?? 0;
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// We are doing this to stay compatible with .NET Framework.
info.SetType(typeof(GenericEqualityComparer<string>));
}
}
}
| mit | C# |
fdf77f14acf09fa5105a44a4d9234f889984f079 | add selection test that now fails (issue with anchor and caret not on selection border) | Unity-Technologies/CodeEditor,Unity-Technologies/CodeEditor | src/CodeEditor.Text.UI.Tests/SelectionTest.cs | src/CodeEditor.Text.UI.Tests/SelectionTest.cs | using Moq;
using NUnit.Framework;
namespace CodeEditor.Text.UI
{
[TestFixture]
public class SelectionTest
{
Selection GetSelectionWithCaretPos (int row, int column)
{
var documentMock = new Mock<ICaret>();
documentMock.SetupGet(o => o.Row).Returns(row);
documentMock.SetupGet(o => o.Column).Returns(column);
return new Selection(documentMock.Object);
}
void CheckValidBeginAndEndDrawPositions(Position beginDrawPos, Position endDrawPos)
{
// We draw from upper left to lower right
Assert.IsTrue(beginDrawPos.Row <= endDrawPos.Row);
if (beginDrawPos.Row == endDrawPos.Row)
Assert.IsTrue(beginDrawPos.Column < endDrawPos.Column);
}
[Test]
public void TestThatCaretPosIsOnOneOfTheSelectionBorders ()
{
Position caretPos = new Position(5, 5);
Position[] anchorPos = new Position[] {
new Position (1,1), new Position (1,5), new Position (1, 10),
new Position (5,1), new Position (5,5), new Position (5, 10),
new Position (10,1), new Position (10,5), new Position (10, 10),
};
Selection selection = GetSelectionWithCaretPos(caretPos.Row, caretPos.Column);
for (int i=0; i<anchorPos.Length; i++)
{
selection.Anchor = anchorPos[i];
bool caretIsOk = selection.BeginDrawPos == caretPos || selection.EndDrawPos == caretPos;
if (!caretIsOk)
System.Console.WriteLine("Error: Caret is NOT on selection border" + " \nData: " + selection + ", Index: " + i);
bool anchorIsOk = selection.BeginDrawPos == selection.Anchor || selection.EndDrawPos == selection.Anchor;
if (!anchorIsOk)
System.Console.WriteLine("Error: Anchor is NOT on selection border" + " \nData: " + selection + ", Index: " + i);
Assert.IsTrue(caretIsOk);
Assert.IsTrue(anchorIsOk);
}
}
[Test]
public void TestSelectionWhereCaretIsAfterAnchorOnSameRow()
{
Selection selection = GetSelectionWithCaretPos(5, 9);
selection.Anchor = new Position (5,5);
CheckValidBeginAndEndDrawPositions (selection.BeginDrawPos, selection.EndDrawPos);
}
[Test]
public void TestSelectionWhereCaretIsBeforeAnchorOnSameRow()
{
Selection selection = GetSelectionWithCaretPos(5, 3);
selection.Anchor = new Position(5, 5);
CheckValidBeginAndEndDrawPositions (selection.BeginDrawPos, selection.EndDrawPos);
}
[Test]
public void TestSelectionWhereCaretRowIsBeforeAnchorRow()
{
Selection selection = GetSelectionWithCaretPos(2, 2);
selection.Anchor = new Position(6, 6);
CheckValidBeginAndEndDrawPositions(selection.BeginDrawPos, selection.EndDrawPos);
}
[Test]
public void TestSelectionWhereCaretRowIsAfterAnchorRow()
{
Selection selection = GetSelectionWithCaretPos(6, 6);
selection.Anchor = new Position(2, 2);
CheckValidBeginAndEndDrawPositions(selection.BeginDrawPos, selection.EndDrawPos);
}
}
}
| using Moq;
using NUnit.Framework;
namespace CodeEditor.Text.UI
{
[TestFixture]
public class SelectionTest
{
Selection GetSelectionWithCaretPos (int row, int column)
{
var documentMock = new Mock<ICaret>();
documentMock.SetupGet(o => o.Row).Returns(row);
documentMock.SetupGet(o => o.Column).Returns(column);
return new Selection(documentMock.Object);
}
void CheckValidBeginAndEndDrawPositions(Position beginDrawPos, Position endDrawPos)
{
// We draw from upper left to lower right
Assert.IsTrue(beginDrawPos.Row <= endDrawPos.Row);
if (beginDrawPos.Row == endDrawPos.Row)
Assert.IsTrue(beginDrawPos.Column < endDrawPos.Column);
}
[Test]
public void TestSelectionWhereCaretIsAfterAnchorOnSameRow()
{
Selection selection = GetSelectionWithCaretPos(5, 9);
selection.Anchor = new Position (5,5);
CheckValidBeginAndEndDrawPositions (selection.BeginDrawPos, selection.EndDrawPos);
}
[Test]
public void TestSelectionWhereCaretIsBeforeAnchorOnSameRow()
{
Selection selection = GetSelectionWithCaretPos(5, 3);
selection.Anchor = new Position(5, 5);
CheckValidBeginAndEndDrawPositions (selection.BeginDrawPos, selection.EndDrawPos);
}
[Test]
public void TestSelectionWhereCaretRowIsBeforeAnchorRow()
{
Selection selection = GetSelectionWithCaretPos(2, 2);
selection.Anchor = new Position(6, 6);
CheckValidBeginAndEndDrawPositions(selection.BeginDrawPos, selection.EndDrawPos);
}
[Test]
public void TestSelectionWhereCaretRowIsAfterAnchorRow()
{
Selection selection = GetSelectionWithCaretPos(6, 6);
selection.Anchor = new Position(2, 2);
CheckValidBeginAndEndDrawPositions(selection.BeginDrawPos, selection.EndDrawPos);
}
}
}
| mit | C# |
6c928ace917c525c84b685fdc27df48679337f2a | Use the in-memory database for testing the home controller | rprouse/IdeaWeb,rprouse/IdeaWeb | IdeaWeb.Test/Controllers/HomeControllerTests.cs | IdeaWeb.Test/Controllers/HomeControllerTests.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdeaWeb.Controllers;
using IdeaWeb.Data;
using IdeaWeb.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
namespace IdeaWeb.Test
{
[TestFixture]
public class HomeControllerTests
{
const int NUM_IDEAS = 10;
HomeController _controller;
[SetUp]
public void SetUp()
{
// Create unique database names based on the test id
var options = new DbContextOptionsBuilder<IdeaContext>()
.UseInMemoryDatabase(TestContext.CurrentContext.Test.ID)
.Options;
// Seed the in-memory database
using (var context = new IdeaContext(options))
{
for(int i = 1; i <= NUM_IDEAS; i++)
{
context.Add(new Idea
{
Name = $"Idea name {i}",
Description = $"Description {i}",
Rating = i % 3 + 1
});
}
context.SaveChanges();
}
// Use a clean copy of the context within the tests
_controller = new HomeController(new IdeaContext(options));
}
[Test]
public async Task IndexReturnsListOfIdeas()
{
ViewResult result = await _controller.Index() as ViewResult;
Assert.That(result?.Model, Is.Not.Null);
Assert.That(result.Model, Has.Count.EqualTo(NUM_IDEAS));
IEnumerable<Idea> ideas = result.Model as IEnumerable<Idea>;
Idea idea = ideas?.FirstOrDefault();
Assert.That(idea, Is.Not.Null);
Assert.That(idea.Name, Is.EqualTo("Idea name 1"));
Assert.That(idea.Description, Does.Contain("1"));
Assert.That(idea.Rating, Is.EqualTo(2));
}
}
}
| using IdeaWeb.Controllers;
using Microsoft.AspNetCore.Mvc;
using NUnit.Framework;
namespace IdeaWeb.Test
{
[TestFixture]
public class HomeControllerTests
{
HomeController _controller;
[SetUp]
public void SetUp()
{
_controller = new HomeController();
}
[Test]
public void IndexReturnsIdeasView()
{
IActionResult result = _controller.Index();
Assert.That(result, Is.Not.Null);
}
}
}
| mit | C# |
079871f6d3ebdde7eeac7273f58cc2790cdcac85 | Add code task | roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon | R7.Epsilon/Skins/SkinObjects/FooterContent.ascx.cs | R7.Epsilon/Skins/SkinObjects/FooterContent.ascx.cs | //
// FooterContent.ascx.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace R7.Epsilon.Skins.SkinObjects
{
// TODO: Rename class to LocalizedPanel or something
public class FooterContent: EpsilonSkinObjectBase
{
public string CssClass { get; set; }
public string ResourceKey { get; set; }
}
}
| //
// FooterContent.ascx.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace R7.Epsilon.Skins.SkinObjects
{
public class FooterContent: EpsilonSkinObjectBase
{
public string CssClass { get; set; }
public string ResourceKey { get; set; }
}
}
| agpl-3.0 | C# |
f25b0767f0b69f513aabdc18b918c16f776d8fc5 | 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()
{
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;
}
}
}
} | using FluentValidation;
using TIKSN.Configuration.Validator;
namespace TIKSN.Analytics.Logging.NLog
{
public class RemoteNLogViewerOptionsPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<RemoteNLogViewerOptions>
{
public RemoteNLogViewerOptionsPartialConfigurationValidator()
{
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# |
67ef68a612f407b375dc3751bd76657ebccd0cfd | Update IPlayerFramework.cs | SwiftAusterity/NetMud,SwiftAusterity/NetMud,SwiftAusterity/NetMud,SwiftAusterity/NetMud,SwiftAusterity/NetMud | NetMud.DataStructure/Player/IPlayerFramework.cs | NetMud.DataStructure/Player/IPlayerFramework.cs | using NetMud.DataStructure.Administrative;
using NetMud.DataStructure.Architectural.ActorBase;
using NetMud.DataStructure.System;
using System.Collections.Generic;
namespace NetMud.DataStructure.Player
{
/// <summary>
/// Backing data for player characters
/// </summary>
public interface IPlayerFramework : IHaveHealth, IHaveStamina
{
/// <summary>
/// Account this player belongs to
/// </summary>
string AccountHandle { get; set; }
/// <summary>
/// Command permissions for player character
/// </summary>
StaffRank GamePermissionsRank { get; set; }
/// <summary>
/// Family name for character
/// </summary>
string SurName { get; set; }
/// <summary>
/// Gender of the player
/// </summary>
IGender Gender { get; set; }
/// <summary>
/// The race daya for this npc, not its own data structure
/// </summary>
IRace Race { get; set; }
/// <summary>
/// Is this character not graduated from the tutorial
/// </summary>
bool StillANoob { get; set; }
/// <summary>
/// Sensory overrides for staff member characters
/// </summary>
HashSet<MessagingType> SuperSenses { get; set; }
}
}
| using NetMud.DataStructure.Administrative;
using NetMud.DataStructure.Architectural.ActorBase;
using NetMud.DataStructure.Combat;
using NetMud.DataStructure.System;
using System.Collections.Generic;
namespace NetMud.DataStructure.Player
{
/// <summary>
/// Backing data for player characters
/// </summary>
public interface IPlayerFramework : IHaveHealth, IHaveStamina
{
/// <summary>
/// Account this player belongs to
/// </summary>
string AccountHandle { get; set; }
/// <summary>
/// Command permissions for player character
/// </summary>
StaffRank GamePermissionsRank { get; set; }
/// <summary>
/// Family name for character
/// </summary>
string SurName { get; set; }
/// <summary>
/// Gender of the player
/// </summary>
IGender Gender { get; set; }
/// <summary>
/// The race daya for this npc, not its own data structure
/// </summary>
IRace Race { get; set; }
/// <summary>
/// Is this character not graduated from the tutorial
/// </summary>
bool StillANoob { get; set; }
/// <summary>
/// Sensory overrides for staff member characters
/// </summary>
HashSet<MessagingType> SuperSenses { get; set; }
}
}
| mit | C# |
9d07230b047d9b44434f9648255870c8ea687997 | fix applicant names | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Parsing/Messages/S_SHOW_CANDIDATE_LIST.cs | TCC.Core/Parsing/Messages/S_SHOW_CANDIDATE_LIST.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCC.Data;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class S_SHOW_CANDIDATE_LIST : ParsedMessage
{
public List<User> Candidates { get; set; }
public S_SHOW_CANDIDATE_LIST(TeraMessageReader reader) : base(reader)
{
var count = reader.ReadUInt16();
var offset = reader.ReadUInt16();
Candidates = new List<User>();
if (count == 0) return;
reader.BaseStream.Position = offset - 4;
for (int i = 0; i < count; i++)
{
var current = reader.ReadUInt16();
var next = reader.ReadUInt16();
var nameOffset = reader.ReadUInt16();
var playerId = reader.ReadUInt32();
var cls = (Class)reader.ReadUInt16();
reader.Skip(2 + 2);
var level = reader.ReadUInt16();
var worldId = reader.ReadUInt32();
var guardId = reader.ReadUInt32();
var sectionId = reader.ReadUInt32();
reader.BaseStream.Position = nameOffset - 4;
var name = reader.ReadTeraString();
Candidates.Add(new User(WindowManager.LfgListWindow.Dispatcher)
{
PlayerId = playerId,
UserClass = cls,
Level = level,
Location = SessionManager.MapDatabase.GetName(guardId, sectionId),
Online = true,
Name = name
});
if (next != 0) reader.BaseStream.Position = next - 4;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCC.Data;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class S_SHOW_CANDIDATE_LIST : ParsedMessage
{
public List<User> Candidates { get; set; }
public S_SHOW_CANDIDATE_LIST(TeraMessageReader reader) : base(reader)
{
var count = reader.ReadUInt16();
var offset = reader.ReadUInt16();
Candidates = new List<User>();
if (count == 0) return;
reader.BaseStream.Position = offset - 4;
for (int i = 0; i < count; i++)
{
var current = reader.ReadUInt16();
var next = reader.ReadUInt16();
var nameOffset = reader.ReadUInt16();
var playerId = reader.ReadUInt32();
var cls = (Class)reader.ReadUInt16();
reader.Skip(2 + 2);
var level = reader.ReadUInt16();
var worldId = reader.ReadUInt32();
var guardId = reader.ReadUInt32();
var sectionId = reader.ReadUInt32();
reader.BaseStream.Position = nameOffset - 4;
var name = reader.ReadTeraString();
Candidates.Add(new User(WindowManager.LfgListWindow.Dispatcher)
{
PlayerId = playerId,
UserClass = cls,
Level = level,
Location = SessionManager.MapDatabase.GetName(guardId, sectionId),
Online = true
});
if (next != 0) reader.BaseStream.Position = next - 4;
}
}
}
}
| mit | C# |
aa5c49926d950c203ebbc6aaf159364e50feea58 | Fix error at level end when target has been intercepted | DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17 | Proto/Assets/Scripts/Interactive/Interactive.cs | Proto/Assets/Scripts/Interactive/Interactive.cs | using UnityEngine;
abstract public class Interactive : MonoBehaviour
{
protected Renderer[] m_Renderers;
protected Material m_SelectMat;
protected Material[] m_TargetMaterials;
protected Material[][] m_TargetDefaultMaterial;
protected HUD m_HUD;
protected bool m_IsActivated = false;
protected bool m_IsSelected = false;
protected void Start()
{
m_HUD = FindObjectOfType<HUD>();
m_Renderers = GetComponentsInChildren<Renderer>();
m_TargetMaterials = new Material[2];
m_TargetDefaultMaterial = new Material[2][];
if (m_Renderers.Length > m_TargetDefaultMaterial.Length)
{
m_TargetDefaultMaterial = new Material[m_Renderers.Length][];
}
}
abstract public void Interact();
public abstract void MoveObject();
public abstract void ResetObject();
public bool isActivated
{
get { return m_IsActivated; }
}
protected void Select()
{
m_IsSelected = true;
if (m_Renderers.Length > 0)
{
for (int i = 0; i < m_Renderers.Length; ++i)
{
m_TargetDefaultMaterial[i] = m_Renderers[i].materials;
m_TargetMaterials[0] = m_TargetDefaultMaterial[i][0];
m_TargetMaterials[1] = m_SelectMat;
m_Renderers[i].materials = m_TargetMaterials;
}
}
}
protected void UnSelect()
{
m_IsSelected = false;
if (m_Renderers.Length > 0)
{
for (int i = 0; i < m_Renderers.Length; ++i)
{
if(m_TargetDefaultMaterial[i] != null)
m_Renderers[i].materials = m_TargetDefaultMaterial[i];
}
}
}
} | using UnityEngine;
abstract public class Interactive : MonoBehaviour
{
protected Renderer[] m_Renderers;
protected Material m_SelectMat;
protected Material[] m_TargetMaterials;
protected Material[][] m_TargetDefaultMaterial;
protected HUD m_HUD;
protected bool m_IsActivated = false;
protected bool m_IsSelected = false;
protected void Start()
{
m_HUD = FindObjectOfType<HUD>();
m_Renderers = GetComponentsInChildren<Renderer>();
m_TargetMaterials = new Material[2];
m_TargetDefaultMaterial = new Material[2][];
if (m_Renderers.Length > m_TargetDefaultMaterial.Length)
{
m_TargetDefaultMaterial = new Material[m_Renderers.Length][];
}
}
abstract public void Interact();
public abstract void MoveObject();
public abstract void ResetObject();
public bool isActivated
{
get { return m_IsActivated; }
}
protected void Select()
{
m_IsSelected = true;
if (m_Renderers.Length > 0)
{
for (int i = 0; i < m_Renderers.Length; ++i)
{
m_TargetDefaultMaterial[i] = m_Renderers[i].materials;
m_TargetMaterials[0] = m_TargetDefaultMaterial[i][0];
m_TargetMaterials[1] = m_SelectMat;
m_Renderers[i].materials = m_TargetMaterials;
}
}
}
protected void UnSelect()
{
m_IsSelected = false;
if (m_Renderers.Length > 0)
{
for (int i = 0; i < m_Renderers.Length; ++i)
{
m_Renderers[i].materials = m_TargetDefaultMaterial[i];
}
}
}
} | mit | C# |
4a263e12ffee4de8bade20184193f3f08e05cdff | Adjust initial size to look nicer | jcrang/dependency-injection-kata-series,mjac/dependency-injection-kata-series | src/DependencyInjection.Console/PatternApp.cs | src/DependencyInjection.Console/PatternApp.cs | namespace DependencyInjection.Console
{
internal class PatternApp
{
private readonly PatternWriter _patternWriter;
private readonly PatternGenerator _patternGenerator;
public PatternApp(bool useColours)
{
_patternWriter = new PatternWriter(useColours);
_patternGenerator = new PatternGenerator();
}
public void Run()
{
var pattern = _patternGenerator.Generate(25, 15);
_patternWriter.Write(pattern);
}
}
} | namespace DependencyInjection.Console
{
internal class PatternApp
{
private readonly PatternWriter _patternWriter;
private readonly PatternGenerator _patternGenerator;
public PatternApp(bool useColours)
{
_patternWriter = new PatternWriter(useColours);
_patternGenerator = new PatternGenerator();
}
public void Run()
{
var pattern = _patternGenerator.Generate(10, 10);
_patternWriter.Write(pattern);
}
}
} | mit | C# |
750d409066fd9d16a61d59e0134080383357a999 | Disable test paralellization | nopara73/HBitcoin | src/HBitcoin.Tests/Properties/AssemblyInfo.cs | src/HBitcoin.Tests/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HBitcoin.Tests")]
[assembly: AssemblyTrademark("")]
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)]
// 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("9cef4271-0144-4132-aa66-6331bc788492")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HBitcoin.Tests")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9cef4271-0144-4132-aa66-6331bc788492")]
| mit | C# |
7da198431ea592076f58159a212c00ac0d62181a | Change namespace | tugberkugurlu/Owin.Limits,damianh/LimitsMiddleware,damianh/LimitsMiddleware | src/Owin.Limits.Tests/AppBuilderExtensions.cs | src/Owin.Limits.Tests/AppBuilderExtensions.cs | namespace Owin
{
using System;
using Owin.Limits;
internal static class AppBuilderExtensions
{
internal static Action<MidFunc> Use(this IAppBuilder builder)
{
return middleware => builder.Use(middleware);
}
internal static IAppBuilder Use(this Action<MidFunc> middleware, IAppBuilder builder)
{
return builder;
}
}
} | namespace Owin.Limits
{
using System;
internal static class AppBuilderExtensions
{
internal static Action<MidFunc> Use(this IAppBuilder builder)
{
return middleware => builder.Use(middleware);
}
internal static IAppBuilder Use(this Action<MidFunc> middleware, IAppBuilder builder)
{
return builder;
}
}
} | mit | C# |
27fa2c930ac36fd20edeaa7a7de466e560377d3d | Increment version to 0.13 | whampson/cascara,whampson/bft-spec | Src/WHampson.Cascara/Properties/AssemblyInfo.cs | Src/WHampson.Cascara/Properties/AssemblyInfo.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.Cascara")]
[assembly: AssemblyProduct("WHampson.Cascara")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.13.0.0")]
[assembly: AssemblyVersion("0.13.0.0")]
[assembly: AssemblyInformationalVersion("0.13")]
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.Cascara")]
[assembly: AssemblyProduct("WHampson.Cascara")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.12.0.0")]
[assembly: AssemblyVersion("0.12.0.0")]
[assembly: AssemblyInformationalVersion("0.12")]
| mit | C# |
f7fb160b896e2619f6693e44ed109ef84d3a6042 | Document method | Liwoj/Metrics.NET,Recognos/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET | Src/Metrics/Reporters/MetricsEndpointReports.cs | Src/Metrics/Reporters/MetricsEndpointReports.cs | using System;
using System.Collections.Generic;
using System.Net;
using Metrics.MetricData;
using Metrics.Visualization;
namespace Metrics.Reports
{
public sealed class MetricsEndpointReports : Utils.IHideObjectMembers
{
private readonly MetricsDataProvider metricsDataProvider;
private readonly Func<HealthStatus> healthStatus;
private readonly List<MetricsEndpoint> endpoints = new List<MetricsEndpoint>();
internal IEnumerable<MetricsEndpoint> Endpoints => this.endpoints;
public MetricsEndpointReports(MetricsDataProvider metricsDataProvider, Func<HealthStatus> healthStatus)
{
this.metricsDataProvider = metricsDataProvider;
this.healthStatus = healthStatus;
}
/// <summary>
/// Register a report at the specified endpoint.
/// </summary>
/// <param name="endpoint">Endpoint where the report will be accessible. E.g. "/text" </param>
/// <param name="responseFactory">Produces the response. Will be called each time the endpoint is accessed.</param>
/// <returns>Chain-able configuration object.</returns>
public MetricsEndpointReports WithEndpointReport(string endpoint, Func<MetricsData, Func<HealthStatus>, HttpListenerContext, MetricsEndpointResponse> responseFactory)
{
var metricsEndpoint = new MetricsEndpoint(endpoint, (c) => responseFactory(this.metricsDataProvider.CurrentMetricsData, this.healthStatus, c));
this.endpoints.Add(metricsEndpoint);
return this;
}
}
}
| using System;
using System.Collections.Generic;
using System.Net;
using Metrics.MetricData;
using Metrics.Visualization;
namespace Metrics.Reports
{
public sealed class MetricsEndpointReports : Utils.IHideObjectMembers
{
private readonly MetricsDataProvider metricsDataProvider;
private readonly Func<HealthStatus> healthStatus;
private readonly List<MetricsEndpoint> endpoints = new List<MetricsEndpoint>();
internal IEnumerable<MetricsEndpoint> Endpoints => this.endpoints;
public MetricsEndpointReports(MetricsDataProvider metricsDataProvider, Func<HealthStatus> healthStatus)
{
this.metricsDataProvider = metricsDataProvider;
this.healthStatus = healthStatus;
}
public MetricsEndpointReports WithEndpointReport(string endpoint, Func<MetricsData, Func<HealthStatus>, HttpListenerContext, MetricsEndpointResponse> responseFactory)
{
var metricsEndpoint = new MetricsEndpoint(endpoint, (c) => responseFactory(this.metricsDataProvider.CurrentMetricsData, this.healthStatus, c));
this.endpoints.Add(metricsEndpoint);
return this;
}
}
}
| apache-2.0 | C# |
5c6aed889194147895c53baa910e057990a26fd5 | Split test into two separate tests | Felsig/Emotion-API | src/EmotionAPI.Tests/EmotionAPIClientTests.cs | src/EmotionAPI.Tests/EmotionAPIClientTests.cs | using Xunit;
namespace EmotionAPI.Tests
{
public class EmotionAPIClientTests : EmotionAPITestsBase
{
[Fact]
public void Can_Create_EmotionAPIClient_Class()
{
var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey);
Assert.NotNull(sut);
}
[Fact]
public void OcpApimSubscriptionKey_Is_Being_Set()
{
var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey);
Assert.NotEmpty(sut.OcpApimSubscriptionKey);
}
}
}
| using Xunit;
namespace EmotionAPI.Tests
{
public class EmotionAPIClientTests : EmotionAPITestsBase
{
[Fact]
public void Can_Create_EmotionAPIClient_Controller()
{
var controller = new EmotionAPIClient(mockOcpApimSubscriptionKey);
Assert.NotNull(controller);
Assert.NotEmpty(controller.OcpApimSubscriptionKey);
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.