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
76ffc24841745fd92b4b84f495d6dd37d4ab5aec
add experimental unused types
glorylo/Joyride
Joyride.Specflow/Configuration/JoyrideConfig.cs
Joyride.Specflow/Configuration/JoyrideConfig.cs
using System.Configuration; namespace Joyride.Specflow.Configuration { public class JoyrideConfig : ConfigurationSection { private static readonly JoyrideConfig _settings = ConfigurationManager.GetSection("joyride") as JoyrideConfig; public static JoyrideConfig Settings { get { return _settings; }} [ConfigurationProperty("capabilities", IsRequired = true)] public GlobalCapabilityElement Capabilities { get { return (GlobalCapabilityElement) base["capabilities"]; } } [ConfigurationProperty("android")] public AndroidElement Android { get { return (AndroidElement) base["android"]; } } [ConfigurationProperty("ios")] public IosElement Ios { get { return (IosElement) base["ios"]; } } [ConfigurationProperty("endpoints", IsRequired = true)] public EndPointElement Endpoints { get { return (EndPointElement) base["endpoints"]; } } } public class EndPointElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection) base[""]; }} } public class IosElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection)base[""]; } } } public class AndroidElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection)base[""]; } } } public class GlobalCapabilityElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection)base[""]; } } } /* public class CapabilityElement : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true)] public string Name { get { return (string) this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("value", IsRequired = true)] public object Value { get { return this["value"]; } set { this["value"] = value; } } [ConfigurationProperty("type", IsRequired = true)] public string Type { get { return (string) this["type"]; } set { this["type"] = value; } } public class CapabilityElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new CapabilityElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((CapabilityElement) element).Name; } } } */ }
using System; using System.Collections.Specialized; using System.Configuration; using System.Runtime.InteropServices.ComTypes; namespace Joyride.Specflow.Configuration { public class JoyrideConfig : ConfigurationSection { private static readonly JoyrideConfig _settings = ConfigurationManager.GetSection("joyride") as JoyrideConfig; public static JoyrideConfig Settings { get { return _settings; }} [ConfigurationProperty("capabilities", IsRequired = true)] public CapabilityElement Capabilities { get { return (CapabilityElement)base["capabilities"]; } } [ConfigurationProperty("android")] public AndroidElement Android { get { return (AndroidElement) base["android"]; } } [ConfigurationProperty("ios")] public IosElement Ios { get { return (IosElement) base["ios"]; } } [ConfigurationProperty("endpoints", IsRequired = true)] public EndPointElement Endpoints { get { return (EndPointElement) base["endpoints"]; } } } public class EndPointElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection) base[""]; }} } public class IosElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection)base[""]; } } } public class AndroidElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection)base[""]; } } } public class CapabilityElement : ConfigurationElement { [ConfigurationProperty("", IsDefaultCollection = true)] public NameValueConfigurationCollection Settings { get { return (NameValueConfigurationCollection)base[""]; } } } }
bsd-3-clause
C#
fe744632e8e79b664ffccee8a7388ace5e739230
Add docs
yishn/GTPWrapper
GTPWrapper/Sgf/GoExtensions.cs
GTPWrapper/Sgf/GoExtensions.cs
using GTPWrapper.DataTypes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapper.Sgf { public static class GoExtensions { /// <summary> /// Converts given vertex on given board into SGF coordinates. /// </summary> /// <param name="board">The board.</param> /// <param name="vertex">The vertex.</param> public static string VertexToSgf(this Board board, Vertex vertex) { if (vertex == Vertex.Pass || !board.HasVertex(vertex)) return ""; return (Vertex.Letters[vertex.X - 1].ToString() + Vertex.Letters[board.Size - vertex.Y - 1].ToString()).ToLower(); } /// <summary> /// Converts given SGF coordinates on given board into a vertex. /// </summary> /// <param name="board">The board.</param> /// <param name="sgfVertex">The SGF coordinates.</param> public static Vertex SgfToVertex(this Board board, string sgfVertex) { if (sgfVertex == "" || board.Size <= 19 && sgfVertex == "tt") return Vertex.Pass; return new Vertex( Vertex.Letters.IndexOf(sgfVertex[0].ToString().ToUpper()) + 1, board.Size - Vertex.Letters.IndexOf(sgfVertex[1].ToString().ToUpper()) ); } } }
using GTPWrapper.DataTypes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapper.Sgf { public static class GoExtensions { public static string VertexToSgf(this Board board, Vertex vertex) { if (vertex == Vertex.Pass || !board.HasVertex(vertex)) return ""; return (Vertex.Letters[vertex.X - 1].ToString() + Vertex.Letters[board.Size - vertex.Y - 1].ToString()).ToLower(); } public static Vertex SgfToVertex(this Board board, string sgfVertex) { if (sgfVertex == "" || board.Size <= 19 && sgfVertex == "tt") return Vertex.Pass; return new Vertex( Vertex.Letters.IndexOf(sgfVertex[0].ToString().ToUpper()) + 1, board.Size - Vertex.Letters.IndexOf(sgfVertex[1].ToString().ToUpper()) ); } } }
mit
C#
a784181bbdedd8c10778d4551130f69aa3b204cc
Add InvokerParameterNameAttribute
danielwertheim/Ensure.That,danielwertheim/Ensure.That
src/projects/EnsureThat/Annotations/JetBrains.cs
src/projects/EnsureThat/Annotations/JetBrains.cs
/* MIT License Copyright (c) 2016 JetBrains http://www.jetbrains.com 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; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming // ReSharper disable once CheckNamespace namespace JetBrains.Annotations { /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c>. /// </summary> /// <example><code> /// [NotNull] object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] internal sealed class NotNullAttribute : Attribute { } /// <summary> /// Indicates that the function argument should be string literal and match one /// of the parameters of the caller function. For example, ReSharper annotates /// the parameter of <see cref="System.ArgumentNullException"/>. /// </summary> /// <example><code> /// void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InvokerParameterNameAttribute : Attribute { } }
/* MIT License Copyright (c) 2016 JetBrains http://www.jetbrains.com 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; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming // ReSharper disable once CheckNamespace namespace JetBrains.Annotations { /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c>. /// </summary> /// <example><code> /// [NotNull] object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] internal sealed class NotNullAttribute : Attribute { } }
mit
C#
019535f57162d13d29e7a9c92c2213365cf27f2c
Update IntuitionB.cs
Keripo/fgo-data
webservice/src/Models/Data/ActiveSkills/IntuitionB.cs
webservice/src/Models/Data/ActiveSkills/IntuitionB.cs
using FGOData.Models.Serialization; using System.Collections.Generic; namespace FGOData.Models.Data { public class IntuitionB : ActiveSkill { public IntuitionB() { Name_EN = "Intuition B"; Name_JP = "直感 B"; Cooldown = 7; Effects = new List<Effect> { new Effect() { EffectType = EffectType.Stars, Target = TargetType.Self, Duration = 1, EffectValuesType = EffectValueType.Constant, EffectValues = new List<float> { 4, 5, 6, 7, 8, 9, 10, 11, 12, 14 } } }; } } }
using FGOData.Models.Serialization; using System.Collections.Generic; namespace FGOData.Models.Data { public class IntuitionB : ActiveSkill { public IntuitionB() { Name_EN = "Intuition B"; Name_JP = "直感 B"; Cooldown = 7; RequiredAscension = 1; Effects = new List<Effect> { new Effect() { EffectType = EffectType.Stars, Target = TargetType.Self, Duration = 1, EffectValuesType = EffectValueType.Constant, EffectValues = new List<float> { 4, 5, 6, 7, 8, 9, 10, 11, 12, 14 } } }; } } }
apache-2.0
C#
b113d9954476c1a24f881973cb1b982f934edbb7
fix typo in FaultSetCollection
maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,maul-esel/ssharp
Source/SafetySharp/Analysis/FaultSetCollection.cs
Source/SafetySharp/Analysis/FaultSetCollection.cs
using System.Collections.Generic; using System.Linq; using SafetySharp.Runtime; namespace SafetySharp.Analysis { class FaultSetCollection { private readonly int numFaults; private readonly HashSet<FaultSet>[] elementsByCardinality; public FaultSetCollection(int numFaults) { this.numFaults = numFaults; elementsByCardinality = new HashSet<FaultSet>[numFaults + 1]; } public void Add(FaultSet set) { var cardinality = set.Cardinality; if (elementsByCardinality[cardinality] == null) elementsByCardinality[cardinality] = new HashSet<FaultSet>(); elementsByCardinality[cardinality].Add(set); } public bool ContainsSubsetOf(FaultSet set) { var cardinality = set.Cardinality; if (elementsByCardinality[cardinality]?.Contains(set) ?? false) return true; for (int i = 0; i < cardinality; ++i) { if (elementsByCardinality[i]?.Any(other => other.IsSubsetOf(set)) ?? false) return true; } return false; } public bool ContainsSupersetOf(FaultSet set) { var cardinality = set.Cardinality; if (elementsByCardinality[cardinality]?.Contains(set) ?? false) return true; for (int i = numFaults; i > cardinality; --i) { if (elementsByCardinality[i]?.Any(other => set.IsSubsetOf(other)) ?? false) return true; } return false; } } }
using System.Collections.Generic; using System.Linq; using SafetySharp.Runtime; namespace SafetySharp.Analysis { class FaultSetCollection { private readonly int numFaults; private readonly HashSet<FaultSet>[] elementsByCardinality; public FaultSetCollection(int numFaults) { this.numFaults = numFaults; elementsByCardinality = new HashSet<FaultSet>[numFaults + 1]; } public void Add(FaultSet set) { var cardinality = set.Cardinality; if (elementsByCardinality[cardinality] == null) elementsByCardinality[cardinality] = new HashSet<FaultSet>(); elementsByCardinality[cardinality].Add(set); } public bool ContainsSubsetOf(FaultSet set) { var cardinality = set.Cardinality; if (elementsByCardinality[cardinality]?.Contains(set) ?? false) return true; for (int i = 0; i < cardinality; ++i) { if (elementsByCardinality[cardinality]?.Any(other => other.IsSubsetOf(set)) ?? false) return true; } return false; } public bool ContainsSupersetOf(FaultSet set) { var cardinality = set.Cardinality; if (elementsByCardinality[cardinality]?.Contains(set) ?? false) return true; for (int i = numFaults; i > cardinality; --i) { if (elementsByCardinality[cardinality]?.Any(other => set.IsSubsetOf(other)) ?? false) return true; } return false; } } }
mit
C#
e85aa4c645e3e75d26b4b478500440b52dce4fe1
Fix ProfilingEventEndArgs.Success inversion
bungeemonkee/Utilitron
Utilitron/Data/Profiling/ProfilingEventEndArgs.cs
Utilitron/Data/Profiling/ProfilingEventEndArgs.cs
using System; namespace Utilitron.Data.Profiling { public class ProfilingEventEndArgs<T>: ProfilingEventStartArgs<T> { public readonly DateTimeOffset EndTime; public readonly Exception Exception; public TimeSpan Duration => EndTime - StartTime; public bool Success => Exception == null; public ProfilingEventEndArgs(T item, DateTimeOffset startTime, DateTimeOffset endTime) : this(item, startTime, endTime, null) { } public ProfilingEventEndArgs(T item, DateTimeOffset startTime, DateTimeOffset endTime, Exception exception) : base(item, startTime) { EndTime = endTime; Exception = exception; } } }
using System; namespace Utilitron.Data.Profiling { public class ProfilingEventEndArgs<T>: ProfilingEventStartArgs<T> { public readonly DateTimeOffset EndTime; public readonly Exception Exception; public TimeSpan Duration => EndTime - StartTime; public bool Success => Exception != null; public ProfilingEventEndArgs(T item, DateTimeOffset startTime, DateTimeOffset endTime) : this(item, startTime, endTime, null) { } public ProfilingEventEndArgs(T item, DateTimeOffset startTime, DateTimeOffset endTime, Exception exception) : base(item, startTime) { EndTime = endTime; Exception = exception; } } }
mit
C#
f56cc5371ca05303615feebfbe5392c8120b1783
Handle elements without elevation data
pacurrie/KmlToGpxConverter
KmlToGpxConverter/KmlReader.cs
KmlToGpxConverter/KmlReader.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace KmlToGpxConverter { internal static class KmlReader { public const string FileExtension = "kml"; public static IList<GpsTimePoint> ReadFile(string filename) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filename); var nsManager = new XmlNamespaceManager(xmlDoc.NameTable); nsManager.AddNamespace("gx", @"http://www.google.com/kml/ext/2.2"); var list = xmlDoc.SelectNodes("//gx:MultiTrack/gx:Track", nsManager); var nodes = new List<GpsTimePoint>(); foreach (XmlNode element in list) { nodes.AddRange(GetGpsPoints(element.ChildNodes)); } return nodes; } private static IList<GpsTimePoint> GetGpsPoints(XmlNodeList nodes) { var retVal = new List<GpsTimePoint>(); var e = nodes.GetEnumerator(); while (e.MoveNext()) { var utcTimepoint = ((XmlNode)e.Current).InnerText; if (!e.MoveNext()) break; var t = ((XmlNode)e.Current).InnerText.Split(new[] { ' ' }); if (t.Length < 2) continue; retVal.Add(new GpsTimePoint(t[0], t[1], t.ElementAtOrDefault(2), utcTimepoint)); } return retVal; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace KmlToGpxConverter { internal static class KmlReader { public const string FileExtension = "kml"; public static IList<GpsTimePoint> ReadFile(string filename) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filename); var nsManager = new XmlNamespaceManager(xmlDoc.NameTable); nsManager.AddNamespace("gx", @"http://www.google.com/kml/ext/2.2"); var list = xmlDoc.SelectNodes("//gx:MultiTrack/gx:Track", nsManager); var nodes = new List<GpsTimePoint>(); foreach (XmlNode element in list) { nodes.AddRange(GetGpsPoints(element.ChildNodes)); } return nodes; } private static IList<GpsTimePoint> GetGpsPoints(XmlNodeList nodes) { var retVal = new List<GpsTimePoint>(); var e = nodes.GetEnumerator(); while (e.MoveNext()) { var utcTimepoint = ((XmlNode)e.Current).InnerText; if (!e.MoveNext()) break; var t = ((XmlNode)e.Current).InnerText.Split(new[] { ' ' }); if (t.Length != 3) break; retVal.Add(new GpsTimePoint(t[0], t[1], t[2], utcTimepoint)); } return retVal; } } }
mit
C#
e11d363019b524639ed10d7f4fddde2af1092edf
Update Auth0Settings.cs
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/Settings/Auth0Settings.cs
Battery-Commander.Web/Models/Settings/Auth0Settings.cs
namespace BatteryCommander.Web.Models { public class Auth0Settings { public string Domain { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public string ApiIdentifier { get; set; } } }
namespace BatteryCommander.Web.Models { public class Auth0Settings { public string Domain { get; set; } public string CallbackUrl { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public string ApiIdentifier { get; set; } } }
mit
C#
cb827e0697a3015c768ab0efd09e5b620cdd0fbe
fix save endpoint
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/Evaluations/Details.cshtml
Battery-Commander.Web/Views/Evaluations/Details.cshtml
@model Evaluation <!-- Edit link, if available --> <!-- Workflow steps available --> <fieldset> @Html.DisplayForModel() </fieldset> <h2>@Html.DisplayNameFor(_ => Model.Events)</h2> <div> @using (Html.BeginForm("Comment", "Evaluations", FormMethod.Post, new { @class = "form-horitzontal" })) { @Html.AntiForgeryToken() @Html.HiddenFor(_ => _.Id) @Html.TextArea("message") <button type="submit">Add Comment</button> } </div> <table class="table"> <thead></thead> <tbody> @foreach (var @event in Model.Events.OrderByDescending(_ => _.Timestamp)) { <tr> <td>@Html.DisplayFor(_ => @event.Author)</td> <td>@Html.DisplayFor(_ => @event.Message)</td> <td>@Html.DisplayFor(_ => @event.Timestamp)</td> </tr> } </tbody> </table>
@model Evaluation <!-- Edit link, if available --> <!-- Workflow steps available --> <fieldset> @Html.DisplayForModel() </fieldset> <h2>@Html.DisplayNameFor(_ => Model.Events)</h2> <div> @using (Html.BeginForm("Comment", "Evaluation", FormMethod.Post, new { @class = "form-horitzontal" })) { @Html.AntiForgeryToken() @Html.HiddenFor(_ => _.Id) @Html.TextArea("message") <button type="submit">Add Comment</button> } </div> <table class="table"> <thead></thead> <tbody> @foreach (var @event in Model.Events.OrderByDescending(_ => _.Timestamp)) { <tr> <td>@Html.DisplayFor(_ => @event.Author)</td> <td>@Html.DisplayFor(_ => @event.Message)</td> <td>@Html.DisplayFor(_ => @event.Timestamp)</td> </tr> } </tbody> </table>
mit
C#
2b2e22c056de76db930e8988bdfb9cf254d17c36
Fix ScrollOnNewItem so it does work
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/Wpf/ScrollOnNewItem.cs
SolidworksAddinFramework/Wpf/ScrollOnNewItem.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Interactivity; namespace SolidworksAddinFramework.Wpf { /// <summary> /// Copied from http://stackoverflow.com/a/11530459/158285 /// </summary> public class ScrollOnNewItem : Behavior<ListBox> { protected override void OnAttached() { AssociatedObject.Loaded += OnLoaded; AssociatedObject.Unloaded += OnUnLoaded; } protected override void OnDetaching() { AssociatedObject.Loaded -= OnLoaded; AssociatedObject.Unloaded -= OnUnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { var incc = AssociatedObject.ItemsSource as INotifyCollectionChanged; if (incc == null) return; incc.CollectionChanged += OnCollectionChanged; } private void OnUnLoaded(object sender, RoutedEventArgs e) { var incc = AssociatedObject.ItemsSource as INotifyCollectionChanged; if (incc == null) return; incc.CollectionChanged -= OnCollectionChanged; } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { AssociatedObject.Items.MoveCurrentToLast(); if(AssociatedObject.Items.Count>0) AssociatedObject.ScrollIntoView(AssociatedObject.Items.CurrentItem); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Interactivity; namespace SolidworksAddinFramework.Wpf { /// <summary> /// Copied from http://stackoverflow.com/a/11530459/158285 /// </summary> public class ScrollOnNewItem : Behavior<ListBox> { protected override void OnAttached() { AssociatedObject.Loaded += OnLoaded; AssociatedObject.Unloaded += OnUnLoaded; } protected override void OnDetaching() { AssociatedObject.Loaded -= OnLoaded; AssociatedObject.Unloaded -= OnUnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { var incc = AssociatedObject.ItemsSource as INotifyCollectionChanged; if (incc == null) return; incc.CollectionChanged += OnCollectionChanged; } private void OnUnLoaded(object sender, RoutedEventArgs e) { var incc = AssociatedObject.ItemsSource as INotifyCollectionChanged; if (incc == null) return; incc.CollectionChanged -= OnCollectionChanged; } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { int count = AssociatedObject.Items.Count; if (count == 0) return; var item = AssociatedObject.Items[count - 1]; var frameworkElement = AssociatedObject.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement; if (frameworkElement == null) return; frameworkElement.BringIntoView(); } } } }
mit
C#
068060b83ad3616bff382dca543518c448b4576f
prepare release of version 1.2.2
dfensgmbh/biz.dfch.CS.Abiquo.Client
src/AssemblyVersion.cs
src/AssemblyVersion.cs
using System.Reflection; // 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: // // NOTE // also update the corresponding nuspec file when changing the version // [assembly: AssemblyVersion("1.2.2.*")]
using System.Reflection; // 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: // // NOTE // also update the corresponding nuspec file when changing the version // [assembly: AssemblyVersion("1.2.1.*")]
apache-2.0
C#
56eebd86d7fd261c92100857d550a3d974e136a9
Reset board at start of the game.
pjbgf/shogi,pjbgf/shogi
Core.Shogi.Tests/BitVersion/BitboardShogiGameShould.cs
Core.Shogi.Tests/BitVersion/BitboardShogiGameShould.cs
using NSubstitute; using Xunit; namespace Core.Shogi.Tests.BitVersion { public class BitboardShogiGameShould { [Fact] public void IdentifyACheckMateState() { var blackPlayer = new Player(PlayerType.Black); var whitePlayer = new Player(PlayerType.White); var board = new NewBitboard(blackPlayer, whitePlayer); var render = Substitute.For<IBoardRender>(); var shogi = new BitboardShogiGame(board, render); shogi.Start(); blackPlayer.Move("7g7f"); whitePlayer.Move("6a7b"); blackPlayer.Move("8h3c"); whitePlayer.Move("4a4b"); blackPlayer.Move("3c4b"); whitePlayer.Move("5a6a"); var result = blackPlayer.Move("G*5b"); Assert.Equal(BoardResult.CheckMate, result); } [Fact] public void EnsureBoardIsResetAtStartOfGame() { var board = Substitute.For<IBoard>(); var render = Substitute.For<IBoardRender>(); var shogi = new BitboardShogiGame(board, render); shogi.Start(); board.ReceivedWithAnyArgs(1).Reset(); } } public interface IBoard { void Reset(); } public class NewBitboard : IBoard { public NewBitboard(Player blackPlayer, Player whitePlayer) { } public void Reset() { } } public class BitboardShogiGame { private readonly IBoard _board; public BitboardShogiGame(IBoard board, IBoardRender render) { _board = board; } public void Start() { _board.Reset(); } } }
using NSubstitute; using Xunit; namespace Core.Shogi.Tests.BitVersion { public class BitboardShogiGameShould { [Fact] public void IdentifyACheckMateState() { var blackPlayer = new Player(PlayerType.Black); var whitePlayer = new Player(PlayerType.White); var board = new NewBitboard(blackPlayer, whitePlayer); var render = Substitute.For<IBoardRender>(); var shogi = new BitboardShogiGame(board, render); blackPlayer.Move("7g7f"); whitePlayer.Move("6a7b"); blackPlayer.Move("8h3c"); whitePlayer.Move("4a4b"); blackPlayer.Move("3c4b"); whitePlayer.Move("5a6a"); var result = blackPlayer.Move("G*5b"); Assert.Equal(BoardResult.CheckMate, result); } } public class NewBitboard : Board { public NewBitboard(Player blackPlayer, Player whitePlayer) { } } public class BitboardShogiGame { public BitboardShogiGame(Board board, IBoardRender render) { } } }
mit
C#
09e350d14d069def409a82a1b56128bdd79fb17d
Remove canBNull specification
peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu
osu.Desktop/Windows/GameplayWinKeyBlocker.cs
osu.Desktop/Windows/GameplayWinKeyBlocker.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.Bindables; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game; using osu.Game.Configuration; namespace osu.Desktop.Windows { public class GameplayWinKeyBlocker : Component { private Bindable<bool> disableWinKey; private Bindable<bool> localUserPlaying; [Resolved] private GameHost host { get; set; } [BackgroundDependencyLoader] private void load(OsuGame game, OsuConfigManager config) { localUserPlaying = game.LocalUserPlaying.GetBoundCopy(); localUserPlaying.BindValueChanged(_ => updateBlocking()); disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey); disableWinKey.BindValueChanged(_ => updateBlocking(), true); } private void updateBlocking() { bool shouldDisable = disableWinKey.Value && localUserPlaying.Value; if (shouldDisable) host.InputThread.Scheduler.Add(WindowsKey.Disable); else host.InputThread.Scheduler.Add(WindowsKey.Enable); } } }
// 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.Bindables; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game; using osu.Game.Configuration; namespace osu.Desktop.Windows { public class GameplayWinKeyBlocker : Component { private Bindable<bool> disableWinKey; private Bindable<bool> localUserPlaying; [Resolved] private GameHost host { get; set; } [BackgroundDependencyLoader(true)] private void load(OsuGame game, OsuConfigManager config) { localUserPlaying = game.LocalUserPlaying.GetBoundCopy(); localUserPlaying.BindValueChanged(_ => updateBlocking()); disableWinKey = config.GetBindable<bool>(OsuSetting.GameplayDisableWinKey); disableWinKey.BindValueChanged(_ => updateBlocking(), true); } private void updateBlocking() { bool shouldDisable = disableWinKey.Value && localUserPlaying.Value; if (shouldDisable) host.InputThread.Scheduler.Add(WindowsKey.Disable); else host.InputThread.Scheduler.Add(WindowsKey.Enable); } } }
mit
C#
93a8092da6504019b871ba4f219e8b9634715b28
Increase usable width slightly further
peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu
osu.Game/Screens/Edit/Verify/VerifyScreen.cs
osu.Game/Screens/Edit/Verify/VerifyScreen.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.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { [Cached] public class VerifyScreen : EditorScreen { public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>(); public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>(); public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible }; public IssueList IssueList { get; private set; } public VerifyScreen() : base(EditorScreenMode.Verify) { } [BackgroundDependencyLoader] private void load() { InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating); InterpretedDifficulty.SetDefault(); Child = new Container { RelativeSizeAxes = Axes.Both, Child = new GridContainer { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Absolute, 250), }, Content = new[] { new Drawable[] { IssueList = new IssueList(), new IssueSettings(), }, } } }; } } }
// 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.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Screens.Edit.Verify { [Cached] public class VerifyScreen : EditorScreen { public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>(); public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>(); public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible }; public IssueList IssueList { get; private set; } public VerifyScreen() : base(EditorScreenMode.Verify) { } [BackgroundDependencyLoader] private void load() { InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating); InterpretedDifficulty.SetDefault(); Child = new Container { RelativeSizeAxes = Axes.Both, Child = new GridContainer { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Absolute, 225), }, Content = new[] { new Drawable[] { IssueList = new IssueList(), new IssueSettings(), }, } } }; } } }
mit
C#
bed5a55b216f501f3528315f57bf7e0bf4f51fdc
Add message to test failure
benallred/Icing
Icing/Icing.Tests/Core/Diagnostics/TestOf_Algorithm.cs
Icing/Icing.Tests/Core/Diagnostics/TestOf_Algorithm.cs
using System; using System.Threading; using Icing.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Icing.Tests.Core.Diagnostics { [TestClass] public class TestOf_Algorithm { [TestMethod] public void Constructor() { Algorithm algorithm; Action action; action = () => { }; algorithm = new Algorithm("asdf", action); Assert.AreEqual("asdf", algorithm.Name); Assert.AreEqual(action, algorithm.Action); action = () => { 2.ToString(); }; algorithm = new Algorithm(action); Assert.AreEqual("Algorithm 2", algorithm.Name); Assert.AreEqual(action, algorithm.Action); action = () => { }; algorithm = new Algorithm("qwer", action); Assert.AreEqual("qwer", algorithm.Name); Assert.AreEqual(action, algorithm.Action); algorithm = new Algorithm(null, action); Assert.AreEqual("Algorithm 4", algorithm.Name); Assert.AreEqual(action, algorithm.Action); algorithm = new Algorithm("", action); Assert.AreEqual("Algorithm 5", algorithm.Name); Assert.AreEqual(action, algorithm.Action); algorithm = new Algorithm(" ", action); Assert.AreEqual("Algorithm 6", algorithm.Name); Assert.AreEqual(action, algorithm.Action); } [TestMethod] public void BenchmarkAndCacheExecutionTime() { Algorithm algorithm = new Algorithm(() => Thread.Sleep(10)); Stats executionTime = algorithm.BenchmarkAndCacheExecutionTime(100, false); Assert.AreEqual(100, executionTime.TotalIterations); Assert.IsTrue(1000 < executionTime.Total && executionTime.Total < 2000, "Actual execution time: " + executionTime.Total); Assert.AreEqual(executionTime.Min, executionTime.Average); Assert.AreEqual(executionTime.Average, executionTime.Max); } [TestMethod] public void BenchmarkAndCacheExecutionTime_ReportIndividualIterations() { Algorithm algorithm = new Algorithm(() => Thread.Sleep(10)); Stats executionTime = algorithm.BenchmarkAndCacheExecutionTime(100, true); Assert.AreEqual(100, executionTime.TotalIterations); Assert.IsTrue(1000 < executionTime.Total && executionTime.Total < 2000, "Actual execution time: " + executionTime.Total); Assert.IsTrue(executionTime.Min < executionTime.Average); Assert.IsTrue(executionTime.Average < executionTime.Max); } [TestMethod] public void BenchmarkAndCacheExecutionTime_Formatter() { Stats executionTime = new Algorithm(() => {}).BenchmarkAndCacheExecutionTime(1, false); executionTime.Total = 1000 * 60 * 60 * 24 + 1000 * 60 * 60 + 1000 * 60 + 1000 + 1; executionTime.TotalIterations = (int)executionTime.Total; executionTime.ExpectedIterations = executionTime.TotalIterations; executionTime.Min = 1000 * 60; executionTime.Max = 1000 * 60 * 60; Assert.AreEqual("Total: 01.01:01:01.001; Min: 01:00.000; Max: 01:00:00.000; Avg: 00.001; Expected: 01.01:01:01.001", executionTime.ToString()); } } }
using System; using System.Threading; using Icing.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Icing.Tests.Core.Diagnostics { [TestClass] public class TestOf_Algorithm { [TestMethod] public void Constructor() { Algorithm algorithm; Action action; action = () => { }; algorithm = new Algorithm("asdf", action); Assert.AreEqual("asdf", algorithm.Name); Assert.AreEqual(action, algorithm.Action); action = () => { 2.ToString(); }; algorithm = new Algorithm(action); Assert.AreEqual("Algorithm 2", algorithm.Name); Assert.AreEqual(action, algorithm.Action); action = () => { }; algorithm = new Algorithm("qwer", action); Assert.AreEqual("qwer", algorithm.Name); Assert.AreEqual(action, algorithm.Action); algorithm = new Algorithm(null, action); Assert.AreEqual("Algorithm 4", algorithm.Name); Assert.AreEqual(action, algorithm.Action); algorithm = new Algorithm("", action); Assert.AreEqual("Algorithm 5", algorithm.Name); Assert.AreEqual(action, algorithm.Action); algorithm = new Algorithm(" ", action); Assert.AreEqual("Algorithm 6", algorithm.Name); Assert.AreEqual(action, algorithm.Action); } [TestMethod] public void BenchmarkAndCacheExecutionTime() { Algorithm algorithm = new Algorithm(() => Thread.Sleep(10)); Stats executionTime = algorithm.BenchmarkAndCacheExecutionTime(100, false); Assert.AreEqual(100, executionTime.TotalIterations); Assert.IsTrue(1000 < executionTime.Total && executionTime.Total < 1200); Assert.AreEqual(executionTime.Min, executionTime.Average); Assert.AreEqual(executionTime.Average, executionTime.Max); } [TestMethod] public void BenchmarkAndCacheExecutionTime_ReportIndividualIterations() { Algorithm algorithm = new Algorithm(() => Thread.Sleep(10)); Stats executionTime = algorithm.BenchmarkAndCacheExecutionTime(100, true); Assert.AreEqual(100, executionTime.TotalIterations); Assert.IsTrue(1000 < executionTime.Total && executionTime.Total < 1200); Assert.IsTrue(executionTime.Min < executionTime.Average); Assert.IsTrue(executionTime.Average < executionTime.Max); } [TestMethod] public void BenchmarkAndCacheExecutionTime_Formatter() { Stats executionTime = new Algorithm(() => {}).BenchmarkAndCacheExecutionTime(1, false); executionTime.Total = 1000 * 60 * 60 * 24 + 1000 * 60 * 60 + 1000 * 60 + 1000 + 1; executionTime.TotalIterations = (int)executionTime.Total; executionTime.ExpectedIterations = executionTime.TotalIterations; executionTime.Min = 1000 * 60; executionTime.Max = 1000 * 60 * 60; Assert.AreEqual("Total: 01.01:01:01.001; Min: 01:00.000; Max: 01:00:00.000; Avg: 00.001; Expected: 01.01:01:01.001", executionTime.ToString()); } } }
mit
C#
f45f5288376fc366d526b9f655c65a067a3fe1c3
Add optional parameter to UseCloudFoundryHosting() to set port in code [delivers #154771454]
SteelToeOSS/Configuration,SteelToeOSS/Configuration,SteelToeOSS/Configuration
src/Steeltoe.Extensions.Configuration.CloudFoundryCore/CloudFoundryHostBuilderExtensions.cs
src/Steeltoe.Extensions.Configuration.CloudFoundryCore/CloudFoundryHostBuilderExtensions.cs
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.AspNetCore.Hosting; using System; using System.Collections.Generic; namespace Steeltoe.Extensions.Configuration.CloudFoundry { public static class CloudFoundryHostBuilderExtensions { /// <summary> /// Enable the application to listen on port(s) provided by the environment at runtime /// </summary> /// <param name="webHostBuilder">Your WebHostBuilder</param> /// <param name="runLocalPort">Set the port number with code so you don't need to set environment variables locally</param> /// <returns>Your WebHostBuilder, now listening on port(s) found in the environment or passed in</returns> /// <remarks>runLocalPort parameter will not be used if an environment variable PORT is found</remarks> public static IWebHostBuilder UseCloudFoundryHosting(this IWebHostBuilder webHostBuilder, int? runLocalPort = null) { if (webHostBuilder == null) { throw new ArgumentNullException(nameof(webHostBuilder)); } List<string> urls = new List<string>(); string portStr = Environment.GetEnvironmentVariable("PORT"); if (!string.IsNullOrWhiteSpace(portStr)) { if (int.TryParse(portStr, out int port)) { urls.Add($"http://*:{port}"); } } else if (runLocalPort != null) { urls.Add($"http://*:{runLocalPort}"); } if (urls.Count > 0) { webHostBuilder.UseUrls(urls.ToArray()); } return webHostBuilder; } public static IWebHostBuilder AddCloudFoundry(this IWebHostBuilder hostBuilder) { hostBuilder.ConfigureAppConfiguration((context, config) => { config.AddCloudFoundry(); }); return hostBuilder; } } }
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.AspNetCore.Hosting; using System; using System.Collections.Generic; namespace Steeltoe.Extensions.Configuration.CloudFoundry { public static class CloudFoundryHostBuilderExtensions { public static IWebHostBuilder UseCloudFoundryHosting(this IWebHostBuilder webHostBuilder) { if (webHostBuilder == null) { throw new ArgumentNullException(nameof(webHostBuilder)); } List<string> urls = new List<string>(); string portStr = Environment.GetEnvironmentVariable("PORT"); if (!string.IsNullOrWhiteSpace(portStr)) { int port; if (int.TryParse(portStr, out port)) { urls.Add($"http://*:{port}"); } } if (urls.Count > 0) { webHostBuilder.UseUrls(urls.ToArray()); } return webHostBuilder; } public static IWebHostBuilder AddCloudFoundry(this IWebHostBuilder hostBuilder) { hostBuilder.ConfigureAppConfiguration((context, config) => { config.AddCloudFoundry(); }); return hostBuilder; } } }
apache-2.0
C#
dc70450bd5ad5bffe6867e1891666b022ac2e007
fix parse
RaghavAbboy/Orchard.ParkingData,CityofSantaMonica/Orchard.ParkingData
Services/ParkingLotsService.cs
Services/ParkingLotsService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using CSM.ParkingData.ViewModels; using Microsoft.WindowsAzure; namespace CSM.ParkingData.Services { public class ParkingLotsService : IParkingLotsService { public IEnumerable<ParkingLot> Get() { var lotDataUrl = CloudConfigurationManager.GetSetting("ParkingLotDataUrl"); return Get(lotDataUrl); } public IEnumerable<ParkingLot> Get(string lotDataUrl) { XDocument xdocument; try { xdocument = XDocument.Load(lotDataUrl); } catch { return Enumerable.Empty<ParkingLot>(); } var lots = new List<ParkingLot>(); foreach (var lot in xdocument.Root.Elements("lot")) { lots.Add(new ParkingLot() { AvailableSpaces = Convert.ToInt32(lot.Element("available").Value), Description = lot.Element("description").Value, Latitude = Convert.ToDecimal(lot.Element("latitude").Value), Longitude = Convert.ToDecimal(lot.Element("longitude").Value), Name = lot.Element("name").Value, StreetAddress = lot.Element("address").Value, ZipCode = Convert.ToInt32(lot.Element("zip").Value) }); } return lots; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using CSM.ParkingData.ViewModels; using Microsoft.WindowsAzure; namespace CSM.ParkingData.Services { public class ParkingLotsService : IParkingLotsService { public IEnumerable<ParkingLot> Get() { var lotDataUrl = CloudConfigurationManager.GetSetting("ParkingLotDataUrl"); return Get(lotDataUrl); } public IEnumerable<ParkingLot> Get(string lotDataUrl) { XDocument xdocument; try { xdocument = XDocument.Load(lotDataUrl); } catch { return Enumerable.Empty<ParkingLot>(); } var lots = new List<ParkingLot>(); foreach (var lot in xdocument.Root.Elements("lot")) { lots.Add(new ParkingLot() { AvailableSpaces = Convert.ToInt32(lot.Element("available").Value), Description = lot.Element("description").Value, Latitude = Convert.ToDecimal(lot.Element("latitude").Value), Longitude = Convert.ToDecimal(lot.Element("longitude").Value), Name = lot.Element("name").Value, StreetAddress = lot.Element("address").Value, ZipCode = Convert.ToInt16(lot.Element("zip").Value) }); } return lots; } } }
mit
C#
9ef323d49636fc2396c753535d9e63ba56d4b886
Test change
geaz/coreDox,geaz/coreDox,geaz/coreDox
tests/coreDox.Core.Tests/Project/ProjectTests.cs
tests/coreDox.Core.Tests/Project/ProjectTests.cs
using coreDox.Core.Project; using coreDox.Core.Project.Config; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace coreDox.Core.Tests.Projects { [TestClass] public class ProjectTests { private string _tmpPath = Path.Combine(Path.GetTempPath(), "testProject"); [TestCleanup] public void TestCleanUp() { if(Directory.Exists(_tmpPath)) Directory.Delete(_tmpPath, true); } [TestMethod] public void ShouldCreateDefaultProjectSuccessfully() { //Arrange var project = new DoxProject(); //Act project.Create(_tmpPath); //Assert Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.AssetFolderName))); Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.LayoutFolderName))); Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.PagesFolderName))); Assert.IsTrue(File.Exists(Path.Combine(_tmpPath, DoxProjectConfig.ConfigFileName))); } [TestMethod] public void ShouldLoadProjectSuccessfully() { //Arrange var project = new DoxProject(); var projectPath = Path.Combine( Path.GetDirectoryName(typeof(ProjectTests).Assembly.Location), "..", "..", "..", "..", "..", "doc", "testDoc"); //Act project.Load(projectPath); //Assert Assert.IsTrue(project.PagesDirectory.Exists); } } }
using coreDox.Core.Project; using coreDox.Core.Project.Config; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace coreDox.Core.Tests.Projects { [TestClass] public class ProjectTests { private string _tmpPath = Path.Combine(Path.GetTempPath(), "testProject"); [TestCleanup] public void TestCleanUp() { if(Directory.Exists(_tmpPath)) Directory.Delete(_tmpPath, true); } [TestMethod] public void ShouldCreateDefaultProjectSuccessfully() { //Arrange var project = new DoxProject(); //Act project.Create(_tmpPath); //Assert Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.AssetFolderName))); Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.LayoutFolderName))); Assert.IsTrue(Directory.Exists(Path.Combine(_tmpPath, DoxProject.PagesFolderName))); Assert.IsTrue(File.Exists(Path.Combine(_tmpPath, DoxProjectConfig.ConfigFileName))); } [TestMethod] public void ShouldLoadProjectSuccessfully() { //Arrange var project = new DoxProject(); var projectPath = Path.Combine( Path.GetDirectoryName(typeof(ProjectTests).Assembly.Location), "..", "..", "..", "..", "..", "doc", "testDoc"); //Act project.Load(projectPath); //Assert Assert.IsTrue(project.RootProjectDirectory.Exists); } } }
mit
C#
bd1007d44ae046998941412a9bad4324a21052af
Set version to 0.1.0.
ruisebastiao/gong-wpf-dragdrop,emsaks/gong-wpf-dragdrop,Haukinger/gong-wpf-dragdrop,JohnnyJoe/Johnny-s-repository,Livit/Mailbird.Gong.WPF.DragDrop,JohnnyJoe/Johnny-s-repository,punker76/gong-wpf-dragdrop,huoxudong125/gong-wpf-dragdrop
GongSolutions.Wpf.DragDrop/Properties/AssemblyInfo.cs
GongSolutions.Wpf.DragDrop/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GongSolutions.Wpf.DragDrop")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GongSolutions.Wpf.DragDrop")] [assembly: AssemblyCopyright("Copyright © 2009")] [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("940084f7-d48e-41b3-9e0d-cf574d587643")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyFileVersion("0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GongSolutions.Wpf.DragDrop")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GongSolutions.Wpf.DragDrop")] [assembly: AssemblyCopyright("Copyright © 2009")] [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("940084f7-d48e-41b3-9e0d-cf574d587643")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bsd-3-clause
C#
9785e4c3720d047fe5eb224875a53f11bfe51b75
Change assembly version
lury-lang/lury-lexer
lury-lexer/Properties/AssemblyInfo.cs
lury-lexer/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("lury-lexer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lury Programming Language")] [assembly: AssemblyCopyright("Copyright © 2015 Tomona Nanase")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("864cc7a3-015a-4c21-9f1f-c6fbb30e8673")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("lury-lexer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lury Programming Language")] [assembly: AssemblyCopyright("Copyright © 2015 Tomona Nanase")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("864cc7a3-015a-4c21-9f1f-c6fbb30e8673")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
212fe092effde0af598e66e85f62bc5d9430fab9
Update button helper
litsungyi/Camus
Scripts/UiUtilities/ButtonHelper.cs
Scripts/UiUtilities/ButtonHelper.cs
using System; using Camus.Validators; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.UI; namespace Camus.UiUtilities { public class ButtonHelper : MonoBehaviour, IButtonProcessingExternalHandler { [SerializeField, NotNull] private Button button; private Text uiText; private void Awake() { if (uiText == null) { uiText = button.GetComponentInChildren<Text>(); } } public void SetOnClickedCallback(Action onClicked) { Assert.IsNotNull(onClicked); button.onClick.AddListener(() => onClicked?.Invoke()); } public void SetText(string text) { if (uiText != null) { uiText.text = text; } } public void SetColor(Color color) { button.image.color = color; } #region IButtonProcessingExternalHandler IButtonProcessingHandler IButtonProcessingExternalHandler.Holder { get; set; } #endregion } }
using System; using Camus.Validators; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.UI; namespace Camus.UiUtilities { public class ButtonHelper : MonoBehaviour, IButtonProcessingExternalHandler { [SerializeField, NotNull] private Button button; public void SetOnClickedCallback(Action onClicked) { Assert.IsNotNull(onClicked); button.onClick.AddListener(() => onClicked?.Invoke()); } public void SetColor(Color color) { button.image.color = color; } #region IButtonProcessingExternalHandler IButtonProcessingHandler IButtonProcessingExternalHandler.Holder { get; set; } #endregion } }
mit
C#
e256d4a58138fd52c1c583dc07ab11412f5ea24b
Use the shortest path if assemblies have the same file name
hruan/Pennyworth
Pennyworth/DropHelper.cs
Pennyworth/DropHelper.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Pennyworth { public static class DropHelper { public static IEnumerable<String> GetAssembliesFromDropData(IEnumerable<FileInfo> data) { Func<FileInfo, Boolean> isDir = fi => ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory); Func<FileInfo, Boolean> isFile = fi => ((fi.Attributes & FileAttributes.Directory) != FileAttributes.Directory); var files = data.Where(isFile); var dirs = data.Where(isDir); var assembliesInDirs = dirs.SelectMany(dir => Directory.EnumerateFiles(dir.FullName, "*.exe", SearchOption.AllDirectories) .Where(path => !path.Contains("vshost"))); return files.Select(fi => fi.FullName).Concat(DiscardSimilarFiles(assembliesInDirs.ToList())); } private static IEnumerable<String> DiscardSimilarFiles(List<String> assemblies) { var fileNames = assemblies.Select(Path.GetFileName).Distinct(); var namePathLookup = assemblies.ToLookup(Path.GetFileName); foreach (var file in fileNames) { var paths = namePathLookup[file].ToList(); if (paths.Any()) { if (paths.Count > 1) { paths.Sort(String.CompareOrdinal); } yield return paths.First(); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Pennyworth { public static class DropHelper { public static IEnumerable<String> GetAssembliesFromDropData(IEnumerable<FileInfo> data) { Func<FileInfo, Boolean> isDir = fi => ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory); Func<FileInfo, Boolean> isFile = fi => ((fi.Attributes & FileAttributes.Directory) != FileAttributes.Directory); var files = data.Where(isFile); var dirs = data .Where(isDir) .Select(fi => { if (fi.FullName.EndsWith("bin", StringComparison.OrdinalIgnoreCase)) return new FileInfo(fi.Directory.FullName); return fi; }) .SelectMany(fi => Directory.EnumerateDirectories(fi.FullName, "bin", SearchOption.AllDirectories)); var firstAssemblies = dirs.Select(dir => Directory.EnumerateFiles(dir, "*.exe", SearchOption.AllDirectories) .FirstOrDefault(path => !path.Contains("vshost"))) .Where(dir => !String.IsNullOrEmpty(dir)); return files.Select(fi => fi.FullName) .Concat(firstAssemblies) .Where(path => Path.HasExtension(path) && (path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))); } } }
mit
C#
d83337e7c1094a1626c9325024387a6a35f56e9f
Make XHud MaskType cast-able to AndHud MaskType
Redth/AndHUD,Redth/AndHUD
AndHUD/XHUD.cs
AndHUD/XHUD.cs
using System; using Android.App; using AndroidHUD; namespace XHUD { public enum MaskType { // None = 1, Clear = 2, Black = 3, // Gradient } public static class HUD { public static Activity MyActivity; public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black) { AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType); } public static void Dismiss() { AndHUD.Shared.Dismiss(HUD.MyActivity); } public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } } }
using System; using Android.App; using AndroidHUD; namespace XHUD { public enum MaskType { // None = 1, Clear, Black, // Gradient } public static class HUD { public static Activity MyActivity; public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black) { AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType); } public static void Dismiss() { AndHUD.Shared.Dismiss(HUD.MyActivity); } public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000) { AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered); } } }
apache-2.0
C#
e1dff722541227a32cc964603853b55202ff6e4b
build script updated, not to use fixed version
flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core
BuildScript.cs
BuildScript.cs
using System; using FlubuCore.Context; using FlubuCore.Scripting; using FlubuCore.Targeting; using FlubuCore.Tasks.NetCore; using FlubuCore.Tasks.Text; using FlubuCore.Tasks.Versioning; public class MyBuildScript : DefaultBuildScript { protected override void ConfigureBuildProperties(ITaskSession session) { Console.WriteLine("1"); } protected override void ConfigureTargets(ITaskSession session) { session .CreateTarget("compile") .AddTask(new FetchVersionFromExternalSourceTask()) .AddTask(new UpdateNetCoreVersionTask("FlubuCore/project.json", "dotnet-flubu/project.json", "Flubu.Tests/project.json") .AdditionalProp("dependencies.FlubuCore", "dependencies.dotnet-flubu")) .AddTask(new ExecuteDotnetTask("restore").WithArguments("FlubuCore")) .AddTask(new ExecuteDotnetTask("restore").WithArguments("dotnet-flubu")) .AddTask(new ExecuteDotnetTask("restore").WithArguments("Flubu.Tests")) .AddTask(new ExecuteDotnetTask("pack").WithArguments("FlubuCore", "-c", "Release")) .AddTask(new ExecuteDotnetTask("pack").WithArguments("dotnet-flubu", "-c", "Release")); } }
using System; using FlubuCore.Context; using FlubuCore.Scripting; using FlubuCore.Targeting; using FlubuCore.Tasks.NetCore; using FlubuCore.Tasks.Text; using FlubuCore.Tasks.Versioning; public class MyBuildScript : DefaultBuildScript { protected override void ConfigureBuildProperties(ITaskSession session) { Console.WriteLine("1"); } protected override void ConfigureTargets(ITaskSession session) { session .CreateTarget("compile") //.AddTask(new FetchVersionFromExternalSourceTask()) .AddTask(new UpdateNetCoreVersionTask("FlubuCore/project.json", "dotnet-flubu/project.json", "Flubu.Tests/project.json") .FixedVersion(new Version(1, 0, 82, 0)) .AdditionalProp("dependencies.FlubuCore", "dependencies.dotnet-flubu")) .AddTask(new ExecuteDotnetTask("restore").WithArguments("FlubuCore")) .AddTask(new ExecuteDotnetTask("restore").WithArguments("dotnet-flubu")) .AddTask(new ExecuteDotnetTask("restore").WithArguments("Flubu.Tests")) .AddTask(new ExecuteDotnetTask("pack").WithArguments("FlubuCore", "-c", "Release")) .AddTask(new ExecuteDotnetTask("pack").WithArguments("dotnet-flubu", "-c", "Release")); } }
bsd-2-clause
C#
76d2dc40d94b1a79f100fe3a4f6521bb095cf9b0
Make the code in the entrypoint even shorter.
DavidLievrouw/WordList
src/WordList/Program.cs
src/WordList/Program.cs
using System; using Autofac; using WordList.Composition; namespace WordList { public class Program { public static void Main(string[] args) { CompositionRoot.Compose().Resolve<IWordListProgram>().Run(); Console.WriteLine("Press any key to quit..."); Console.ReadKey(); } } }
using System; using Autofac; using WordList.Composition; namespace WordList { public class Program { public static void Main(string[] args) { var compositionRoot = CompositionRoot.Compose(); var wordListProgram = compositionRoot.Resolve<IWordListProgram>(); wordListProgram.Run(); Console.WriteLine("Press any key to quit..."); Console.ReadKey(); } } }
mit
C#
241cb9c50b62b273ba33e5c066c17418c11abe2d
add LocalCacheDeadLockInGetTest
mc7246/WeiXinMPSDK,wanddy/WeiXinMPSDK,down4u/WeiXinMPSDK,lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,mc7246/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP.Test/CacheTests/CacheTests.cs
src/Senparc.Weixin.MP/Senparc.Weixin.MP.Test/CacheTests/CacheTests.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Senparc.Weixin.Cache; using Senparc.Weixin.Cache.Redis; using Senparc.Weixin.MP.AdvancedAPIs; using Senparc.Weixin.MP.Test.CommonAPIs; namespace Senparc.Weixin.MP.Test.CacheTests { [TestClass] public class CacheTests : CommonApiTest { private void LocalCacheDeadLockTestThreadFun() { UserApi.Info(base._appId, base._testOpenId); } [TestMethod] public void LocalCacheDeadLockTest() { //测试本地缓存死锁问题 CacheStrategyFactory.RegisterObjectCacheStrategy(() => LocalObjectCacheStrategy.Instance);//Local List<Task> taskList = new List<Task>(); var dt1 = DateTime.Now; for (int i = 0; i < 50; i++) { var lastTask = new Task(LocalCacheDeadLockTestThreadFun); lastTask.Start(); taskList.Add(lastTask); } Task.WaitAll(taskList.ToArray()); var dt2 = DateTime.Now; Console.Write("总耗时:{0}ms", (dt2 - dt1).TotalMilliseconds); } [TestMethod] public void LocalCacheDeadLockInGetTest() { //测试死锁发生 //Task.Factory.StartNew(() => //{ var dt1 = DateTime.Now; for (int i = 0; i < 10; i++) { Console.WriteLine("开始循环:{0}", i); Senparc.Weixin.MP.AdvancedAPIs.UserApi.InfoAsync(base._appId, base._testOpenId); Console.WriteLine("结束循环:{0}\r\n", i); } var dt2 = DateTime.Now; Console.Write("总耗时:{0}ms", (dt2 - dt1).TotalMilliseconds); //}).Wait(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Senparc.Weixin.Cache; using Senparc.Weixin.Cache.Redis; using Senparc.Weixin.MP.AdvancedAPIs; using Senparc.Weixin.MP.Test.CommonAPIs; namespace Senparc.Weixin.MP.Test.CacheTests { [TestClass] public class CacheTests : CommonApiTest { private void LocalCacheDeadLockTestThreadFun() { UserApi.Info(base._appId, base._testOpenId); } [TestMethod] public void LocalCacheDeadLockTest() { //测试本地缓存死锁问题 CacheStrategyFactory.RegisterObjectCacheStrategy(() => LocalObjectCacheStrategy.Instance);//Local List<Task> taskList = new List<Task>(); var dt1 = DateTime.Now; for (int i = 0; i < 50; i++) { var lastTask = new Task(LocalCacheDeadLockTestThreadFun); lastTask.Start(); taskList.Add(lastTask); } Task.WaitAll(taskList.ToArray()); var dt2 = DateTime.Now; Console.Write("总耗时:{0}ms",(dt2-dt1).TotalMilliseconds); } } }
apache-2.0
C#
b66a7c6decc78a763e7d5220df41c239bab8c119
Make points orderable
TheEadie/PlayerRank,TheEadie/PlayerRank
PlayerRank/Points.cs
PlayerRank/Points.cs
using System; namespace PlayerRank { public class Points : IComparable { private readonly double m_Points; public Points(double points) { m_Points = points; } [Obsolete("This getter will be removed in a future version")] internal double GetValue() { return m_Points; } protected bool Equals(Points other) { return m_Points.Equals(other.m_Points); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((Points) obj); } public override int GetHashCode() { return m_Points.GetHashCode(); } public int CompareTo(object obj) { var other = obj as Points; if (other == null) throw new ArgumentException("Can not compare Points to other type"); if (other > this) return -1; if (other < this) return 1; return 0; } public static Points operator +(Points pointsA, Points pointsB) { return new Points(pointsA.m_Points + pointsB.m_Points); } public static Points operator -(Points pointsA, Points pointsB) { return new Points(pointsA.m_Points - pointsB.m_Points); } public static double operator /(Points points, double divider) { return points.m_Points / divider; } public static bool operator >(Points pointsA, Points pointsB) { return (pointsA.m_Points > pointsB.m_Points); } public static bool operator <(Points pointsA, Points pointsB) { return (pointsA.m_Points < pointsB.m_Points); } public static bool operator ==(Points pointsA, Points pointsB) { return (pointsA.m_Points == pointsB.m_Points); } public static bool operator !=(Points pointsA, Points pointsB) { return !(pointsA == pointsB); } public override string ToString() { return m_Points.ToString(); } } }
using System; namespace PlayerRank { public class Points { private readonly double m_Points; public Points(double points) { m_Points = points; } [Obsolete("This getter will be removed in a future version")] internal double GetValue() { return m_Points; } protected bool Equals(Points other) { return m_Points.Equals(other.m_Points); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((Points) obj); } public override int GetHashCode() { return m_Points.GetHashCode(); } public static Points operator +(Points pointsA, Points pointsB) { return new Points(pointsA.m_Points + pointsB.m_Points); } public static Points operator -(Points pointsA, Points pointsB) { return new Points(pointsA.m_Points - pointsB.m_Points); } public static double operator /(Points points, double divider) { return points.m_Points / divider; } public static bool operator >(Points pointsA, Points pointsB) { return (pointsA.m_Points > pointsB.m_Points); } public static bool operator <(Points pointsA, Points pointsB) { return (pointsA.m_Points < pointsB.m_Points); } public static bool operator ==(Points pointsA, Points pointsB) { return (pointsA.m_Points == pointsB.m_Points); } public static bool operator !=(Points pointsA, Points pointsB) { return !(pointsA == pointsB); } public override string ToString() { return m_Points.ToString(); } } }
mit
C#
030865cf921b6fb731d26bce98cc2f873d9eaff1
Add FirstLetterToLower() to each exception message
lecaillon/Evolve
src/Evolve/Exception/EvolveConfigurationException.cs
src/Evolve/Exception/EvolveConfigurationException.cs
using System; namespace Evolve { public class EvolveConfigurationException : EvolveException { private const string EvolveConfigurationError = "Evolve configuration error: "; public EvolveConfigurationException(string message) : base(EvolveConfigurationError + FirstLetterToLower(message)) { } public EvolveConfigurationException(string message, Exception innerException) : base(EvolveConfigurationError + FirstLetterToLower(message), innerException) { } private static string FirstLetterToLower(string str) { if (str == null) { return ""; } if (str.Length > 1) { return Char.ToLowerInvariant(str[0]) + str.Substring(1); } return str.ToLowerInvariant(); } } }
using System; namespace Evolve { public class EvolveConfigurationException : EvolveException { private const string EvolveConfigurationError = "Evolve configuration error: "; public EvolveConfigurationException(string message) : base(EvolveConfigurationError + message) { } public EvolveConfigurationException(string message, Exception innerException) : base(EvolveConfigurationError + message, innerException) { } } }
mit
C#
4739a03e0a7663f164d8804693f442f1962a509a
Fix integration test
tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools
tests/Tgstation.Server.Tests/TestingServer.cs
tests/Tgstation.Server.Tests/TestingServer.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host; namespace Tgstation.Server.Tests { sealed class TestingServer : IServer { public Uri Url { get; } public string Directory { get; } public bool RestartRequested => realServer.RestartRequested; readonly IServer realServer; public TestingServer() { Directory = Path.GetTempFileName(); File.Delete(Directory); System.IO.Directory.CreateDirectory(Directory); Url = new Uri("http://localhost:5001"); //so we need a db //we have to rely on env vars var databaseType = Environment.GetEnvironmentVariable("TGS4_TEST_DATABASE_TYPE"); var connectionString = Environment.GetEnvironmentVariable("TGS4_TEST_CONNECTION_STRING"); if (String.IsNullOrEmpty(databaseType)) Assert.Fail("No database type configured in env var TGS4_TEST_DATABASE_TYPE!"); if (String.IsNullOrEmpty(connectionString)) Assert.Fail("No connection string configured in env var TGS4_TEST_CONNECTION_STRING!"); realServer = new ServerFactory().CreateServer(new string[] { String.Format(CultureInfo.InvariantCulture, "Kestrel:EndPoints:Http:Url={0}", Url), String.Format(CultureInfo.InvariantCulture, "Database:DatabaseType={0}", databaseType), String.Format(CultureInfo.InvariantCulture, "Database:ConnectionString={0}", connectionString), "Database:DropDatabase=true" }, null); } public void Dispose() { realServer.Dispose(); System.IO.Directory.Delete(Directory, true); } public Task RunAsync(CancellationToken cancellationToken) => realServer.RunAsync(cancellationToken); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host; namespace Tgstation.Server.Tests { sealed class TestingServer : IServer { public Uri Url { get; } public string Directory { get; } public bool RestartRequested => realServer.RestartRequested; readonly IServer realServer; public TestingServer() { Directory = Path.GetTempFileName(); File.Delete(Directory); System.IO.Directory.CreateDirectory(Directory); Url = new Uri("http://localhost:5001"); //so we need a db //we have to rely on env vars var databaseType = Environment.GetEnvironmentVariable("TGS4_TEST_DATABASE_TYPE"); var connectionString = Environment.GetEnvironmentVariable("TGS4_TEST_CONNECTION_STRING"); if (String.IsNullOrEmpty(databaseType)) Assert.Fail("No database type configured in env var TGS4_TEST_DATABASE_TYPE!"); if (String.IsNullOrEmpty(connectionString)) Assert.Fail("No connection string configured in env var TGS4_TEST_CONNECTION_STRING!"); realServer = new ServerFactory().CreateServer(new string[] { "--urls", Url.ToString(), String.Format(CultureInfo.InvariantCulture, "Database:DatabaseType={0}", databaseType), String.Format(CultureInfo.InvariantCulture, "Database:ConnectionString={0}", connectionString), "Database:DropDatabase=true" }, null); } public void Dispose() { realServer.Dispose(); System.IO.Directory.Delete(Directory, true); } public Task RunAsync(CancellationToken cancellationToken) => realServer.RunAsync(cancellationToken); } }
agpl-3.0
C#
045dfd1ddfaf96ed10e5cd779633b32ff407a8ef
Tidy up DependsOnAttribute
eightlittlebits/elbsms
elbemu_shared/Configuration/DependsOnAttribute.cs
elbemu_shared/Configuration/DependsOnAttribute.cs
using System; namespace elbemu_shared.Configuration { [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)] public sealed class DependsOnAttribute : Attribute { public string PropertyName { get; } public DependsOnAttribute(string propertyName) { PropertyName = propertyName; } } }
using System; namespace elbemu_shared.Configuration { [AttributeUsage(System.AttributeTargets.Property, Inherited = false, AllowMultiple = false)] public sealed class DependsOnAttribute : System.Attribute { public string PropertyName { get; } // This is a positional argument public DependsOnAttribute(string propertyName) { PropertyName = propertyName; } } }
mit
C#
333194f5b16f968d93d48b54f5ff8b1ed1387ebd
Disable Kestrel server header
martincostello/api,martincostello/api,martincostello/api
src/API/Program.cs
src/API/Program.cs
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the MIT license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Api { using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// The exit code from the application. /// </returns> public static int Main(string[] args) { try { CreateHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Console.Error.WriteLine($"Unhandled exception: {ex}"); return -1; } } /// <summary> /// Creates the host builder to use for the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// A <see cref="IHostBuilder"/> to use. /// </returns> public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults( (webBuilder) => { webBuilder.CaptureStartupErrors(true) .ConfigureKestrel((p) => p.AddServerHeader = false) .UseStartup<Startup>(); }); } } }
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the MIT license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Api { using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// The exit code from the application. /// </returns> public static int Main(string[] args) { try { CreateHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Console.Error.WriteLine($"Unhandled exception: {ex}"); return -1; } } /// <summary> /// Creates the host builder to use for the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// A <see cref="IHostBuilder"/> to use. /// </returns> public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults( (webBuilder) => { webBuilder.CaptureStartupErrors(true) .UseStartup<Startup>(); }); } } }
mit
C#
6bb4e11e8c758232ebbc451658f31da8ffe9a803
Remove unused attribute in RunnerInvocation
BennieCopeland/NSpec,mattflo/NSpec,mattflo/NSpec,nspec/NSpec,mattflo/NSpec,mattflo/NSpec,nspectator/NSpectator,nspectator/NSpectator,nspec/NSpec,BennieCopeland/NSpec
NSpec/Domain/RunnerInvocation.cs
NSpec/Domain/RunnerInvocation.cs
using System; using NSpec.Domain.Formatters; namespace NSpec.Domain { [Serializable] public class RunnerInvocation { public ContextCollection Run() { var reflector = new Reflector(this.dll); var finder = new SpecFinder(reflector); var tagsFilter = new Tags().Parse(Tags); var builder = new ContextBuilder(finder, tagsFilter, new DefaultConventions()); var runner = new ContextRunner(tagsFilter, Formatter, failFast); var contexts = builder.Contexts().Build(); if(contexts.AnyTaggedWithFocus()) { tagsFilter = new Tags().Parse(NSpec.Domain.Tags.Focus); builder = new ContextBuilder(finder, tagsFilter, new DefaultConventions()); runner = new ContextRunner(tagsFilter, Formatter, failFast); contexts = builder.Contexts().Build(); } return runner.Run(contexts); } public RunnerInvocation(string dll, string tags) : this(dll, tags, false) {} public RunnerInvocation(string dll, string tags, bool failFast) : this(dll, tags, new ConsoleFormatter(), failFast) {} public RunnerInvocation(string dll, string tags, IFormatter formatter, bool failFast) { this.dll = dll; this.failFast = failFast; Tags = tags; Formatter = formatter; } public string Tags; public IFormatter Formatter; string dll; bool failFast; } }
using System; using NSpec.Domain.Formatters; namespace NSpec.Domain { [Serializable] public class RunnerInvocation { public ContextCollection Run() { var reflector = new Reflector(this.dll); var finder = new SpecFinder(reflector); var tagsFilter = new Tags().Parse(Tags); var builder = new ContextBuilder(finder, tagsFilter, new DefaultConventions()); var runner = new ContextRunner(tagsFilter, Formatter, failFast); var contexts = builder.Contexts().Build(); if(contexts.AnyTaggedWithFocus()) { tagsFilter = new Tags().Parse(NSpec.Domain.Tags.Focus); builder = new ContextBuilder(finder, tagsFilter, new DefaultConventions()); runner = new ContextRunner(tagsFilter, Formatter, failFast); contexts = builder.Contexts().Build(); } return runner.Run(contexts); } public RunnerInvocation(string dll, string tags) : this(dll, tags, false) {} public RunnerInvocation(string dll, string tags, bool failFast) : this(dll, tags, new ConsoleFormatter(), failFast) {} public RunnerInvocation(string dll, string tags, IFormatter formatter, bool failFast) { this.dll = dll; this.failFast = failFast; Tags = tags; Formatter = formatter; } public string Tags; public IFormatter Formatter; public bool inDomain; // TODO it should be removed completely string dll; bool failFast; } }
mit
C#
8b876c76384fcdf4d71f5b094922b99cbe92f8e0
put swagger test into sequential test group
os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos
Tests.Integration.Presentation.Web/Swagger/SwaggerDocumentationTest.cs
Tests.Integration.Presentation.Web/Swagger/SwaggerDocumentationTest.cs
using System.Net; using System.Threading.Tasks; using Tests.Integration.Presentation.Web.Tools; using Tests.Integration.Presentation.Web.Tools.XUnit; using Xunit; namespace Tests.Integration.Presentation.Web.Swagger { [Collection(nameof(SequentialTestGroup))] public class SwaggerDocumentationTest { public class SwaggerDoc { public string Swagger { get; set; } public string Host { get; set; } } [Theory] [InlineData(1)] [InlineData(2)] public async Task Can_Load_Swagger_Doc(int version) { //Arrange var url = TestEnvironment.CreateUrl($"/swagger/docs/{version}"); //Act using var result = await HttpApi.GetAsync(url); //Assert Assert.Equal(HttpStatusCode.OK, result.StatusCode); var doc = await result.ReadResponseBodyAsAsync<SwaggerDoc>(); Assert.Equal("2.0", doc.Swagger); Assert.Equal(url.Authority, doc.Host); } } }
using System.Net; using System.Threading.Tasks; using Tests.Integration.Presentation.Web.Tools; using Xunit; namespace Tests.Integration.Presentation.Web.Swagger { public class SwaggerDocumentationTest { public class SwaggerDoc { public string Swagger { get; set; } public string Host { get; set; } } [Theory] [InlineData(1)] [InlineData(2)] public async Task Can_Load_Swagger_Doc(int version) { //Arrange var url = TestEnvironment.CreateUrl($"/swagger/docs/{version}"); //Act using (var result = await HttpApi.GetAsync(url)) { //Assert Assert.Equal(HttpStatusCode.OK, result.StatusCode); var doc = await result.ReadResponseBodyAsAsync<SwaggerDoc>(); Assert.Equal("2.0", doc.Swagger); Assert.Equal(url.Authority, doc.Host); } } } }
mpl-2.0
C#
18a924c5e4f276cd8bf3e98694c717449387b0f9
clear color for bitmap
Meragon/Unity-WinForms
System/Drawing/Bitmap.cs
System/Drawing/Bitmap.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.Drawing { [Serializable] public class Bitmap : Image { public static implicit operator UnityEngine.Texture2D(Bitmap image) { if (image == null) return null; return image.uTexture; } public static implicit operator Bitmap(UnityEngine.Texture2D text) { return new Bitmap(text); } public Bitmap(UnityEngine.Texture2D original) { Color = Color.White; uTexture = original; } public Bitmap(UnityEngine.Texture2D original, Color color) { Color = color; uTexture = original; } public Bitmap(int width, int height) { Color = Color.White; uTexture = new UnityEngine.Texture2D(width, height); } public void Apply() { uTexture.Apply(); } public void ClearColor(Color c, bool apply = true) { var colors = new UnityEngine.Color32[Width * Height]; for (int i = 0; i < colors.Length; i++) colors[i] = c.ToUColor(); uTexture.SetPixels32(colors); if (apply) Apply(); } public Color GetPixel(int x, int y) { return Color.FromUColor(uTexture.GetPixel(x, uTexture.height - y - 1)); } public Color[] GetPixels(int x, int y, int w, int h) { var ucs = uTexture.GetPixels(x, uTexture.height - y - 1, w, h); Color[] cs = new Color[ucs.Length]; for (int i = 0; i < cs.Length; i++) cs[i] = Color.FromUColor(ucs[i]); return cs; } public void SetPixel(int x, int y, Color color) { uTexture.SetPixel(x, uTexture.height - y - 1, color.ToUColor()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.Drawing { [Serializable] public class Bitmap : Image { public static implicit operator UnityEngine.Texture2D(Bitmap image) { if (image == null) return null; return image.uTexture; } public static implicit operator Bitmap(UnityEngine.Texture2D text) { return new Bitmap(text); } public Bitmap(UnityEngine.Texture2D original) { Color = Color.White; uTexture = original; } public Bitmap(UnityEngine.Texture2D original, Color color) { Color = color; uTexture = original; } public Bitmap(int width, int height) { Color = Color.White; uTexture = new UnityEngine.Texture2D(width, height); } public void Apply() { uTexture.Apply(); } public Color GetPixel(int x, int y) { return Color.FromUColor(uTexture.GetPixel(x, uTexture.height - y - 1)); } public Color[] GetPixels(int x, int y, int w, int h) { var ucs = uTexture.GetPixels(x, uTexture.height - y - 1, w, h); Color[] cs = new Color[ucs.Length]; for (int i = 0; i < cs.Length; i++) cs[i] = Color.FromUColor(ucs[i]); return cs; } public void SetPixel(int x, int y, Color color) { uTexture.SetPixel(x, uTexture.height - y - 1, color.ToUColor()); } } }
mit
C#
6249e33dafa8bf5e9c1a1e044a12d59b75e90314
bump version
raml-org/raml-dotnet-parser,raml-org/raml-dotnet-parser
source/AMF.Parser/Properties/AssemblyInfo.cs
source/AMF.Parser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AMF.Parser")] [assembly: AssemblyDescription("RAML and OAS (swagger) parser for .Net")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MuleSoft")] [assembly: AssemblyProduct("AMF.Parser")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("af24976e-d021-4aa5-b7d7-1de6574cd6f6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.4.0")] [assembly: AssemblyFileVersion("0.9.4.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AMF.Parser")] [assembly: AssemblyDescription("RAML and OAS (swagger) parser for .Net")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MuleSoft")] [assembly: AssemblyProduct("AMF.Parser")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("af24976e-d021-4aa5-b7d7-1de6574cd6f6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.3.0")] [assembly: AssemblyFileVersion("0.9.3.0")]
apache-2.0
C#
d3c7fec81ac153e03da1faafb3d0333e21ac5ed1
Fix readonly property issue.
sdcb/sdmap
sdmap/src/sdmap/Parser/Visitor/CoreSqlVisitor.cs
sdmap/src/sdmap/Parser/Visitor/CoreSqlVisitor.cs
using sdmap.Functional; using sdmap.Parser.Context; using sdmap.Parser.G4; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading.Tasks; using static sdmap.Parser.G4.SdmapParser; using Antlr4.Runtime.Misc; using sdmap.Parser.Utils; namespace sdmap.Parser.Visitor { public class CoreSqlVisitor : SdmapParserBaseVisitor<Result> { private readonly SdmapContext _context; private EmitFunction _function; private ILGenerator _il; private CoreSqlVisitor(SdmapContext context) { _context = context; } public override Result VisitNamedSql([NotNull] NamedSqlContext context) { var openSql = context.GetToken(OpenNamedSql, 0); var id = LexerUtil.GetOpenSqlId(openSql.GetText()); var fullName = _context.GetFullName(id); var method = new DynamicMethod(fullName, typeof(string), new[] { typeof(object) }); _il = method.GetILGenerator(); _function = (EmitFunction)method.CreateDelegate(typeof(EmitFunction)); return Result.Ok(); } public static CoreSqlVisitor Create(SdmapContext context) { return new CoreSqlVisitor(context); } public static Result<EmitFunction> Compile(NamedSqlContext parseTree, SdmapContext context) { var visitor = Create(context); return visitor.Visit(parseTree) .OnSuccess(() => visitor._function); } } }
using sdmap.Functional; using sdmap.Parser.Context; using sdmap.Parser.G4; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading.Tasks; using static sdmap.Parser.G4.SdmapParser; using Antlr4.Runtime.Misc; using sdmap.Parser.Utils; namespace sdmap.Parser.Visitor { public class CoreSqlVisitor : SdmapParserBaseVisitor<Result> { private readonly SdmapContext _context; private EmitFunction _function; private readonly ILGenerator _il; private CoreSqlVisitor(SdmapContext context) { _context = context; } public override Result VisitNamedSql([NotNull] NamedSqlContext context) { var openSql = context.GetToken(OpenNamedSql, 0); var id = LexerUtil.GetOpenSqlId(openSql.GetText()); var fullName = _context.GetFullName(id); var method = new DynamicMethod(fullName, typeof(string), new[] { typeof(object) }); _il = method.GetILGenerator(); _function = (EmitFunction)method.CreateDelegate(typeof(EmitFunction)); return Result.Ok(); } public static CoreSqlVisitor Create(SdmapContext context) { return new CoreSqlVisitor(context); } public static Result<EmitFunction> Compile(NamedSqlContext parseTree, SdmapContext context) { var visitor = Create(context); return visitor.Visit(parseTree) .OnSuccess(() => visitor._function); } } }
mit
C#
f7a78b4ca6e9ec116424e15eaab127b4d8c0b00d
Add ApplicationCommand#ApplicationId property
appharbor/appharbor-cli
src/AppHarbor/Commands/ApplicationCommand.cs
src/AppHarbor/Commands/ApplicationCommand.cs
namespace AppHarbor.Commands { public abstract class ApplicationCommand : Command { private readonly IApplicationConfiguration _applicationConfiguration; public ApplicationCommand(IApplicationConfiguration applicationConfiguration) { _applicationConfiguration = applicationConfiguration; } protected string ApplicationId { get { return _applicationConfiguration.GetApplicationId(); } } } }
namespace AppHarbor.Commands { public abstract class ApplicationCommand : Command { private readonly IApplicationConfiguration _applicationConfiguration; public ApplicationCommand(IApplicationConfiguration applicationConfiguration) { _applicationConfiguration = applicationConfiguration; } } }
mit
C#
fd22b6522de76f1178c4f996838985668aa3a727
Fix type
banguit/fluentfilters
src/FluentFilters/Properties/AssemblyInfo.cs
src/FluentFilters/Properties/AssemblyInfo.cs
#region License // Copyright (c) Dmitry Antonenko (http://hystrix.com.ua) // // 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. // // The latest version of this file can be found at http://fluentfilters.codeplex.com/ #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FluentFilters")] [assembly: AssemblyDescription("Library for ASP.NET Core, that will add support of criteria for global action filters.")] [assembly: AssemblyProduct("FluentFilters")] [assembly: AssemblyCopyright("Copyright (c) Dmytro Antonenko 2016")] // 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("66f9fd49-1e8e-4aba-b0e9-8bd8f64ff61f")]
#region License // Copyright (c) Dmitry Antonenko (http://hystrix.com.ua) // // 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. // // The latest version of this file can be found at http://fluentfilters.codeplex.com/ #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FluentFilters")] [assembly: AssemblyDescription("Library for ASP.NET Core, that will add support of criterias for global action filters.")] [assembly: AssemblyProduct("FluentFilters")] [assembly: AssemblyCopyright("Copyright (c) Dmytro Antonenko Antonenko 2016")] // 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("66f9fd49-1e8e-4aba-b0e9-8bd8f64ff61f")]
apache-2.0
C#
9272ac5a1241b8df409363649736518b6edb247b
Add default constructor to VersionedRoute
infrabel/GNaP.WebApi.Versioning,infrabel/GNaP.WebApi.Versioning
src/GNaP.WebApi.Versioning/VersionedRoute.cs
src/GNaP.WebApi.Versioning/VersionedRoute.cs
namespace GNaP.WebApi.Versioning { using System.Collections.Generic; using System.Web.Http.Routing; public class VersionedRoute : RouteFactoryAttribute { public int Version { get; private set; } public override IDictionary<string, object> Constraints { get { return new HttpRouteValueDictionary { { "version", new VersionConstraint(Version) } }; } } public VersionedRoute() : this(string.Empty) { } public VersionedRoute(string template) : this(template, 1) { } public VersionedRoute(string template, int version) : base(template) { Version = version; } } }
namespace GNaP.WebApi.Versioning { using System.Collections.Generic; using System.Web.Http.Routing; public class VersionedRoute : RouteFactoryAttribute { public int Version { get; private set; } public override IDictionary<string, object> Constraints { get { return new HttpRouteValueDictionary { { "version", new VersionConstraint(Version) } }; } } public VersionedRoute(string template) : this(template, 1) { } public VersionedRoute(string template, int version) : base(template) { Version = version; } } }
bsd-3-clause
C#
dc9775742ca0dfc20f65e9de2d043c714a6f1a61
Fix incorrect code migration
peppy/osu,NeoAdonis/osu,peppy/osu,2yangk23/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu
osu.Game/Rulesets/Mods/ModTimeRamp.cs
osu.Game/Rulesets/Mods/ModTimeRamp.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.Linq; using osu.Framework.Audio.Track; using osu.Game.Beatmaps; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Mods { public abstract class ModTimeRamp : Mod, IUpdatableByPlayfield, IApplicableToTrack, IApplicableToBeatmap { /// <summary> /// The point in the beatmap at which the final ramping rate should be reached. /// </summary> private const double final_rate_progress = 0.75f; public override Type[] IncompatibleMods => new[] { typeof(ModTimeAdjust) }; protected abstract double FinalRateAdjustment { get; } private double finalRateTime; private double beginRampTime; private Track track; public virtual void ApplyToTrack(Track track) { this.track = track; lastAdjust = 1; // for preview purposes. during gameplay, Update will overwrite this setting. applyAdjustment(1); } public virtual void ApplyToBeatmap(IBeatmap beatmap) { HitObject lastObject = beatmap.HitObjects.LastOrDefault(); beginRampTime = beatmap.HitObjects.FirstOrDefault()?.StartTime ?? 0; finalRateTime = final_rate_progress * (lastObject?.GetEndTime() ?? 0); } public virtual void Update(Playfield playfield) { applyAdjustment((track.CurrentTime - beginRampTime) / finalRateTime); } private double lastAdjust = 1; /// <summary> /// Adjust the rate along the specified ramp /// </summary> /// <param name="amount">The amount of adjustment to apply (from 0..1).</param> private void applyAdjustment(double amount) { double adjust = 1 + (Math.Sign(FinalRateAdjustment) * Math.Clamp(amount, 0, 1) * Math.Abs(FinalRateAdjustment)); track.Tempo.Value /= lastAdjust; track.Tempo.Value *= adjust; lastAdjust = adjust; } } }
// 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.Linq; using osu.Framework.Audio.Track; using osu.Game.Beatmaps; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Mods { public abstract class ModTimeRamp : Mod, IUpdatableByPlayfield, IApplicableToTrack, IApplicableToBeatmap { /// <summary> /// The point in the beatmap at which the final ramping rate should be reached. /// </summary> private const double final_rate_progress = 0.75f; public override Type[] IncompatibleMods => new[] { typeof(ModTimeAdjust) }; protected abstract double FinalRateAdjustment { get; } private double finalRateTime; private double beginRampTime; private Track track; public virtual void ApplyToTrack(Track track) { this.track = track; lastAdjust = 1; // for preview purposes. during gameplay, Update will overwrite this setting. applyAdjustment(1); } public virtual void ApplyToBeatmap(IBeatmap beatmap) { HitObject lastObject = beatmap.HitObjects.LastOrDefault(); beginRampTime = beatmap.HitObjects.FirstOrDefault()?.StartTime ?? 0; finalRateTime = final_rate_progress * (lastObject?.GetEndTime() ?? 0); } public virtual void Update(Playfield playfield) { applyAdjustment((track.CurrentTime - beginRampTime) / finalRateTime); } private double lastAdjust = 1; /// <summary> /// Adjust the rate along the specified ramp /// </summary> /// <param name="amount">The amount of adjustment to apply (from 0..1).</param> private void applyAdjustment(double amount) { double adjust = 1 + (Math.Sign(FinalRateAdjustment) * Math.Clamp(amount, 0, 1) * Math.Abs(FinalRateAdjustment)); track.Tempo.Value /= lastAdjust; track.Tempo.Value *= lastAdjust; lastAdjust = adjust; } } }
mit
C#
ec241ae48a8082d7516bfd84fd4e790d20730fea
Add assertion to check for cycles in ExecutionTree
symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix
src/Symbooglix/Executor/ExecutionTreeNode.cs
src/Symbooglix/Executor/ExecutionTreeNode.cs
using System; using System.Collections.Generic; using System.Diagnostics; namespace Symbooglix { public class ExecutionTreeNode { public readonly ExecutionTreeNode Parent; public readonly ProgramLocation CreatedAt; public readonly ExecutionState State; // Should this be a weak reference to allow GC? public readonly int Depth; private List<ExecutionTreeNode> Children; public ExecutionTreeNode(ExecutionState self, ExecutionTreeNode parent, ProgramLocation createdAt) { Debug.Assert(self != null, "self cannot be null!"); this.State = self; if (parent == null) this.Parent = null; else { this.Parent = parent; // Add this as a child of the parent this.Parent.AddChild(this); } this.Depth = self.ExplicitBranchDepth; this.CreatedAt = createdAt; Children = new List<ExecutionTreeNode>(); // Should we lazily create this? } public ExecutionTreeNode GetChild(int index) { return Children[index]; } public int ChildrenCount { get { return Children.Count; } } public void AddChild(ExecutionTreeNode node) { Debug.Assert(node != null, "Child cannot be null"); Debug.Assert(node != this, "Cannot have cycles"); Children.Add(node); } public override string ToString() { return string.Format ("[{0}.{1}]", State.Id, State.ExplicitBranchDepth); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Symbooglix { public class ExecutionTreeNode { public readonly ExecutionTreeNode Parent; public readonly ProgramLocation CreatedAt; public readonly ExecutionState State; // Should this be a weak reference to allow GC? public readonly int Depth; private List<ExecutionTreeNode> Children; public ExecutionTreeNode(ExecutionState self, ExecutionTreeNode parent, ProgramLocation createdAt) { Debug.Assert(self != null, "self cannot be null!"); this.State = self; if (parent == null) this.Parent = null; else { this.Parent = parent; // Add this as a child of the parent this.Parent.AddChild(this); } this.Depth = self.ExplicitBranchDepth; this.CreatedAt = createdAt; Children = new List<ExecutionTreeNode>(); // Should we lazily create this? } public ExecutionTreeNode GetChild(int index) { return Children[index]; } public int ChildrenCount { get { return Children.Count; } } public void AddChild(ExecutionTreeNode node) { Debug.Assert(node != null, "Child cannot be null"); Children.Add(node); } public override string ToString() { return string.Format ("[{0}.{1}]", State.Id, State.ExplicitBranchDepth); } } }
bsd-2-clause
C#
0557a3a3b3c9d9ea5353ea869f9e17e333b39910
Remove unnecessary constructor
proyecto26/RestClient
src/Proyecto26.RestClient/Utils/RequestHelper.cs
src/Proyecto26.RestClient/Utils/RequestHelper.cs
using System; using UnityEngine; using System.Collections.Generic; using UnityEngine.Networking; namespace Proyecto26 { public class RequestHelper { public string url; public int? timeout; private Dictionary<string, string> _headers; public Dictionary<string, string> headers { get { if (_headers == null) { _headers = new Dictionary<string, string>(); } return _headers; } set { _headers = value; } } public float uploadProgress { get { float progress = 0; if(this.request != null){ progress = this.request.uploadProgress; } return progress; } } public float downloadProgress { get { float progress = 0; if (this.request != null) { progress = this.request.downloadProgress; } return progress; } } public string GetHeader(string name){ string headerValue; if(request != null) { headerValue = request.GetRequestHeader(name); } else { this.headers.TryGetValue(name, out headerValue); } return headerValue; } /// <summary> /// Internal use /// </summary> public UnityWebRequest request { private get; set; } } }
using System; using UnityEngine; using System.Collections.Generic; using UnityEngine.Networking; namespace Proyecto26 { public class RequestHelper { public RequestHelper() { headers = new Dictionary<string, string>(); } public string url; public int? timeout; private Dictionary<string, string> _headers; public Dictionary<string, string> headers { get { if (_headers == null) { _headers = new Dictionary<string, string>(); } return _headers; } set { _headers = value; } } public float uploadProgress { get { float progress = 0; if(this.request != null){ progress = this.request.uploadProgress; } return progress; } } public float downloadProgress { get { float progress = 0; if (this.request != null) { progress = this.request.downloadProgress; } return progress; } } public string GetHeader(string name){ string headerValue; if(request != null) { headerValue = request.GetRequestHeader(name); } else { this.headers.TryGetValue(name, out headerValue); } return headerValue; } /// <summary> /// Internal use /// </summary> public UnityWebRequest request { private get; set; } } }
mit
C#
0694e17b3edc903b41ce886e4d335e3ee1e598f1
Fix header for table
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
BatteryCommander.Web/Views/Soldier/Bulk.cshtml
BatteryCommander.Web/Views/Soldier/Bulk.cshtml
@model IEnumerable<BatteryCommander.Web.Models.SoldierEditModel> @{ ViewBag.Title = "Bulk Add/Edit"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm("Bulk", "Soldier", FormMethod.Post)) { <div class="form-horizontal"> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.AntiForgeryToken() <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Id)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Status)</th> </tr> </thead> <tbody> @Html.EditorForModel() </tbody> </table> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> }
@model IEnumerable<BatteryCommander.Web.Models.SoldierEditModel> @{ ViewBag.Title = "Bulk Add/Edit"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm("Bulk", "Soldier", FormMethod.Post)) { <div class="form-horizontal"> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.AntiForgeryToken() <table> <thead> <tr>@Html.DisplayNameFor(s => s.FirstOrDefault().Id)</tr> <tr>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</tr> <tr>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</tr> <tr>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</tr> <tr>@Html.DisplayNameFor(s => s.FirstOrDefault().Status)</tr> </thead> <tbody> @Html.EditorForModel() </tbody> </table> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> }
mit
C#
6c88ccc73e9adeae0a4b813ae2f3f6f2a9ff4407
Bump version
beekmanlabs/Storage,beekmanlabs/Storage
BeekmanLabs.Storage/Properties/AssemblyInfo.cs
BeekmanLabs.Storage/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.0.2.*")] [assembly: AssemblyInformationalVersion("0.0.2")] [assembly: AssemblyTitle("BeekmanLabs.Storage")] [assembly: AssemblyCompany("Beekman Labs")] [assembly: AssemblyProduct("BeekmanLabs.Storage")] [assembly: AssemblyCopyright("Copyright © Beekman Labs 2015")] [assembly: ComVisible(false)] [assembly: Guid("f054b802-3240-4884-ae74-d1b7c0f34af8")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.0.1.*")] [assembly: AssemblyInformationalVersion("0.0.1")] [assembly: AssemblyTitle("BeekmanLabs.Storage")] [assembly: AssemblyCompany("Beekman Labs")] [assembly: AssemblyProduct("BeekmanLabs.Storage")] [assembly: AssemblyCopyright("Copyright © Beekman Labs 2015")] [assembly: ComVisible(false)] [assembly: Guid("f054b802-3240-4884-ae74-d1b7c0f34af8")]
mit
C#
49a3685e27c985d0a2cbbff8b80b84bdf2165055
Use dictionary instead of lists
ozim/CakeStuff
ReverseWords/BracesValidator/BracesValidator.cs
ReverseWords/BracesValidator/BracesValidator.cs
namespace BracesValidator { using System.Collections.Generic; public class BracesValidator { public bool Validate(string code) { char[] codeArray = code.ToCharArray(); Dictionary<char, char> openersClosersMap = new Dictionary<char, char>(); openersClosersMap.Add('{', '}'); openersClosersMap.Add('[', ']'); openersClosersMap.Add('(', ')'); Stack<char> parensStack = new Stack<char>(); int braceCounter = 0; for (int i = 0; i < codeArray.Length; i++) { if(openersClosersMap.ContainsKey(codeArray[i])) { parensStack.Push(codeArray[i]); } if(openersClosersMap.ContainsValue(codeArray[i])) { var current = parensStack.Pop(); if(openersClosersMap[current] != codeArray[i]) { return false; } } } return parensStack.Count == 0; } } }
namespace BracesValidator { using System.Collections.Generic; public class BracesValidator { public bool Validate(string code) { char[] codeArray = code.ToCharArray(); List<char> openers = new List<char> { '{', '[', '(' }; List<char> closers = new List<char> { '}', ']', ')' }; Stack<char> parensStack = new Stack<char>(); int braceCounter = 0; for (int i = 0; i < codeArray.Length; i++) { if(openers.Contains(codeArray[i])) { parensStack.Push(codeArray[i]); } if(closers.Contains(codeArray[i])) { var current = parensStack.Pop(); if(openers.IndexOf(current) != closers.IndexOf(codeArray[i])) { return false; } } } return parensStack.Count == 0; } } }
apache-2.0
C#
0cd5fde8061aa7cea98c6847ad2312fe4f14f9a7
handle CompareValues for RowListField type
WasimAhmad/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,dfaruque/Serenity,dfaruque/Serenity,WasimAhmad/Serenity
Serenity.Data.Entity/FieldTypes/RowListField.cs
Serenity.Data.Entity/FieldTypes/RowListField.cs
using System; using System.Collections.Generic; namespace Serenity.Data { public class RowListField<TForeign> : CustomClassField<List<TForeign>> where TForeign: Row { public RowListField(ICollection<Field> collection, string name, LocalText caption = null, int size = 0, FieldFlags flags = FieldFlags.Default, Func<Row, List<TForeign>> getValue = null, Action<Row, List<TForeign>> setValue = null) : base(collection, name, caption, size, flags, getValue, setValue) { } protected override int CompareValues(List<TForeign> value1, List<TForeign> value2) { if (value1 == null && value2 == null) return 0; if (value1 == null) return -1; if (value2 == null) return 1; if (value1.Count != value2.Count) return value1.Count.CompareTo(value2.Count); for (var i = 0; i < value1.Count; i++) { var v1 = value1[i]; var v2 = value2[i]; if (v1 == null && v2 == null) continue; if (v1 == null) return -1; if (v2 == null) return 1; foreach (var f in v1.GetFields()) { var c = f.IndexCompare(v1, v2); if (c != 0) return c; } } return 0; } protected override List<TForeign> Clone(List<TForeign> value) { var clone = new List<TForeign>(); foreach (var row in value) clone.Add(row.Clone()); return clone; } } }
using System; using System.Collections.Generic; namespace Serenity.Data { public class RowListField<TForeign> : CustomClassField<List<TForeign>> where TForeign: Row { public RowListField(ICollection<Field> collection, string name, LocalText caption = null, int size = 0, FieldFlags flags = FieldFlags.Default, Func<Row, List<TForeign>> getValue = null, Action<Row, List<TForeign>> setValue = null) : base(collection, name, caption, size, flags, getValue, setValue) { } protected override int CompareValues(List<TForeign> value1, List<TForeign> value2) { throw new NotImplementedException(); } protected override List<TForeign> Clone(List<TForeign> value) { var clone = new List<TForeign>(); foreach (var row in value) clone.Add(row.Clone()); return clone; } } }
mit
C#
41daadc7afa6fd39e39851b1d0ef7f1aebe2411d
Sort usings
projecteon/thecollection,projecteon/thecollection,projecteon/thecollection,projecteon/thecollection
TheCollection.Web/Commands/SearchBagsCommand.cs
TheCollection.Web/Commands/SearchBagsCommand.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.Documents; using System.Linq; using System.Threading.Tasks; using TheCollection.Business.Tea; using TheCollection.Web.Constants; using TheCollection.Web.Extensions; using TheCollection.Web.Models; using TheCollection.Web.Services; namespace TheCollection.Web.Commands { public class SearchBagsCommand : IAsyncCommand<Search> { private readonly IDocumentClient documentDbClient; public SearchBagsCommand(IDocumentClient documentDbClient) { this.documentDbClient = documentDbClient; } public async Task<IActionResult> ExecuteAsync(Search search) { if (search.searchterm.IsNullOrWhiteSpace()) { return new BadRequestResult(); } var bagsRepository = new SearchRepository<Bag>(documentDbClient, DocumentDB.DatabaseId, DocumentDB.BagsCollectionId); var bags = await bagsRepository.SearchAsync(search.searchterm, search.pagesize); var result = new SearchResult<Bag> { count = await bagsRepository.SearchRowCountAsync(search.searchterm), data = bags.OrderBy(bag => bag.Brand.Name) .ThenBy(bag => bag.Hallmark) .ThenBy(bag => bag.Serie) .ThenBy(bag => bag.BagType?.Name) .ThenBy(bag => bag.Flavour) }; return new OkObjectResult(result); } } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.Documents; using TheCollection.Web.Constants; using TheCollection.Business.Tea; using TheCollection.Web.Services; using System.Linq; using TheCollection.Web.Models; using TheCollection.Web.Extensions; namespace TheCollection.Web.Commands { public class SearchBagsCommand : IAsyncCommand<Search> { private readonly IDocumentClient documentDbClient; public SearchBagsCommand(IDocumentClient documentDbClient) { this.documentDbClient = documentDbClient; } public async Task<IActionResult> ExecuteAsync(Search search) { if (search.searchterm.IsNullOrWhiteSpace()) { return new BadRequestResult(); } var bagsRepository = new SearchRepository<Bag>(documentDbClient, DocumentDB.DatabaseId, DocumentDB.BagsCollectionId); var bags = await bagsRepository.SearchAsync(search.searchterm, search.pagesize); var result = new SearchResult<Bag> { count = await bagsRepository.SearchRowCountAsync(search.searchterm), data = bags.OrderBy(bag => bag.Brand.Name) .ThenBy(bag => bag.Hallmark) .ThenBy(bag => bag.Serie) .ThenBy(bag => bag.BagType?.Name) .ThenBy(bag => bag.Flavour) }; return new OkObjectResult(result); } } }
apache-2.0
C#
5caa7920629419327460d12745fd60a8c6c928ba
Add comment.
Microsoft/xunit-performance,ericeil/xunit-performance,ianhays/xunit-performance,visia/xunit-performance,mmitche/xunit-performance,Microsoft/xunit-performance,pharring/xunit-performance
src/xunit.performance.analysis/MathExtensions.cs
src/xunit.performance.analysis/MathExtensions.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MathNet.Numerics; using MathNet.Numerics.Statistics; using System; using System.Collections.Generic; namespace Microsoft.Xunit.Performance.Analysis { public static class MathExtensions { /// <summary> /// Calculates a confidence interval as a percentage of the mean /// </summary> /// <remarks> /// This assumes a roughly normal distribution in the sample data. /// </remarks> /// <param name="stats">A <see cref="RunningStatistics"/> object pre-populated with the sample data.</param> /// <param name="confidence">The desired confidence in the resulting interval.</param> /// <returns>The confidence interval, as a percentage of the mean.</returns> public static double MarginOfError(this RunningStatistics stats, double confidence) { if (stats.Count < 2) return double.NaN; var stderr = stats.StandardDeviation / Math.Sqrt(stats.Count); var t = TInv(1.0 - confidence, (int)stats.Count - 1); var mean = stats.Mean; var interval = t * stderr; return interval / mean; } [ThreadStatic] private static Dictionary<double, Dictionary<int, double>> t_TInvCache = new Dictionary<double, Dictionary<int, double>>(); private static double TInv(double probability, int degreesOfFreedom) { Dictionary<int, double> dofCache; if (!t_TInvCache.TryGetValue(probability, out dofCache)) t_TInvCache[probability] = dofCache = new Dictionary<int, double>(); double result; if (!dofCache.TryGetValue(degreesOfFreedom, out result)) dofCache[degreesOfFreedom] = result = ExcelFunctions.TInv(probability, degreesOfFreedom); return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MathNet.Numerics; using MathNet.Numerics.Statistics; using System; using System.Collections.Generic; namespace Microsoft.Xunit.Performance.Analysis { public static class MathExtensions { public static double MarginOfError(this RunningStatistics stats, double confidence) { if (stats.Count < 2) return double.NaN; var stderr = stats.StandardDeviation / Math.Sqrt(stats.Count); var t = TInv(1.0 - confidence, (int)stats.Count - 1); var mean = stats.Mean; var interval = t * stderr; return interval / mean; } [ThreadStatic] private static Dictionary<double, Dictionary<int, double>> t_TInvCache = new Dictionary<double, Dictionary<int, double>>(); private static double TInv(double probability, int degreesOfFreedom) { Dictionary<int, double> dofCache; if (!t_TInvCache.TryGetValue(probability, out dofCache)) t_TInvCache[probability] = dofCache = new Dictionary<int, double>(); double result; if (!dofCache.TryGetValue(degreesOfFreedom, out result)) dofCache[degreesOfFreedom] = result = ExcelFunctions.TInv(probability, degreesOfFreedom); return result; } } }
mit
C#
1635197d94ae9f2f18aac8d07914e0374840450f
Implement ExecuteInstructionFromConsole() in Main
vejuhust/msft-scooter
ScooterController/ScooterController/Program.cs
ScooterController/ScooterController/Program.cs
using System; namespace ScooterController { class Program { private static void ExecuteInstructionFromFile(string filename) { var parser = new InstructionInterpreter(filename); var controller = new HardwareController(); HardwareInstruction instruction; while ((instruction = parser.GetNextInstruction()) != null) { Console.WriteLine("\n[{0}{1}]", instruction.Operator, instruction.HasOperand ? " " + instruction.Operand : string.Empty); if (instruction.Operator == HardwareOperator.NoOp || instruction.Operator == HardwareOperator.Exit) { break; } else { controller.ExecuteInstruction(instruction); } } } private static void ExecuteInstructionFromConsole() { Console.WriteLine("Welcome to Scooter Console!"); var instructionCounter = 0; var parser = new InstructionInterpreter(); var controller = new HardwareController(); while (true) { instructionCounter++; Console.Write("\n>>{0:D4}>>> ", instructionCounter); var inputLine = Console.ReadLine(); var instruction = parser.InterpretRawLine(inputLine, true); if (instruction == null) { Console.WriteLine("[Invalid Instruction]"); } else { Console.WriteLine("[{0}{1}]", instruction.Operator, instruction.HasOperand ? " " + instruction.Operand : string.Empty); if (instruction.Operator == HardwareOperator.NoOp || instruction.Operator == HardwareOperator.Exit) { break; } else { controller.ExecuteInstruction(instruction); } } } } static void Main(string[] args) { if (args.Length >= 1) { ExecuteInstructionFromFile(args[0]); } else { ExecuteInstructionFromConsole(); } } } }
using System; namespace ScooterController { class Program { private static void ExecuteInstructionFromFile(string filename) { var parser = new InstructionInterpreter(filename); var controller = new HardwareController(); HardwareInstruction instruction; while ((instruction = parser.GetNextInstruction()) != null) { Console.WriteLine("\n[{0}{1}]", instruction.Operator, instruction.HasOperand ? " " + instruction.Operand : string.Empty); if (instruction.Operator == HardwareOperator.NoOp || instruction.Operator == HardwareOperator.Exit) { break; } controller.ExecuteInstruction(instruction); } } static void Main(string[] args) { if (args.Length >= 1) { ExecuteInstructionFromFile(args[0]); } } } }
mit
C#
6d15dcf1ca4a9f34d7d70dd6de08fde11b0a6cdd
Use TryAdd for ISessionStore service #2755
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Session/SessionServiceCollectionExtensions.cs
src/Microsoft.AspNetCore.Session/SessionServiceCollectionExtensions.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Session; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding session services to the DI container. /// </summary> public static class SessionServiceCollectionExtensions { /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.TryAddTransient<ISessionStore, DistributedSessionStore>(); services.AddDataProtection(); return services; } /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <param name="configure">The session options to configure the middleware with.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services, Action<SessionOptions> configure) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } services.Configure(configure); services.AddSession(); return services; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Session; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding session services to the DI container. /// </summary> public static class SessionServiceCollectionExtensions { /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddTransient<ISessionStore, DistributedSessionStore>(); services.AddDataProtection(); return services; } /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <param name="configure">The session options to configure the middleware with.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services, Action<SessionOptions> configure) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } services.Configure(configure); services.AddSession(); return services; } } }
apache-2.0
C#
0acc010734b7e64a8b0b2a562d19a4d540473f5a
Change FileParsingBenchmark to use parsing defaults (#308)
sebastienros/esprima-dotnet,sebastienros/esprima-dotnet
samples/Esprima.Benchmark/FileParsingBenchmark.cs
samples/Esprima.Benchmark/FileParsingBenchmark.cs
using System.Collections.Generic; using System.IO; using System.Linq; using BenchmarkDotNet.Attributes; namespace Esprima.Benchmark; [MemoryDiagnoser] public class FileParsingBenchmark { private static readonly Dictionary<string, string> files = new() { { "underscore-1.5.2", null }, { "backbone-1.1.0", null }, { "mootools-1.4.5", null }, { "jquery-1.9.1", null }, { "yui-3.12.0", null }, { "jquery.mobile-1.4.2", null }, { "angular-1.2.5", null } }; [GlobalSetup] public void Setup() { foreach (var fileName in files.Keys.ToList()) { files[fileName] = File.ReadAllText($"3rdparty/{fileName}.js"); } } [ParamsSource(nameof(FileNames))] public string FileName { get; set; } public IEnumerable<string> FileNames() { foreach (var entry in files) { yield return entry.Key; } } [Benchmark] public void ParseProgram() { var parser = new JavaScriptParser(files[FileName]); parser.ParseScript(); } }
using System.Collections.Generic; using System.IO; using System.Linq; using BenchmarkDotNet.Attributes; namespace Esprima.Benchmark; [MemoryDiagnoser] public class FileParsingBenchmark { private static readonly Dictionary<string, string> files = new() { { "underscore-1.5.2", null }, { "backbone-1.1.0", null }, { "mootools-1.4.5", null }, { "jquery-1.9.1", null }, { "yui-3.12.0", null }, { "jquery.mobile-1.4.2", null }, { "angular-1.2.5", null } }; private static readonly ParserOptions parserOptions = new() { Comment = true, Tokens = true }; [GlobalSetup] public void Setup() { foreach (var fileName in files.Keys.ToList()) { files[fileName] = File.ReadAllText($"3rdparty/{fileName}.js"); } } [ParamsSource(nameof(FileNames))] public string FileName { get; set; } public IEnumerable<string> FileNames() { foreach (var entry in files) { yield return entry.Key; } } [Benchmark] public void ParseProgram() { var parser = new JavaScriptParser(files[FileName], parserOptions); parser.ParseScript(); } }
bsd-3-clause
C#
51f447a5f2594a56c20988f1a57dc1f6dd51d380
Remove warnings from Ably log to reduce noise.
StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis
service/DotNetApis.Common/AsyncLocalAblyLogger.cs
service/DotNetApis.Common/AsyncLocalAblyLogger.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using DotNetApis.Common.Internals; using Microsoft.Extensions.Logging; namespace DotNetApis.Common { /// <summary> /// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created. /// </summary> public sealed class AsyncLocalAblyLogger : ILogger { private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>(); public static void TryCreate(string channelName, ILogger logger) { try { ImplicitChannel.Value = AblyService.CreateLogChannel(channelName); } catch (Exception ex) { logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message); } } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (IsEnabled(logLevel)) ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception)); } public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel >= LogLevel.Information && logLevel != LogLevel.Warning; public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using DotNetApis.Common.Internals; using Microsoft.Extensions.Logging; namespace DotNetApis.Common { /// <summary> /// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created. /// </summary> public sealed class AsyncLocalAblyLogger : ILogger { private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>(); public static void TryCreate(string channelName, ILogger logger) { try { ImplicitChannel.Value = AblyService.CreateLogChannel(channelName); } catch (Exception ex) { logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message); } } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (IsEnabled(logLevel)) ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception)); } public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel >= LogLevel.Information; public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException(); } }
mit
C#
14e22810e7c386e9ab0a31492295e8e3e72ae056
fix for max wild level when creating test creatures
cadon/ARKStatsExtractor
ARKBreedingStats/library/AddDummyCreaturesSettings.cs
ARKBreedingStats/library/AddDummyCreaturesSettings.cs
using System; using System.Windows.Forms; namespace ARKBreedingStats.library { public partial class AddDummyCreaturesSettings : Form { public AddDummyCreaturesSettings() { InitializeComponent(); var settings = DummyCreatures.LastSettings != null ? DummyCreatures.LastSettings : new DummyCreatureCreationSettings(); NudAmount.ValueSave = settings.CreatureCount; if (settings.OnlySelectedSpecies) RbOnlySelectedSpecies.Checked = true; else RbMultipleRandomSpecies.Checked = true; NudSpeciesAmount.ValueSave = settings.SpeciesCount; NudBreedForGenerations.ValueSave = settings.Generations; NudUsePairsPerGeneration.ValueSave = settings.PairsPerGeneration; NudProbabilityInheritingHigherStat.ValueSaveDouble = settings.ProbabilityHigherStat * 100; NudMutationChance.ValueSaveDouble = settings.RandomMutationChance * 100; nudMaxWildLevel.ValueSave = settings.MaxWildLevel; } private void BtCancel_Click(object sender, EventArgs e) { Close(); } private void BtOk_Click(object sender, EventArgs e) { if (NudAmount.Value > 0) { DialogResult = DialogResult.OK; Settings = new DummyCreatureCreationSettings { CreatureCount = (int)NudAmount.Value, OnlySelectedSpecies = RbOnlySelectedSpecies.Checked, SpeciesCount = (int)NudSpeciesAmount.Value, Generations = (int)NudBreedForGenerations.Value, PairsPerGeneration = (int)NudUsePairsPerGeneration.Value, ProbabilityHigherStat = (double)NudProbabilityInheritingHigherStat.Value / 100, RandomMutationChance = (double)NudMutationChance.Value / 100, MaxWildLevel = (int)nudMaxWildLevel.Value }; } Close(); } public DummyCreatureCreationSettings Settings; } }
using System; using System.Windows.Forms; namespace ARKBreedingStats.library { public partial class AddDummyCreaturesSettings : Form { public AddDummyCreaturesSettings() { InitializeComponent(); var settings = DummyCreatures.LastSettings != null ? DummyCreatures.LastSettings : new DummyCreatureCreationSettings(); NudAmount.ValueSave = settings.CreatureCount; if (settings.OnlySelectedSpecies) RbOnlySelectedSpecies.Checked = true; else RbMultipleRandomSpecies.Checked = true; NudSpeciesAmount.ValueSave = settings.SpeciesCount; NudBreedForGenerations.ValueSave = settings.Generations; NudUsePairsPerGeneration.ValueSave = settings.PairsPerGeneration; NudProbabilityInheritingHigherStat.ValueSaveDouble = settings.ProbabilityHigherStat * 100; NudMutationChance.ValueSaveDouble = settings.RandomMutationChance * 100; nudMaxWildLevel.ValueSave = settings.MaxWildLevel; } private void BtCancel_Click(object sender, EventArgs e) { Close(); } private void BtOk_Click(object sender, EventArgs e) { if (NudAmount.Value > 0) { DialogResult = DialogResult.OK; Settings = new DummyCreatureCreationSettings { CreatureCount = (int)NudAmount.Value, OnlySelectedSpecies = RbOnlySelectedSpecies.Checked, SpeciesCount = (int)NudSpeciesAmount.Value, Generations = (int)NudBreedForGenerations.Value, PairsPerGeneration = (int)NudUsePairsPerGeneration.Value, ProbabilityHigherStat = (double)NudProbabilityInheritingHigherStat.Value / 100, RandomMutationChance = (double)NudMutationChance.Value / 100 }; } Close(); } public DummyCreatureCreationSettings Settings; } }
mit
C#
84c00bdbb63df193e1e956e7d634de5cdfb68d22
Test against test data
stofte/ream-query
test/ReamQuery.Test/QueryTemplateEndpoint.cs
test/ReamQuery.Test/QueryTemplateEndpoint.cs
namespace ReamQuery.Test { using System; using Xunit; using System.Linq; using ReamQuery.Models; using System.Net.Http; using Newtonsoft.Json; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; public class QueryTemplateEndpoint : E2EBase { [Theory, MemberData("Connections")] [Trait("Category", "Integration")] public async void Querytemplate_Returns_Expected_Template_For_Database(string connectionString, DatabaseProviderType dbType) { var ns = "ns"; var request = new QueryInput { ServerType = dbType, ConnectionString = connectionString, Namespace = ns, Text = "" }; var json = JsonConvert.SerializeObject(request); var res = await _client.PostAsync("/querytemplate", new StringContent(json)); var jsonRes = await res.Content.ReadAsStringAsync(); var output = JsonConvert.DeserializeObject<TemplateResult>(jsonRes); var nodes = CSharpSyntaxTree.ParseText(output.Template).GetRoot().DescendantNodes(); Assert.Single(nodes.OfType<ClassDeclarationSyntax>(), cls => { return cls.Identifier.ToString() == SqlData[0][1].ToString(); }); } } }
namespace ReamQuery.Test { using System; using Xunit; using System.Linq; using ReamQuery.Models; using System.Net.Http; using Newtonsoft.Json; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; public class QueryTemplateEndpoint : E2EBase { [Theory, MemberData("Connections")] [Trait("Category", "Integration")] public async void Querytemplate_Returns_Expected_Template_For_Database(string connectionString, DatabaseProviderType dbType) { var ns = "ns"; var request = new QueryInput { ServerType = dbType, ConnectionString = connectionString, Namespace = ns, Text = "" }; var json = JsonConvert.SerializeObject(request); var res = await _client.PostAsync("/querytemplate", new StringContent(json)); var jsonRes = await res.Content.ReadAsStringAsync(); var output = JsonConvert.DeserializeObject<TemplateResult>(jsonRes); var nodes = CSharpSyntaxTree.ParseText(output.Template).GetRoot().DescendantNodes(); Assert.Single(nodes.OfType<ClassDeclarationSyntax>(), cls => { return cls.Identifier.ToString() == "Foo"; }); } } }
mit
C#
b3c52aaa296db6bf9928cd09dca75dbdda7dac72
add hover text for player totem on the game board
pseale/monopoly-dotnet,pseale/monopoly-dotnet
src/MonopolyDotNet/MonopolyWeb/Views/Game/Index.cshtml
src/MonopolyDotNet/MonopolyWeb/Views/Game/Index.cshtml
@model MonopolyWeb.Models.ViewModels.GameStatusViewModel @using Microsoft.Web.Mvc @using MonopolyWeb.Controllers @{ ViewBag.Title = "Your turn"; } @section styles { <style> .monopoly-board { height: 720px; width: 720px; background-image: url('@Url.Content("~/img/board.png")'); background-position: center center; position: relative; } .player-card { height: 160px; } .player-card h4 { height: 40px; } .holdings { width: 180px; } img.player-icon { float: left; padding: 3px; } img.player-totem { float: right; vertical-align: bottom; } @foreach (var player in Model.PlayerStatuses) { <text> img#player-@(player.PlayerNumber) { position: absolute; left: @(player.OffsetFromLeft)px; top: @(player.OffsetFromTop)px; }</text> } </style> } <div class="monopoly-board span9"> @foreach (var player in Model.PlayerStatuses) { <img class="player-totem" id="player-@(player.PlayerNumber)" src="~/img/@(player.TotemIcon)" alt="Player @(player.PlayerNumber): @(player.Name)" title="Player @(player.PlayerNumber): @(player.Name)" /> } </div> @foreach (var player in Model.PlayerStatuses) { <div class="player-card span3" id="player-@(player.PlayerNumber)"> <img class="player-icon" src="~/img/@(@player.Icon)" /> <h4>@player.Name</h4> <div class="cash">@player.Cash</div> @(Html.ListBoxFor(x => x.PlayerStatuses[0].Holdings, player.Holdings, new { @class = "holdings" })) </div> } <div class="span3"> @if (Model.CanRoll) { using (Html.BeginForm<GameController>(x => x.Roll())) { <input class="btn btn-large" type="submit" value="Roll" /> } } @if (Model.CanBuyProperty) { using (Html.BeginForm<GameController>(x => x.BuyProperty())) { <input class="btn btn-large" type="submit" value="Buy (@(Model.PropertySalePrice))" /> } } @if (Model.CanEndTurn) { using (Html.BeginForm<GameController>(x => x.EndTurn())) { <input class="btn btn-large" type="submit" value="End Turn" /> } } </div>
@model MonopolyWeb.Models.ViewModels.GameStatusViewModel @using Microsoft.Web.Mvc @using MonopolyWeb.Controllers @{ ViewBag.Title = "Your turn"; } @section styles { <style> .monopoly-board { height: 720px; width: 720px; background-image: url('@Url.Content("~/img/board.png")'); background-position: center center; position: relative; } .player-card { height: 160px; } .player-card h4 { height: 40px; } .holdings { width: 180px; } img.player-icon { float: left; padding: 3px; } img.player-totem { float: right; vertical-align: bottom; } @foreach (var player in Model.PlayerStatuses) { <text> img#player-@(player.PlayerNumber) { position: absolute; left: @(player.OffsetFromLeft)px; top: @(player.OffsetFromTop)px; }</text> } </style> } <div class="monopoly-board span9"> @foreach (var player in Model.PlayerStatuses) { <img class="player-totem" id="player-@(player.PlayerNumber)" src="~/img/@(player.TotemIcon)" /> } </div> @foreach (var player in Model.PlayerStatuses) { <div class="player-card span3" id="player-@(player.PlayerNumber)"> <img class="player-icon" src="~/img/@(@player.Icon)" /> <h4>@player.Name</h4> <div class="cash">@player.Cash</div> @(Html.ListBoxFor(x => x.PlayerStatuses[0].Holdings, player.Holdings, new { @class = "holdings" })) </div> } <div class="span3"> @if (Model.CanRoll) { using (Html.BeginForm<GameController>(x => x.Roll())) { <input class="btn btn-large" type="submit" value="Roll" /> } } @if (Model.CanBuyProperty) { using (Html.BeginForm<GameController>(x => x.BuyProperty())) { <input class="btn btn-large" type="submit" value="Buy (@(Model.PropertySalePrice))" /> } } @if (Model.CanEndTurn) { using (Html.BeginForm<GameController>(x => x.EndTurn())) { <input class="btn btn-large" type="submit" value="End Turn" /> } } </div>
mit
C#
dcb8688154edb3b58f2f41e7a5107c671f496c81
Remove excessive debug messages
mono/dbus-sharp-glib,mono/dbus-sharp-glib
glib/GLib.cs
glib/GLib.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; //using GLib; //using Gtk; using NDesk.DBus; using NDesk.GLib; using org.freedesktop.DBus; namespace NDesk.DBus { //FIXME: this API needs review and de-unixification public static class DApplication { public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data) { //Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition); connection.Iterate (); //Console.Error.WriteLine ("Dispatch done"); return true; } public static Connection Connection { get { return connection; } } static Connection connection; static Bus bus; public static void Init () { connection = new Connection (); //ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); //string name = "org.freedesktop.DBus"; /* bus = connection.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.Error.WriteLine ("NameAcquired: " + acquired_name); }; string myName = bus.Hello (); Console.Error.WriteLine ("myName: " + myName); */ IO.AddWatch ((int)connection.sock.Handle, Dispatch); } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; //using GLib; //using Gtk; using NDesk.DBus; using NDesk.GLib; using org.freedesktop.DBus; namespace NDesk.DBus { public static class DApplication { public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data) { Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition); connection.Iterate (); Console.Error.WriteLine ("Dispatch done"); return true; } public static Connection Connection { get { return connection; } } static Connection connection; static Bus bus; public static void Init () { connection = new Connection (); //ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); //string name = "org.freedesktop.DBus"; /* bus = connection.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.Error.WriteLine ("NameAcquired: " + acquired_name); }; string myName = bus.Hello (); Console.Error.WriteLine ("myName: " + myName); */ IO.AddWatch ((int)connection.sock.Handle, Dispatch); } } }
mit
C#
9bc96d2bbf17e574c9563ee8a71d928cf6a2951e
Make sure we only ever initialize once
mono/dbus-sharp-glib,mono/dbus-sharp-glib
glib/GLib.cs
glib/GLib.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; //using GLib; //using Gtk; using NDesk.DBus; using NDesk.GLib; using org.freedesktop.DBus; namespace NDesk.DBus { //FIXME: this API needs review and de-unixification. It is horrid, but gets the job done. public static class BusG { static bool SystemDispatch (IOChannel source, IOCondition condition, IntPtr data) { Bus.System.Iterate (); return true; } static bool SessionDispatch (IOChannel source, IOCondition condition, IntPtr data) { Bus.Session.Iterate (); return true; } static bool initialized = false; public static void Init () { if (initialized) return; Init (Bus.System, SystemDispatch); Init (Bus.Session, SessionDispatch); initialized = true; } public static void Init (Connection conn, IOFunc dispatchHandler) { IOChannel channel = new IOChannel ((int)conn.SocketHandle); IO.AddWatch (channel, IOCondition.In, dispatchHandler); } //TODO: add public API to watch an arbitrary connection } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; //using GLib; //using Gtk; using NDesk.DBus; using NDesk.GLib; using org.freedesktop.DBus; namespace NDesk.DBus { //FIXME: this API needs review and de-unixification. It is horrid, but gets the job done. public static class BusG { static bool SystemDispatch (IOChannel source, IOCondition condition, IntPtr data) { Bus.System.Iterate (); return true; } static bool SessionDispatch (IOChannel source, IOCondition condition, IntPtr data) { Bus.Session.Iterate (); return true; } public static void Init () { Init (Bus.System, SystemDispatch); Init (Bus.Session, SessionDispatch); } public static void Init (Connection conn, IOFunc dispatchHandler) { IOChannel channel = new IOChannel ((int)conn.SocketHandle); IO.AddWatch (channel, IOCondition.In, dispatchHandler); } //TODO: add public API to watch an arbitrary connection } }
mit
C#
6a288024ef35a56f52b9e54035d1eabbe8e5b3a6
Increase Version Number
BYteWareGmbH/XAF.ElasticSearch
BYteWare.XAF.ElasticSearch/Properties/AssemblyInfo.cs
BYteWare.XAF.ElasticSearch/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BYteWare.XAF.ElasticSearch")] [assembly: AssemblyDescription("BYteWare XAF Module")] [assembly: AssemblyProduct("BYteWare.XAF.ElasticSearch")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("16.24.20")] [assembly: AssemblyInformationalVersion("16.24.20.3")]
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BYteWare.XAF.ElasticSearch")] [assembly: AssemblyDescription("BYteWare XAF Module")] [assembly: AssemblyProduct("BYteWare.XAF.ElasticSearch")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("16.24.20")] [assembly: AssemblyInformationalVersion("16.24.20.2")]
mpl-2.0
C#
20412a3d3a4ce709eaa1823a3c83ac0c19de9855
add TODO
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Services/Implementations/TableService.cs
src/FilterLists.Services/Implementations/TableService.cs
using System.IO; using System.Net.Http; using System.Threading.Tasks; using FilterLists.Data.Repositories.Contracts; using FilterLists.Services.Contracts; namespace FilterLists.Services.Implementations { public class TableService : ITableService { private readonly ITableCsvRepository _tableCsvRepository; public TableService(ITableCsvRepository tableCsvRepository) { _tableCsvRepository = tableCsvRepository; } /// <summary> /// update all tables via .CSVs from GitHub /// </summary> public void UpdateTables() { //TODO: loop through all CSVs UpdateTable("List"); } /// <summary> /// update table via .CSV from GitHub /// </summary> /// <param name="tableName">name of database table</param> public void UpdateTable(string tableName) { var file = FetchFile(_tableCsvRepository.GetUrlByName(tableName), tableName).Result; //TODO: exec stored procedure to merge/upsert csv into corresponding db table //TODO: delete file when finished } /// <summary> /// fetch file as string from internet /// </summary> /// <param name="url">URL of file to fetch</param> /// <param name="fileName">name to save file as</param> /// <returns>string of file</returns> private static async Task<string> FetchFile(string url, string fileName) { var response = await new HttpClient().GetAsync(url); response.EnsureSuccessStatusCode(); var path = Path.Combine(Directory.GetCurrentDirectory(), "csv"); Directory.CreateDirectory(path); var file = Path.Combine(path, fileName + ".csv"); using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) { await response.Content.CopyToAsync(fileStream); } return file; } } }
using System.IO; using System.Net.Http; using System.Threading.Tasks; using FilterLists.Data.Repositories.Contracts; using FilterLists.Services.Contracts; namespace FilterLists.Services.Implementations { public class TableService : ITableService { private readonly ITableCsvRepository _tableCsvRepository; public TableService(ITableCsvRepository tableCsvRepository) { _tableCsvRepository = tableCsvRepository; } /// <summary> /// update all tables via .CSVs from GitHub /// </summary> public void UpdateTables() { //TODO: loop through all CSVs UpdateTable("List"); } /// <summary> /// update table via .CSV from GitHub /// </summary> /// <param name="tableName">name of database table</param> public void UpdateTable(string tableName) { var file = FetchFile(_tableCsvRepository.GetUrlByName(tableName), tableName).Result; //TODO: exec stored procedure to merge/upsert csv into corresponding db table } /// <summary> /// fetch file as string from internet /// </summary> /// <param name="url">URL of file to fetch</param> /// <param name="fileName">name to save file as</param> /// <returns>string of file</returns> private static async Task<string> FetchFile(string url, string fileName) { var response = await new HttpClient().GetAsync(url); response.EnsureSuccessStatusCode(); var path = Path.Combine(Directory.GetCurrentDirectory(), "csv"); Directory.CreateDirectory(path); var file = Path.Combine(path, fileName + ".csv"); using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) { await response.Content.CopyToAsync(fileStream); } return file; } } }
mit
C#
0029b8f0539f181ce0dad0f24b4387ca188d1d08
Use non-pinnable buffer for zero byte read (#3094)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Kestrel.Transport.Sockets/Internal/SocketReceiver.cs
src/Kestrel.Transport.Sockets/Internal/SocketReceiver.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO.Pipelines; using System.Net.Sockets; namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal { public sealed class SocketReceiver : SocketSenderReceiverBase { public SocketReceiver(Socket socket, PipeScheduler scheduler) : base(socket, scheduler) { } public SocketAwaitableEventArgs WaitForDataAsync() { #if NETCOREAPP2_1 _awaitableEventArgs.SetBuffer(Memory<byte>.Empty); #else _awaitableEventArgs.SetBuffer(Array.Empty<byte>(), 0, 0); #endif if (!_socket.ReceiveAsync(_awaitableEventArgs)) { _awaitableEventArgs.Complete(); } return _awaitableEventArgs; } public SocketAwaitableEventArgs ReceiveAsync(Memory<byte> buffer) { #if NETCOREAPP2_1 _awaitableEventArgs.SetBuffer(buffer); #elif NETSTANDARD2_0 var segment = buffer.GetArray(); _awaitableEventArgs.SetBuffer(segment.Array, segment.Offset, segment.Count); #else #error TFMs need to be updated #endif if (!_socket.ReceiveAsync(_awaitableEventArgs)) { _awaitableEventArgs.Complete(); } return _awaitableEventArgs; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO.Pipelines; using System.Net.Sockets; namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal { public sealed class SocketReceiver : SocketSenderReceiverBase { public SocketReceiver(Socket socket, PipeScheduler scheduler) : base(socket, scheduler) { } public SocketAwaitableEventArgs WaitForDataAsync() { _awaitableEventArgs.SetBuffer(Array.Empty<byte>(), 0, 0); if (!_socket.ReceiveAsync(_awaitableEventArgs)) { _awaitableEventArgs.Complete(); } return _awaitableEventArgs; } public SocketAwaitableEventArgs ReceiveAsync(Memory<byte> buffer) { #if NETCOREAPP2_1 _awaitableEventArgs.SetBuffer(buffer); #elif NETSTANDARD2_0 var segment = buffer.GetArray(); _awaitableEventArgs.SetBuffer(segment.Array, segment.Offset, segment.Count); #else #error TFMs need to be updated #endif if (!_socket.ReceiveAsync(_awaitableEventArgs)) { _awaitableEventArgs.Complete(); } return _awaitableEventArgs; } } }
apache-2.0
C#
7d32089f8c496005925ff6848c5a69f942d2896b
Set version to 0.5.0
morgen2009/DelegateDecompiler,hazzik/DelegateDecompiler,jaenyph/DelegateDecompiler
src/DelegateDecompiler/Properties/AssemblyInfo.cs
src/DelegateDecompiler/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012")] [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("cec0a257-502b-4718-91c3-9e67555c5e1b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.5.0.0")] [assembly: AssemblyFileVersion("0.5.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012")] [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("cec0a257-502b-4718-91c3-9e67555c5e1b")] // 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.4.1.0")] [assembly: AssemblyFileVersion("0.4.1.0")]
mit
C#
fe2024809eee6f01bbce8ca34c1023ebe9507070
Update version number for new publish
GibraltarSoftware/DistributedLocking
src/DistributedLocking/Properties/AssemblyInfo.cs
src/DistributedLocking/Properties/AssemblyInfo.cs
#region File Header and License // /* // AssemblyInfo.cs // Copyright 2008-2017 Gibraltar Software, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // */ #endregion 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("Gibraltar Software Distributed Locking")] [assembly: AssemblyDescription("Inter-computer and Inter-process locking library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Gibraltar Software, Inc.")] [assembly: AssemblyProduct("Loupe")] [assembly: AssemblyCopyright("Copyright © 2008-2017 Gibraltar Software, Inc.")] [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("debc0303-9943-4bcc-9b01-29a0ba10764b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.1.0")]
#region File Header and License // /* // AssemblyInfo.cs // Copyright 2008-2017 Gibraltar Software, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // */ #endregion 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("Gibraltar Software Distributed Locking")] [assembly: AssemblyDescription("Inter-computer and Inter-process locking library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Gibraltar Software, Inc.")] [assembly: AssemblyProduct("Loupe")] [assembly: AssemblyCopyright("Copyright © 2008-2017 Gibraltar Software, Inc.")] [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("debc0303-9943-4bcc-9b01-29a0ba10764b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
apache-2.0
C#
5fe97a9a06da256268f3e60c49bdd50b9961b280
Fix build
Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/Components/Interop/JsonFile.cs
src/Tgstation.Server.Host/Components/Interop/JsonFile.cs
using System.Collections.Generic; using Tgstation.Server.Api.Models; using Tgstation.Server.Api.Models.Internal; namespace Tgstation.Server.Host.Components.Interop { /// <summary> /// Representation of the initial json passed to DreamDaemon /// </summary> sealed class JsonFile { /// <summary> /// The code used by the server to authenticate command Topics /// </summary> public string AccessIdentifier { get; set; } /// <summary> /// If DD should just respond if it's API is working and then exit /// </summary> public bool ApiValidateOnly { get; set; } /// <summary> /// The <see cref="Api.Models.Instance.Name"/> of the owner at the time of launch /// </summary> public string InstanceName { get; set; } /// <summary> /// JSON file name that contains current active chat channel information /// </summary> public string ChatChannelsJson { get; set; } /// <summary> /// JSON file DD should write to with available chat commands /// </summary> public string ChatCommandsJson { get; set; } /// <summary> /// JSON file DD should write to to send commands to the server /// </summary> public string ServerCommandsJson { get; set; } /// <summary> /// The <see cref="Api.Models.Internal.RevisionInformation"/> of the launch /// </summary> public Api.Models.Internal.RevisionInformation Revision { get; set; } /// <summary> /// The <see cref="DreamDaemonSecurity"/> level of the launch /// </summary> public DreamDaemonSecurity SecurityLevel { get; set; } /// <summary> /// The <see cref="TestMerge"/>s in the launch /// </summary> public List<TestMerge> TestMerges { get; } = new List<TestMerge>(); } }
using System.Collections.Generic; using Tgstation.Server.Api.Models; using Tgstation.Server.Api.Models.Internal; namespace Tgstation.Server.Host.Components.Interop { /// <summary> /// Representation of the initial json passed to DreamDaemon /// </summary> sealed class JsonFile { /// <summary> /// The code used by the server to authenticate command Topics /// </summary> public string AccessIdentifier { get; set; } /// <summary> /// If DD should just respond if it's API is working and then exit /// </summary> public bool ApiValidateOnly { get; set; } /// <summary> /// The <see cref="Api.Models.Instance.Name"/> of the owner at the time of launch /// </summary> public string InstanceName { get; set; } /// <summary> /// JSON file name that contains current active chat channel information /// </summary> public string ChatChannelsJson { get; set; } /// <summary> /// JSON file DD should write to with available chat commands /// </summary> public string ChatCommandsJson { get; set; } /// <summary> /// JSON file DD should write to to send commands to the server /// </summary> public string ServerCommandsJson { get; set; } /// <summary> /// The <see cref="RevisionInformation"/> of the launch /// </summary> public Api.Models.Internal.RevisionInformation Revision { get; set; } /// <summary> /// The <see cref="DreamDaemonSecurity"/> level of the launch /// </summary> public DreamDaemonSecurity SecurityLevel { get; set; } /// <summary> /// The <see cref="TestMerge"/>s in the launch /// </summary> public List<TestMerge> TestMerges { get; } = new List<TestMerge>(); } }
agpl-3.0
C#
3685093930195e7f73bc2704027886b7fe95f3cf
Fix time for shaking the camera
matiasbeckerle/perspektiva,matiasbeckerle/breakout,matiasbeckerle/arkanoid
source/Assets/Scripts/Camera/CameraShake.cs
source/Assets/Scripts/Camera/CameraShake.cs
using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { /// <summary> /// Shake amount. /// </summary> public float shakeAmount = 0.1f; /// <summary> /// Shake decrease factor. /// </summary> public float shakeDecreaseFactor = 1f; /// <summary> /// MainCamera's reference. /// </summary> private GameObject _mainCamera; /// <summary> /// Flag to know when the camera is shaking. /// </summary> private bool _isShaking; void Awake() { _mainCamera = GameObject.FindGameObjectWithTag("MainCamera"); } /// <summary> /// Shakes the camera. /// </summary> /// <param name="duration">Seconds to end the movement.</param> public void Shake(float duration) { if (!_isShaking) { StartCoroutine(ShakeItOff(duration)); } } /// <summary> /// Shakes the camera. /// </summary> /// <param name="duration">Seconds to end the movement.</param> /// <returns></returns> IEnumerator ShakeItOff(float duration) { // One shake at the time. _isShaking = true; // Keep a reference of the current position. Vector3 cameraOriginalPosition = _mainCamera.transform.position; float elapsed = 0f; while (elapsed < duration) { // Shake the camera. _mainCamera.transform.localPosition += Random.insideUnitSphere * shakeAmount * elapsed; // Increase the elapsed time of camera being shake. elapsed += Time.fixedDeltaTime * shakeDecreaseFactor; yield return null; } // Back to the original position. _mainCamera.transform.localPosition = cameraOriginalPosition; _isShaking = false; } }
using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { /// <summary> /// Shake amount. /// </summary> public float shakeAmount = 0.1f; /// <summary> /// Shake decrease factor. /// </summary> public float shakeDecreaseFactor = 1f; /// <summary> /// MainCamera's reference. /// </summary> private GameObject _mainCamera; /// <summary> /// Flag to know when the camera is shaking. /// </summary> private bool _isShaking; void Awake() { _mainCamera = GameObject.FindGameObjectWithTag("MainCamera"); } /// <summary> /// Shakes the camera. /// </summary> /// <param name="duration">Seconds to end the movement.</param> public void Shake(float duration) { if (!_isShaking) { StartCoroutine(ShakeItOff(duration)); } } /// <summary> /// Shakes the camera. /// </summary> /// <param name="duration">Seconds to end the movement.</param> /// <returns></returns> IEnumerator ShakeItOff(float duration) { // One shake at the time. _isShaking = true; // Keep a reference of the current position. Vector3 cameraOriginalPosition = _mainCamera.transform.position; float elapsed = 0f; while (elapsed < duration) { // Shake the camera. _mainCamera.transform.localPosition += Random.insideUnitSphere * shakeAmount * elapsed; // Increase the elapsed time of camera being shake. elapsed += Time.deltaTime * shakeDecreaseFactor; yield return null; } // Back to the original position. _mainCamera.transform.localPosition = cameraOriginalPosition; _isShaking = false; } }
unknown
C#
1b3d6420af8d723b2e9137229f1e14c6aa778221
Make queue extension methods public
ghkim69/win-beacon,huysentruitw/win-beacon
src/WinBeacon.Stack/Extensions/QueueExtensions.cs
src/WinBeacon.Stack/Extensions/QueueExtensions.cs
/* * Copyright 2015 Huysentruit Wouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace WinBeacon.Stack { /// <summary> /// Queue extension methods. /// </summary> public static class QueueExtensions { /// <summary> /// Dequeue all items from the queue. /// </summary> /// <typeparam name="T">Item type.</typeparam> /// <param name="queue">The queue.</param> /// <returns>Array of dequeued items.</returns> public static T[] DequeueAll<T>(this Queue<T> queue) { var result = new List<T>(); while (queue.Count > 0) result.Add(queue.Dequeue()); return result.ToArray(); } /// <summary> /// Dequeue the specified number of items. /// </summary> /// <typeparam name="T">Item type.</typeparam> /// <param name="queue">The queue.</param> /// <param name="count">Number of items to dequeue.</param> /// <returns>Array of dequeued items.</returns> public static T[] Dequeue<T>(this Queue<T> queue, int count) { var result = new List<T>(); for (int i = 0; i < count; i++) result.Add(queue.Dequeue()); return result.ToArray(); } } }
/* * Copyright 2015 Huysentruit Wouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace WinBeacon.Stack { /// <summary> /// Queue extension methods. /// </summary> internal static class QueueExtensions { /// <summary> /// Dequeue all items from the queue. /// </summary> /// <typeparam name="T">Item type.</typeparam> /// <param name="queue">The queue.</param> /// <returns>Array of dequeued items.</returns> public static T[] DequeueAll<T>(this Queue<T> queue) { var result = new List<T>(); while (queue.Count > 0) result.Add(queue.Dequeue()); return result.ToArray(); } /// <summary> /// Dequeue the specified number of items. /// </summary> /// <typeparam name="T">Item type.</typeparam> /// <param name="queue">The queue.</param> /// <param name="count">Number of items to dequeue.</param> /// <returns>Array of dequeued items.</returns> public static T[] Dequeue<T>(this Queue<T> queue, int count) { var result = new List<T>(); for (int i = 0; i < count; i++) result.Add(queue.Dequeue()); return result.ToArray(); } } }
mit
C#
d402f17e2e20cb445b250b315331b37d8d2ae017
Update to correct version strings
PyramidTechnologies/netPyramid-RS-232
Apex7000_BillValidator/Properties/AssemblyInfo.cs
Apex7000_BillValidator/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NET Pyramid RS-232")] [assembly: AssemblyDescription("RS-232 API by Pyramid Technologies")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Pyramid Technologies Inc")] [assembly: AssemblyProduct("NET Pyramid RS-232")] [assembly: AssemblyCopyright("© Pyramid Technologies Inc. 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("380ac9e2-635d-4547-a090-4e0e25663de9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly : InternalsVisibleTo("PyramidNETRS232_Test")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NET Pyramid RS-232")] [assembly: AssemblyDescription("RS-232 API by Pyramid Technologies")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Pyramid Technologies Inc")] [assembly: AssemblyProduct("NET Pyramid RS-232")] [assembly: AssemblyCopyright("© Pyramid Technologies Inc. 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("380ac9e2-635d-4547-a090-4e0e25663de9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly : InternalsVisibleTo("PyramidNETRS232_Test")]
mit
C#
cdceb44c2aac8701f448dcb8da032ac6ffd2f8ef
Update AssemblyInfo.cs
BaamStudios/SharpAngie,BaamStudios/SharpAngie,BaamStudios/SharpAngie
BaamStudios.SharpAngie/Properties/AssemblyInfo.cs
BaamStudios.SharpAngie/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BaamStudios.SharpAngie")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("BaamStudios")] [assembly: AssemblyProduct("BaamStudios.SharpAngie")] [assembly: AssemblyCopyright("Copyright © BaamStudios 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d5b185c3-f74e-461f-b273-ef5997c47d44")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BaamStudios.SharpAngie")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("hannover re")] [assembly: AssemblyProduct("BaamStudios.SharpAngie")] [assembly: AssemblyCopyright("Copyright © hannover re 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d5b185c3-f74e-461f-b273-ef5997c47d44")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
f3e041492fb92f68389afb5e9657c323bec21cd9
Add test data for Teacher to DbInitializer.
Programazing/Open-School-Library,Programazing/Open-School-Library
src/Open-School-Library/Data/DbInitializer.cs
src/Open-School-Library/Data/DbInitializer.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; using Open_School_Library.Models.DatabaseModels; namespace Open_School_Library.Data { public class DbInitializer { public static void Initialize(LibraryContext context) { context.Database.EnsureCreated(); //Look for Students if(context.Students.Any()) { return; //DB has been seeded } var students = new Student[] { new Student { FirstName="John", LastName="Tell", Email="a@b.com", Grade=3, HomeRoomTeacher=1, Fines=1.50M, IssusedID=10254 } }; foreach (Student s in students) { context.Students.Add(s); } context.SaveChanges(); var teachers = new Teacher[] { new Teacher {FirstName="Erik", LastName="Henderson", Grade=3 } }; foreach (Teacher s in teachers) { context.Teachers.Add(s); } context.SaveChanges(); var genres = new Genre[] { new Genre { Name="Horror" }, new Genre { Name="Romance" } }; foreach (Genre s in genres) { context.Genres.Add(s); } context.SaveChanges(); var deweys = new Dewey[] { new Dewey { Name="Computer Science, Information & General Works", Number=000 }, new Dewey { Name="Philosophy & Psychology", Number=100 }, new Dewey { Name="Religion", Number=200 } }; foreach (Dewey s in deweys) { context.Deweys.Add(s); } context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; using Open_School_Library.Models.DatabaseModels; namespace Open_School_Library.Data { public class DbInitializer { public static void Initialize(LibraryContext context) { context.Database.EnsureCreated(); //Look for Students if(context.Students.Any()) { return; //DB has been seeded } var students = new Student[] { new Student { FirstName="John", LastName="Tell", Email="a@b.com", Grade=3, HomeRoomTeacher=1, Fines=1.50M, IssusedID=10254 } }; foreach (Student s in students) { context.Students.Add(s); } context.SaveChanges(); var genres = new Genre[] { new Genre { Name="Horror" }, new Genre { Name="Romance" } }; foreach (Genre s in genres) { context.Genres.Add(s); } context.SaveChanges(); var deweys = new Dewey[] { new Dewey { Name="Computer Science, Information & General Works", Number=000 }, new Dewey { Name="Philosophy & Psychology", Number=100 }, new Dewey { Name="Religion", Number=200 } }; foreach (Dewey s in deweys) { context.Deweys.Add(s); } context.SaveChanges(); } } }
mit
C#
24bc198b9131dbf6567fc8a03d2cb0adf2aac41a
Update plug in version of MenuBar
pergerch/DotSpatial,JasminMarinelli/DotSpatial,bdgza/DotSpatial,bdgza/DotSpatial,DotSpatial/DotSpatial,pergerch/DotSpatial,pedwik/DotSpatial,pergerch/DotSpatial,DotSpatial/DotSpatial,pedwik/DotSpatial,CGX-GROUP/DotSpatial,donogst/DotSpatial,bdgza/DotSpatial,swsglobal/DotSpatial,CGX-GROUP/DotSpatial,DotSpatial/DotSpatial,JasminMarinelli/DotSpatial,JasminMarinelli/DotSpatial,swsglobal/DotSpatial,donogst/DotSpatial,swsglobal/DotSpatial,donogst/DotSpatial,pedwik/DotSpatial,CGX-GROUP/DotSpatial
DotSpatial.Plugins.MenuBar/Properties/AssemblyInfo.cs
DotSpatial.Plugins.MenuBar/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("DotSpatial.Plugins.MenuBar")] [assembly: AssemblyDescription("A standard set of icons and buttons for interacting with the map. http://www.fatcow.com/free-icons provided some of the icons.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DotSpatial Team")] [assembly: AssemblyProduct("DotSpatial.Plugins.MenuBar")] [assembly: AssemblyCopyright("Copyright © DotSpatial Team 2010-2012")] [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("9183a9f6-a464-430d-8a37-0d0894f4f74b")] // 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.11.9.6")] [assembly: AssemblyFileVersion("1.0.1191")]
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("DotSpatial.Plugins.MenuBar")] [assembly: AssemblyDescription("A standard set of icons and buttons for interacting with the map. http://www.fatcow.com/free-icons provided some of the icons.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DotSpatial Team")] [assembly: AssemblyProduct("DotSpatial.Plugins.MenuBar")] [assembly: AssemblyCopyright("Copyright © DotSpatial Team 2010-2012")] [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("9183a9f6-a464-430d-8a37-0d0894f4f74b")] // 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.11.9.6")] [assembly: AssemblyFileVersion("1.0.1190")]
mit
C#
d3a1e82d76719bd8c9d439946f6d365a964174ed
Call Dispose and the GC to avoid leaking memory.
xamarin/SignaturePad,xamarin/SignaturePad
src/SignaturePad.Android/ClearingImageView.cs
src/SignaturePad.Android/ClearingImageView.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Util; using Android.Graphics; namespace SignaturePad { public class ClearingImageView : ImageView { private Bitmap imageBitmap = null; public ClearingImageView (Context context) : base (context) { } public ClearingImageView (Context context, IAttributeSet attrs) : base (context, attrs) { } public ClearingImageView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { } public override void SetImageBitmap(Bitmap bm) { base.SetImageBitmap (bm); if (imageBitmap != null) { imageBitmap.Recycle (); imageBitmap.Dispose (); } imageBitmap = bm; System.GC.Collect (); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Util; using Android.Graphics; namespace SignaturePad { public class ClearingImageView : ImageView { private Bitmap imageBitmap = null; public ClearingImageView (Context context) : base (context) { } public ClearingImageView (Context context, IAttributeSet attrs) : base (context, attrs) { } public ClearingImageView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { } public override void SetImageBitmap(Bitmap bm) { base.SetImageBitmap (bm); if (imageBitmap != null) { imageBitmap.Recycle (); } imageBitmap = bm; } } }
mit
C#
9a753140fd9d671f45601c9c5480a0845808b43d
Fix failing tests.
AvaloniaUI/Avalonia,susloparovdenis/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,OronDF343/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,punker76/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,susloparovdenis/Perspex,jazzay/Perspex,jkoritzinsky/Avalonia,MrDaedra/Avalonia,jkoritzinsky/Avalonia,OronDF343/Avalonia,jkoritzinsky/Avalonia,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,susloparovdenis/Avalonia,MrDaedra/Avalonia
tests/Perspex.Controls.UnitTests/TestRoot.cs
tests/Perspex.Controls.UnitTests/TestRoot.cs
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Moq; using Perspex.Layout; using Perspex.Platform; using Perspex.Rendering; using Perspex.Styling; namespace Perspex.Controls.UnitTests { internal class TestRoot : Decorator, ILayoutRoot, IRenderRoot, IStyleRoot { public Size ClientSize => new Size(100, 100); public Size MaxClientSize => Size.Infinity; public ILayoutManager LayoutManager => new Mock<ILayoutManager>().Object; public IRenderTarget RenderTarget { get { throw new NotImplementedException(); } } public IRenderQueueManager RenderQueueManager => null; public Point TranslatePointToScreen(Point p) { return new Point(); } } }
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Moq; using Perspex.Layout; using Perspex.Platform; using Perspex.Rendering; using Perspex.Styling; namespace Perspex.Controls.UnitTests { internal class TestRoot : Decorator, ILayoutRoot, IRenderRoot, IStyleRoot { public Size ClientSize => new Size(100, 100); public Size MaxClientSize => Size.Infinity; public ILayoutManager LayoutManager => new Mock<ILayoutManager>().Object; public IRenderTarget RenderTarget { get { throw new NotImplementedException(); } } public IRenderQueueManager RenderQueueManager { get { throw new NotImplementedException(); } } public Point TranslatePointToScreen(Point p) { return new Point(); } } }
mit
C#
620312e479ea03e2f9cdb3771d4fde53ce8a1692
Use 0.0.0.0.
FacilityApi/FacilityGeneratorApi,FacilityApi/FacilityGeneratorApi,FacilityApi/FacilityGeneratorApi
src/Facility.GeneratorApi.WebApi/Program.cs
src/Facility.GeneratorApi.WebApi/Program.cs
using System.IO; using Microsoft.AspNetCore.Hosting; namespace Facility.GeneratorApi.WebApi { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseUrls("http://0.0.0.0:45054") .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
using System.IO; using Microsoft.AspNetCore.Hosting; namespace Facility.GeneratorApi.WebApi { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseUrls("http://local.fsdgenapi.facility.io:45054") .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
mit
C#
39d0682a220505735036eb1fc2b9cfe85bf0b4d1
use mongodb provider's IdentityUser
g0t4/aspnet-identity-mongo-sample,g0t4/aspnet-identity-mongo-sample,g0t4/aspnet-identity-mongo-sample
src/IdentitySample/Models/IdentityModels.cs
src/IdentitySample/Models/IdentityModels.cs
using AspNet.Identity.MongoDB; using Microsoft.AspNet.Identity; using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; namespace IdentitySample.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } static ApplicationDbContext() { // Set the database intializer which is run once during application start // This seeds the database with admin user credentials and admin role Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
using Microsoft.AspNet.Identity; using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; namespace IdentitySample.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } static ApplicationDbContext() { // Set the database intializer which is run once during application start // This seeds the database with admin user credentials and admin role Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
mit
C#
f60ccdb8547aefbf7388ae97c64ab6b4343cb8c0
Update VotePopUp.cs
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/Voting/VotePopUp.cs
UnityProject/Assets/Scripts/Voting/VotePopUp.cs
using System.Collections; using System.Collections.Generic; using DatabaseAPI; using UnityEngine; using UnityEngine.UI; public class VotePopUp : MonoBehaviour { [SerializeField] private Text voteTitle = null; [SerializeField] private Text voteInstigator = null; [SerializeField] private Text voteCount = null; [SerializeField] private Text voteTimer = null; [SerializeField] private Button yesBtn = null; [SerializeField] private Button noBtn = null; [SerializeField] private Button vetoBtn = null; private int buttonPresses = 0; public void ShowVotePopUp(string title, string instigator, string currentCount, string timer) { buttonPresses = 0; ToggleButtons(true); gameObject.SetActive(true); voteTitle.text = title; voteInstigator.text = instigator; voteCount.text = currentCount; voteTimer.text = timer; if (PlayerList.Instance.AdminToken == null) return; vetoBtn.gameObject.SetActive(true); } public void UpdateVoteWindow(string currentCount, string timer) { if (!gameObject.activeInHierarchy) return; voteCount.text = currentCount; voteTimer.text = timer; } public void CloseVoteWindow() { vetoBtn.gameObject.SetActive(false); gameObject.SetActive(false); } public void VoteYes() { SoundManager.Play("Click01"); if (PlayerManager.PlayerScript != null) { PlayerManager.PlayerScript.playerNetworkActions.CmdRegisterVote(true); } buttonPresses ++; yesBtn.interactable = false; noBtn.interactable = true; ToggleButtons(false); } public void VoteNo() { SoundManager.Play("Click01"); if (PlayerManager.PlayerScript != null) { PlayerManager.PlayerScript.playerNetworkActions.CmdRegisterVote(false); } buttonPresses++; yesBtn.interactable = true; noBtn.interactable = false; ToggleButtons(false); } public void AdminVeto() { SoundManager.Play("Click01"); if (PlayerManager.PlayerScript != null) { PlayerManager.PlayerScript.playerNetworkActions.CmdVetoRestartVote(ServerData.UserID, PlayerList.Instance.AdminToken); } buttonPresses++; ToggleButtons(false); } void ToggleButtons(bool isOn) { if (buttonPresses < 10) return; yesBtn.interactable = isOn; noBtn.interactable = isOn; } }
using System.Collections; using System.Collections.Generic; using DatabaseAPI; using UnityEngine; using UnityEngine.UI; public class VotePopUp : MonoBehaviour { [SerializeField] private Text voteTitle = null; [SerializeField] private Text voteInstigator = null; [SerializeField] private Text voteCount = null; [SerializeField] private Text voteTimer = null; [SerializeField] private Button yesBtn = null; [SerializeField] private Button noBtn = null; [SerializeField] private Button vetoBtn = null; private int buttonPresses = 0; public void ShowVotePopUp(string title, string instigator, string currentCount, string timer) { buttonPresses = 0; ToggleButtons(true); gameObject.SetActive(true); voteTitle.text = title; voteInstigator.text = instigator; voteCount.text = currentCount; voteTimer.text = timer; if (PlayerList.Instance.AdminToken == null) return; vetoBtn.gameObject.SetActive(true); } public void UpdateVoteWindow(string currentCount, string timer) { if (!gameObject.activeInHierarchy) return; voteCount.text = currentCount; voteTimer.text = timer; } public void CloseVoteWindow() { vetoBtn.gameObject.SetActive(false); gameObject.SetActive(false); } public void VoteYes() { SoundManager.Play("Click01"); if (PlayerManager.PlayerScript != null) { PlayerManager.PlayerScript.playerNetworkActions.CmdRegisterVote(true); } buttonPresses ++; ToggleButtons(false); yesBtn.interactable = false; noBtn.interactable = true; } public void VoteNo() { SoundManager.Play("Click01"); if (PlayerManager.PlayerScript != null) { PlayerManager.PlayerScript.playerNetworkActions.CmdRegisterVote(false); } buttonPresses++; ToggleButtons(false); yesBtn.interactable = true; noBtn.interactable = false; } public void AdminVeto() { SoundManager.Play("Click01"); if (PlayerManager.PlayerScript != null) { PlayerManager.PlayerScript.playerNetworkActions.CmdVetoRestartVote(ServerData.UserID, PlayerList.Instance.AdminToken); } buttonPresses++; ToggleButtons(false); } void ToggleButtons(bool isOn) { if (buttonPresses < 10) return; yesBtn.interactable = isOn; noBtn.interactable = isOn; } }
agpl-3.0
C#
abb22c24f294e7bd0a810a905e5dfe552173c56a
Fix homepage layout on small mobile screens
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
src/LondonTravel.Site/Views/Home/Index.cshtml
src/LondonTravel.Site/Views/Home/Index.cshtml
@inject SiteOptions Options @{ ViewBag.Title = "Home"; } @if (User.Identity.IsAuthenticated && string.Equals(Context.Request.Query["Message"], nameof(SiteMessage.AccountCreated), StringComparison.OrdinalIgnoreCase)) { <div class="alert alert-success" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="lead"> Your London Travel account has been created. </p> </div> } @if (!User.Identity.IsAuthenticated && string.Equals(Context.Request.Query["Message"], nameof(SiteMessage.AccountDeleted), StringComparison.OrdinalIgnoreCase)) { <div class="alert alert-success" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="lead"> Your London Travel account has been deleted. </p> <p> Sorry to see you go. </p> </div> } <div class="jumbotron"> <h1>London Travel</h1> <p class="lead"> An Amazon Alexa skill for checking the status of travel in London. </p> <p> <a class="btn btn-primary" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa from amazon.co.uk">Install <i class="fa fa-external-link" aria-hidden="true"></i></a> @if (!User.Identity.IsAuthenticated) { <a class="btn btn-primary hidden-xs" asp-route="@SiteRoutes.Register" title="Register for a London Travel account">Register <i class="fa fa-user-plus" aria-hidden="true"></i></a> <a class="btn btn-primary hidden-xs" asp-route="@SiteRoutes.SignIn" title="Sign in to your London Travel account">Sign In <i class="fa fa-sign-in" aria-hidden="true"></i></a> } </p> @if (!User.Identity.IsAuthenticated) { <p class="visible-xs"> <a class="btn btn-primary" asp-route="@SiteRoutes.Register" title="Register for a London Travel account">Register <i class="fa fa-user-plus" aria-hidden="true"></i></a> <a class="btn btn-primary" asp-route="@SiteRoutes.SignIn" title="Sign in to your London Travel account">Sign In <i class="fa fa-sign-in" aria-hidden="true"></i></a> </p> } </div>
@inject SiteOptions Options @{ ViewBag.Title = "Home"; } @if (User.Identity.IsAuthenticated && string.Equals(Context.Request.Query["Message"], nameof(SiteMessage.AccountCreated), StringComparison.OrdinalIgnoreCase)) { <div class="alert alert-success" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="lead"> Your London Travel account has been created. </p> </div> } @if (!User.Identity.IsAuthenticated && string.Equals(Context.Request.Query["Message"], nameof(SiteMessage.AccountDeleted), StringComparison.OrdinalIgnoreCase)) { <div class="alert alert-success" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="lead"> Your London Travel account has been deleted. </p> <p> Sorry to see you go. </p> </div> } <div class="jumbotron"> <h1>London Travel</h1> <p class="lead"> An Amazon Alexa skill for checking the status of travel in London. </p> <p> <a class="btn btn-primary" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa from amazon.co.uk">Install <i class="fa fa-external-link" aria-hidden="true"></i></a> @if (!User.Identity.IsAuthenticated) { <a class="btn btn-primary" asp-route="@SiteRoutes.Register" title="Register for a London Travel account">Register <i class="fa fa-user-plus" aria-hidden="true"></i></a> <a class="btn btn-primary" asp-route="@SiteRoutes.SignIn" title="Sign in to your London Travel account">Sign In <i class="fa fa-sign-in" aria-hidden="true"></i></a> } </p> </div>
apache-2.0
C#
14c4c5b072f3e653eb473b9c863ced11146203cf
enable Unknown FacebookPostType
losttech/Facebook.Models
src/FacebookPostType.cs
src/FacebookPostType.cs
namespace Facebook.Models { using System.Runtime.Serialization; public enum FacebookPostType { [EnumMember(Value = "")] Unknown, [EnumMember(Value = "mobile_status_update")] Mobile, [EnumMember(Value = "created_note")] Note, [EnumMember(Value = "added_photos")] Photos, [EnumMember(Value = "added_video")] Video, [EnumMember(Value = "shared_story")] Story, [EnumMember(Value = "created_group")] Group, [EnumMember(Value = "created_event")] Event, [EnumMember(Value = "wall_post")] WallPost, [EnumMember(Value = "app_created_story")] AppCreatedStory, [EnumMember(Value = "published_story")] PublishedStory, [EnumMember(Value = "tagged_in_photo")] Tagged, [EnumMember(Value = "approved_friend")] ApprovedFriend, } }
namespace Facebook.Models { using System.Runtime.Serialization; public enum FacebookPostType { [EnumMember(Value = "mobile_status_update")] Mobile, [EnumMember(Value = "created_note")] Note, [EnumMember(Value = "added_photos")] Photos, [EnumMember(Value = "added_video")] Video, [EnumMember(Value = "shared_story")] Story, [EnumMember(Value = "created_group")] Group, [EnumMember(Value = "created_event")] Event, [EnumMember(Value = "wall_post")] WallPost, [EnumMember(Value = "app_created_story")] AppCreatedStory, [EnumMember(Value = "published_story")] PublishedStory, [EnumMember(Value = "tagged_in_photo")] Tagged, [EnumMember(Value = "approved_friend")] ApprovedFriend, } }
apache-2.0
C#
1f7909117f1fd7d565b8a6bc2c51003191034802
Add parallelism to Tests project
atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata
src/Atata.Tests/Properties/AssemblyInfo.cs
src/Atata.Tests/Properties/AssemblyInfo.cs
using NUnit.Framework; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Atata.Tests")] [assembly: Guid("9d0aa4f2-4987-4395-be95-76abc329b7a0")] [assembly: LevelOfParallelism(4)] [assembly: Parallelizable(ParallelScope.Fixtures)] [assembly: Atata.Culture("en-us")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Atata.Tests")] [assembly: Guid("9d0aa4f2-4987-4395-be95-76abc329b7a0")]
apache-2.0
C#
88719cbb7526046aaa7f64951fef0de22087193d
update profile ssl and Microsoft MVP (#380)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/MichaelRidland.cs
src/Firehose.Web/Authors/MichaelRidland.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MichaelRidland : IAmAXamarinMVP, IAmAMicrosoftMVP { public string FirstName => "Michael"; public string LastName => "Ridland"; public string StateOrRegion => "Sydney, Australia"; public string EmailAddress => "michael@xam-consulting.com"; public string ShortBioOrTagLine => "Xamarin Contractor/Consultant | Founder XAM Consulting (xam-consulting.com) | Creator of FreshMvvm"; public Uri WebSite => new Uri("https://michaelridland.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://michaelridland.com/feed/"); } } public string TwitterHandle => "rid00z"; public string GravatarHash => "3c07e56045d18f4f290eb4983031309d"; public string GitHubHandle => "rid00z"; public GeoPosition Position => new GeoPosition(-25.348875, 131.035000); } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MichaelRidland : IAmAXamarinMVP { public string FirstName => "Michael"; public string LastName => "Ridland"; public string StateOrRegion => "Sydney, Australia"; public string EmailAddress => "michael@xam-consulting.com"; public string ShortBioOrTagLine => "Xamarin Contractor/Consultant | Founder XAM Consulting (xam-consulting.com) | Creator of FreshMvvm"; public Uri WebSite => new Uri("http://www.michaelridland.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://www.michaelridland.com/feed/"); } } public string TwitterHandle => "rid00z"; public string GravatarHash => "3c07e56045d18f4f290eb4983031309d"; public string GitHubHandle => "rid00z"; public GeoPosition Position => new GeoPosition(-25.348875, 131.035000); } }
mit
C#
32957c47d08dd0815bdbe8782b8a137b017a071d
Update CloneExtension.cs
NMSLanX/Natasha
src/Natasha/ExtensionApi/CloneExtension.cs
src/Natasha/ExtensionApi/CloneExtension.cs
using System; using System.Collections.Generic; using System.Text; namespace Natasha.Clone { public static class CloneExtension { public static T Clone<T>(this T instance) { return CloneOperator.Clone(instance); } } }
using System; using System.Collections.Generic; using System.Text; namespace Natasha.Clone { public static class CloneExtension { public static T Clone<T>(this T instance) where T : Delegate { return CloneOperator.Clone(instance); } } }
mpl-2.0
C#
88fb2596e00ee156ead29966076260914caf0658
Make ServerFactory public
tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server
src/Tgstation.Server.Host/ServerFactory.cs
src/Tgstation.Server.Host/ServerFactory.cs
using Microsoft.AspNetCore; namespace Tgstation.Server.Host { /// <inheritdoc /> public sealed class ServerFactory : IServerFactory { /// <inheritdoc /> public IServer CreateServer(string[] args, string updatePath) => new Server(WebHost.CreateDefaultBuilder(args), updatePath); } }
using Microsoft.AspNetCore; namespace Tgstation.Server.Host { /// <inheritdoc /> sealed class ServerFactory : IServerFactory { /// <inheritdoc /> public IServer CreateServer(string[] args, string updatePath) => new Server(WebHost.CreateDefaultBuilder(args), updatePath); } }
agpl-3.0
C#
cba5bd3195c82e46aa1009860e3385ae8a5e7524
Fix init firebase manager.
Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x
src/unity/Runtime/Services/Internal/FirebaseManager.cs
src/unity/Runtime/Services/Internal/FirebaseManager.cs
using System; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Assertions; namespace EE.Internal { internal static class FirebaseManager { private static Task<bool> _initializer; public static Task<bool> Initialize() => _initializer = _initializer ?? (_initializer = InitializeImpl()); private static async Task<bool> InitializeImpl() { Debug.Log($"FirebaseManager: InitializeImpl"); // https://firebase.google.com/docs/unity/setup var typeFirebaseApp = Type.GetType("Firebase.FirebaseApp, Firebase.App"); if (typeFirebaseApp == null) { throw new ArgumentException("Cannot find Firebase.FirebaseApp"); } var methodCheckAndFixDependenciesAsync = typeFirebaseApp.GetMethod("CheckAndFixDependenciesAsync", new Type[] { }); Assert.IsNotNull(methodCheckAndFixDependenciesAsync); var typeDependencyStatus = Type.GetType("Firebase.DependencyStatus, Firebase.App"); Assert.IsNotNull(typeDependencyStatus); var task = (Task) methodCheckAndFixDependenciesAsync.Invoke(null, new object[] { }); await task.ConfigureAwait(false); var status = task.GetType().GetProperty("Result")?.GetValue(task); Debug.Log($"FirebaseManager: CheckAndFixDependenciesAsync result = {status}"); var fieldDependencyStatusAvailable = Enum.Parse(typeDependencyStatus, "Available"); if (fieldDependencyStatusAvailable.Equals(status)) { return true; } Debug.LogError($"Could not resolve all Firebase dependencies"); return false; } } }
using System; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Assertions; namespace EE.Internal { internal static class FirebaseManager { private static Task<bool> _initializer; public static Task<bool> Initialize() => _initializer = _initializer ?? (_initializer = InitializeImpl()); private static async Task<bool> InitializeImpl() { // https://firebase.google.com/docs/unity/setup var typeFirebaseApp = Type.GetType("Firebase.FirebaseApp, Firebase.Core"); if (typeFirebaseApp == null) { throw new ArgumentException("Cannot find Firebase.FirebaseApp"); } var methodCheckAndFixDependenciesAsync = typeFirebaseApp.GetMethod("CheckAndFixDependenciesAsync"); Assert.IsNotNull(methodCheckAndFixDependenciesAsync); var status = await (Task<object>) methodCheckAndFixDependenciesAsync.Invoke(null, new object[] { }); var typeDependencyStatus = Type.GetType("Firebase.DependencyStatus, Firebase.Core"); Assert.IsNotNull(typeDependencyStatus); var fieldDependencyStatusAvailable = Enum.Parse(typeDependencyStatus, "Available"); if (status == fieldDependencyStatusAvailable) { return true; } Debug.LogError($"Could not resolve all Firebase dependencies"); return false; } } }
mit
C#
605ad57d0165ff19abb20bd53ecf8421c1e3fdf3
Fix GameWindow.AllowUserResizing
sharpdx/Toolkit,tomba/Toolkit,sharpdx/Toolkit
Source/Toolkit/SharpDX.Toolkit.Game/GameWindowForm.cs
Source/Toolkit/SharpDX.Toolkit.Game/GameWindowForm.cs
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !W8CORE using System.Windows.Forms; using SharpDX.Windows; namespace SharpDX.Toolkit { internal class GameWindowForm : RenderForm { private bool allowUserResizing; private bool isFullScreenMaximized; public GameWindowForm() : this("SharpDX") { } public GameWindowForm(string text) : base(text) { // By default, non resizable MaximizeBox = false; FormBorderStyle = FormBorderStyle.FixedSingle; } internal bool AllowUserResizing { get { return allowUserResizing; } set { if (allowUserResizing != value) { allowUserResizing = value; MaximizeBox = allowUserResizing; FormBorderStyle = allowUserResizing ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle; } } } } } #endif
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !W8CORE using System.Windows.Forms; using SharpDX.Windows; namespace SharpDX.Toolkit { internal class GameWindowForm : RenderForm { private bool allowUserResizing; private bool isFullScreenMaximized; public GameWindowForm() { } public GameWindowForm(string text) : base(text) { } internal bool AllowUserResizing { get { return allowUserResizing; } set { if (allowUserResizing != value) { allowUserResizing = value; MaximizeBox = !allowUserResizing; FormBorderStyle = allowUserResizing ? FormBorderStyle.FixedSingle : FormBorderStyle.Sizable; } } } } } #endif
mit
C#
94d6820c13dd609ae4b9bf36e79e955d5a070cf0
Swap to IUserComposer
Gibe/Gibe.Navigation
Gibe.Navigation.Umbraco/GibeNavigationComposer.cs
Gibe.Navigation.Umbraco/GibeNavigationComposer.cs
using Gibe.Navigation.Models; using Gibe.Navigation.Umbraco.Filters; using Gibe.UmbracoWrappers; using Umbraco.Core; using Umbraco.Core.Composing; namespace Gibe.Navigation.Umbraco { public class GibeNavigationComposer : IUserComposer { public void Compose(Composition composition) { composition.Register<INavigationElementFactory, NavigationElementFactory>(); composition.Register<INodeTypeFactory, DefaultNodeTypeFactory>(); composition.Register<INavigationProvider<INavigationElement>, UmbracoNavigationProvider<INavigationElement>>(); composition.Register<IUmbracoNodeService, UmbracoNodeService>(); composition.Register<INavigationFilter, TemplateOrRedirectFilter>(); } } }
using Gibe.Navigation.Models; using Gibe.Navigation.Umbraco.Filters; using Gibe.UmbracoWrappers; using Umbraco.Core; using Umbraco.Core.Composing; namespace Gibe.Navigation.Umbraco { public class GibeNavigationComposer : IComposer { public void Compose(Composition composition) { composition.Register<INavigationElementFactory, NavigationElementFactory>(); composition.Register<IUmbracoWrapper, DefaultUmbracoWrapper>(); composition.Register<INodeTypeFactory, DefaultNodeTypeFactory>(); composition.Register<INavigationProvider<INavigationElement>, UmbracoNavigationProvider<INavigationElement>>(); composition.Register<IUmbracoNodeService, UmbracoNodeService>(); composition.Register<INavigationFilter, TemplateOrRedirectFilter>(); } } }
mit
C#
1d0afd15b666f370854eded251f7dfb313d6aed5
Fix typo.
JohanLarsson/Gu.State,JohanLarsson/Gu.State,JohanLarsson/Gu.ChangeTracking
Gu.State/Internals/Reflection/IGetterAndSetter.cs
Gu.State/Internals/Reflection/IGetterAndSetter.cs
namespace Gu.State { using System; using System.Reflection; /// <summary>Provides functionlaity for getting and setting values for a member.</summary> internal interface IGetterAndSetter { /// <summary>Gets the declaring type of the member.</summary> Type SourceType { get; } /// <summary>Gets the value type of the member.</summary> Type ValueType { get; } /// <summary> /// Gets a value indicating whether the member is init only. /// For a field this means private readonly... /// For a property this means public int Value { get; }. /// </summary> bool IsInitOnly { get; } /// <summary>Gets the member.</summary> MemberInfo Member { get; } void SetValue(object source, object value); object GetValue(object source); /// <summary> /// Check if x and y can be equated by value semantics. /// This can be if: /// 1) either or both are null. /// 2) They are the same instance. /// 3) They are of types implementing IEquatable /// 4) An IEqualityComparer if provided for the type. /// </summary> /// <param name="x">The x value.</param> /// <param name="y">The y value.</param> /// <param name="settings">The settings.</param> /// <param name="equal">True if <paramref name="x"/> and <paramref name="y"/> are equal.</param> /// <param name="xv">The x value fetched for the member.</param> /// <param name="yv">The y value fetched for the member.</param> /// <returns>True if equality could be determined for <paramref name="x"/> and <paramref name="y"/>.</returns> bool TryGetValueEquals(object x, object y, MemberSettings settings, out bool equal, out object xv, out object yv); void CopyValue(object source, object target); } }
namespace Gu.State { using System; using System.Reflection; /// <summary>Provides functionlaity for getting and setting values for a member.</summary> internal interface IGetterAndSetter { /// <summary>Gets the declaring type of the member.</summary> Type SourceType { get; } /// <summary>Gets the value type of the member.</summary> Type ValueType { get; } /// <summary> /// Gets a value indicating whether the member is init only. /// For a field this means private readonly... /// For a property this means public int Value { get; }. /// </summary> bool IsInitOnly { get; } /// <summary>Gets the member.</summary> MemberInfo Member { get; } void SetValue(object source, object value); object GetValue(object source); /// <summary> /// Check if x and y can be equated by value semantics. /// This can be if: /// 1) either or both are null. /// 2) They are the same insatnce. /// 3) They are of types implementing IEquatable /// 4) An IEqualityComparer if provided for the type. /// </summary> /// <param name="x">The x value.</param> /// <param name="y">The y value.</param> /// <param name="settings">The settings.</param> /// <param name="equal">True if <paramref name="x"/> and <paramref name="y"/> are equal.</param> /// <param name="xv">The x value fetched for the member.</param> /// <param name="yv">The y value fetched for the member.</param> /// <returns>True if equality could be determined for <paramref name="x"/> and <paramref name="y"/>.</returns> bool TryGetValueEquals(object x, object y, MemberSettings settings, out bool equal, out object xv, out object yv); void CopyValue(object source, object target); } }
mit
C#
02be323fb3f4d9b3b274bec4393285d15b1cf8fd
Update source reader tests according to new specs
IfElseSwitch/hc-engine,IfElseSwitch/hc-engine
HCEngine/HCEngine.UnitTesting/SourceReaderTest.cs
HCEngine/HCEngine.UnitTesting/SourceReaderTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using HCEngine.Default; namespace HCEngine.UnitTesting { [TestClass] public class SourceReaderTest { [TestMethod] public void TestReadingNormal() { string[] expected = new string[] { "reading", "this", "should", "be", "ok" }; string compact = "reading this should be ok"; string padded = " reading this should be ok \n"; ISourceReader reader = new SourceReader(); reader.Initialize(compact); TestReader(reader, expected); reader.Initialize(padded); TestReader(reader, expected); } void TestReader(ISourceReader reader, string[] expected) { foreach (string str in expected) { Assert.IsFalse(reader.ReadingComplete); Assert.IsNotNull(reader.LastKeyword); Assert.AreEqual(str, reader.LastKeyword); reader.ReadNext(); } } [TestMethod] public void TestReadingStrings() { string[] expected = new string[] { "reading", "\"this should\"", "be", "ok" }; string compact = "reading \"this should\" be ok"; string padded = " reading \"this should\" be ok \n"; ISourceReader reader = new SourceReader(); reader.Initialize(compact); TestReader(reader, expected); reader.Initialize(padded); TestReader(reader, expected); } [TestMethod] public void TestReadingLines() { string source = "reading\nthis should\nbe ok"; ISourceReader reader = new SourceReader(); reader.Initialize(source); Assert.AreEqual(reader.Line, 1); Assert.AreEqual(reader.Column, 1); reader.ReadNext(); Assert.AreEqual(reader.Line, 2); Assert.AreEqual(reader.Column, 1); reader.ReadNext(); Assert.AreEqual(reader.Line, 2); Assert.AreEqual(reader.Column, 6); reader.ReadNext(); Assert.AreEqual(reader.Line, 3); Assert.AreEqual(reader.Column, 1); reader.ReadNext(); Assert.AreEqual(reader.Line, 3); Assert.AreEqual(reader.Column, 3); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using HCEngine.Default; namespace HCEngine.UnitTesting { [TestClass] public class SourceReaderTest { [TestMethod] public void TestReadingNormal() { string[] expected = new string[] { "reading", "this", "should", "be", "ok" }; string compact = "reading this should be ok"; string padded = " reading this should be ok \n"; ISourceReader reader = new SourceReader(); reader.Initialize(compact); TestReader(reader, expected); reader.Initialize(padded); TestReader(reader, expected); } void TestReader(ISourceReader reader, string[] expected) { foreach (string str in expected) { Assert.IsFalse(reader.ReadingComplete); Assert.IsNotNull(reader.LastKeyword); Assert.AreEqual(str, reader.LastKeyword); reader.ReadNext(); } } [TestMethod] public void TestReadingStrings() { string[] expected = new string[] { "reading", "\"this should\"", "be", "ok" }; string compact = "reading \"this should\" be ok"; string padded = " reading \"this should\" be ok \n"; ISourceReader reader = new SourceReader(); reader.Initialize(compact); TestReader(reader, expected); reader.Initialize(padded); TestReader(reader, expected); } } }
mit
C#
b76fbbf8e51014995bb2e6aed0735430abbe3af6
Fix crew to reference by BroeCrewId
MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site
HeadRaceTiming-Site/Controllers/CrewController.cs
HeadRaceTiming-Site/Controllers/CrewController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using HeadRaceTimingSite.Models; using Microsoft.EntityFrameworkCore; namespace HeadRaceTimingSite.Controllers { public class CrewController : BaseController { public CrewController(TimingSiteContext context) : base(context) { } public async Task<IActionResult> Details(int? id) { Crew crew = await _context.Crews.Include(c => c.Competition) .Include(c => c.Athletes) .Include("Athletes.Athlete") .Include("Awards.Award") .SingleOrDefaultAsync(c => c.BroeCrewId == id); return View(crew); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using HeadRaceTimingSite.Models; using Microsoft.EntityFrameworkCore; namespace HeadRaceTimingSite.Controllers { public class CrewController : BaseController { public CrewController(TimingSiteContext context) : base(context) { } public async Task<IActionResult> Details(int? id) { Crew crew = await _context.Crews.Include(c => c.Competition) .Include(c => c.Athletes) .Include("Athletes.Athlete") .Include("Awards.Award") .SingleOrDefaultAsync(c => c.CrewId == id); return View(crew); } } }
mit
C#
eaffe33a22a86ee59ed07f4ad79dcd254a664d09
Update DeliveryClientFactory.cs
Kentico/delivery-sdk-net,Kentico/Deliver-.NET-SDK
Kentico.Kontent.Delivery/DeliveryClientFactory.cs
Kentico.Kontent.Delivery/DeliveryClientFactory.cs
using System; using Kentico.Kontent.Delivery.Abstractions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Kentico.Kontent.Delivery { /// <summary> /// A factory class for <see cref="IDeliveryClient"/> /// </summary> public class DeliveryClientFactory : IDeliveryClientFactory { private readonly IServiceProvider _serviceProvider; private string _notImplementExceptionMessage = "The default implementation does not support retrieving clients by name. Please use the Kentico.Kontent.Delivery.Extensions.Autofac.DependencyInjection or implement your own factory."; /// <summary> /// Initializes a new instance of the <see cref="DeliveryClientFactory"/> class. /// </summary> /// <param name="serviceProvider">An <see cref="IServiceProvider"/> instance.</param> public DeliveryClientFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc /> public IDeliveryClient Get(string name) => throw new NotImplementedException(_notImplementExceptionMessage); /// <inheritdoc /> public IDeliveryClient Get() { return _serviceProvider.GetRequiredService<IDeliveryClient>(); } /// <summary> /// Creates a <see cref="IDeliveryClient"/> instance manually. /// </summary> /// <param name="options">A <see cref="DeliveryOptions"/></param> /// <param name="modelProvider">A <see cref="IModelProvider"/> instance.</param> /// <param name="retryPolicyProvider">A <see cref="IRetryPolicyProvider"/> instance.</param> /// <param name="typeProvider">A <see cref="ITypeProvider"/> instance.</param> /// <param name="deliveryHttpClient">A <see cref="IDeliveryHttpClient"/> instance.</param> /// <param name="jsonSerializer">A <see cref="JsonSerializer"/> instance.</param> /// <returns></returns> public static IDeliveryClient Create( IOptionsMonitor<DeliveryOptions> options, IModelProvider modelProvider, IRetryPolicyProvider retryPolicyProvider, ITypeProvider typeProvider, IDeliveryHttpClient deliveryHttpClient, JsonSerializer jsonSerializer) { return new DeliveryClient(options, modelProvider, retryPolicyProvider, typeProvider, deliveryHttpClient, jsonSerializer); } } }
using System; using Kentico.Kontent.Delivery.Abstractions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Kentico.Kontent.Delivery { /// <summary> /// A factory class for <see cref="IDeliveryClient"/> /// </summary> public class DeliveryClientFactory : IDeliveryClientFactory { private readonly IServiceProvider _serviceProvider; private string _notImplementExceptionMessage = "The default implementation does not support retrieving clients by name.Use the Kentico.Kontent.Delivery.Extensions.Autofac.DependencyInjection or implement your own factory."; /// <summary> /// Initializes a new instance of the <see cref="DeliveryClientFactory"/> class. /// </summary> /// <param name="serviceProvider">An <see cref="IServiceProvider"/> instance.</param> public DeliveryClientFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc /> public IDeliveryClient Get(string name) => throw new NotImplementedException(_notImplementExceptionMessage); /// <inheritdoc /> public IDeliveryClient Get() { return _serviceProvider.GetRequiredService<IDeliveryClient>(); } /// <summary> /// Creates a <see cref="IDeliveryClient"/> instance manually. /// </summary> /// <param name="options">A <see cref="DeliveryOptions"/></param> /// <param name="modelProvider">A <see cref="IModelProvider"/> instance.</param> /// <param name="retryPolicyProvider">A <see cref="IRetryPolicyProvider"/> instance.</param> /// <param name="typeProvider">A <see cref="ITypeProvider"/> instance.</param> /// <param name="deliveryHttpClient">A <see cref="IDeliveryHttpClient"/> instance.</param> /// <param name="jsonSerializer">A <see cref="JsonSerializer"/> instance.</param> /// <returns></returns> public static IDeliveryClient Create( IOptionsMonitor<DeliveryOptions> options, IModelProvider modelProvider, IRetryPolicyProvider retryPolicyProvider, ITypeProvider typeProvider, IDeliveryHttpClient deliveryHttpClient, JsonSerializer jsonSerializer) { return new DeliveryClient(options, modelProvider, retryPolicyProvider, typeProvider, deliveryHttpClient, jsonSerializer); } } }
mit
C#
0d3d889e480a3e1a33d4b0319d75a20858cc193b
fix the position
Steguer/MTLGJ,Steguer/MTLGJ
Assets/Scripts/Gui.cs
Assets/Scripts/Gui.cs
using UnityEngine; using System.Collections; public class Gui : MonoBehaviour { public float timer = 100; private GameObject[] playerArray; private float timeBuffer; // Use this for initialization void Start () { playerArray = GameObject.FindGameObjectsWithTag("Player"); timeBuffer = Time.time; } // Update is called once per frame void Update () { if (Time.time - timeBuffer >= 1) { timer -= Time.time - timeBuffer; timeBuffer = Time.time; } } void OnGUI() { for(int i = 0; i < playerArray.Length; ++i) { if(playerArray[i] != null) { switch(i) { case 0: GUILayout.BeginArea (new Rect (0, 0, Screen.width/5, Screen.height/10)); GUI.color = Color.cyan; break; case 1: GUILayout.BeginArea (new Rect (Screen.width-Screen.width/5, 0, Screen.width/5, Screen.height/10)); GUI.color = Color.green; break; case 2: GUILayout.BeginArea (new Rect (0, Screen.height-Screen.height/10, Screen.width/5, Screen.height/10)); GUI.color = Color.yellow; break; case 3: GUILayout.BeginArea (new Rect (Screen.width-Screen.width/5, Screen.height-Screen.height/10, Screen.width/5, Screen.height/10)); GUI.color = Color.magenta; break; default: GUILayout.BeginArea (new Rect (0,0,Screen.width/5,Screen.height/10)); break; } GUILayout.BeginHorizontal(); GUILayout.Box("Steps: " + playerArray[i].GetComponent<StepCounter>().compteur); GUILayout.EndHorizontal(); GUILayout.EndArea(); } } GUILayout.BeginArea(new Rect(Screen.width/2 - Screen.width/10, Screen.height/100, Screen.width/5, Screen.height/10)); GUI.color = Color.white; if(timer <= 0) { GUILayout.Box("Try again"); } else { GUILayout.Box(""+(int)timer); } GUILayout.EndArea(); } }
using UnityEngine; using System.Collections; public class Gui : MonoBehaviour { public float timer = 100; private GameObject[] playerArray; private float timeBuffer; // Use this for initialization void Start () { playerArray = GameObject.FindGameObjectsWithTag("Player"); timeBuffer = Time.time; } // Update is called once per frame void Update () { if (Time.time - timeBuffer >= 1) { timer -= Time.time - timeBuffer; timeBuffer = Time.time; } } void OnGUI() { for(int i = 0; i < playerArray.Length; ++i) { if(playerArray[i] != null) { switch(i) { case 0: GUILayout.BeginArea (new Rect (0, 0, Screen.width/5, Screen.height/10)); GUI.color = Color.cyan; break; case 1: GUILayout.BeginArea (new Rect (Screen.width-Screen.width/5, 0, Screen.width/5, Screen.height/10)); GUI.color = Color.green; break; case 2: GUILayout.BeginArea (new Rect (0, Screen.height-Screen.width/5, Screen.width/5, Screen.height/10)); GUI.color = Color.yellow; break; case 3: GUILayout.BeginArea (new Rect (Screen.width-Screen.width/5, Screen.height-Screen.width/5, Screen.width/5, Screen.height/10)); GUI.color = Color.magenta; break; default: GUILayout.BeginArea (new Rect (0,0,Screen.width/5,Screen.height/10)); break; } GUILayout.BeginHorizontal(); GUILayout.Box("Steps: " + playerArray[i].GetComponent<StepCounter>().compteur); GUILayout.EndHorizontal(); GUILayout.EndArea(); } } GUILayout.BeginArea(new Rect(Screen.width/2 - Screen.width/10, Screen.height/100, Screen.width/5, Screen.height/10)); GUI.color = Color.white; if(timer <= 0) { GUILayout.Box("Try again"); } else { GUILayout.Box(""+(int)timer); } GUILayout.EndArea(); } }
mit
C#
886bee57c85901d09f815da232a4fb5969e01a4c
Mark the empty method detour test as NoInlining
AngelDE98/MonoMod,0x0ade/MonoMod
MonoMod.UnitTest/RuntimeDetour/DetourEmptyTest.cs
MonoMod.UnitTest/RuntimeDetour/DetourEmptyTest.cs
#pragma warning disable CS1720 // Expression will always cause a System.NullReferenceException because the type's default value is null #pragma warning disable xUnit1013 // Public method should be marked as test using Xunit; using MonoMod.RuntimeDetour; using System; using System.Reflection; using System.Runtime.CompilerServices; using MonoMod.Utils; using System.Reflection.Emit; using System.Text; namespace MonoMod.UnitTest { [Collection("RuntimeDetour")] public class DetourEmptyTest { private bool DidNothing = true; [Fact] public void TestDetoursEmpty() { // The following use cases are not meant to be usage examples. // Please take a look at DetourTest and HookTest instead. Assert.True(DidNothing); using (Hook h = new Hook( // .GetNativeStart() to enforce a native detour. typeof(DetourEmptyTest).GetMethod("DoNothing"), new Action<DetourEmptyTest>(self => { DidNothing = false; }) )) { DoNothing(); Assert.False(DidNothing); } } [MethodImpl(MethodImplOptions.NoInlining)] public void DoNothing() { } } }
#pragma warning disable CS1720 // Expression will always cause a System.NullReferenceException because the type's default value is null #pragma warning disable xUnit1013 // Public method should be marked as test using Xunit; using MonoMod.RuntimeDetour; using System; using System.Reflection; using System.Runtime.CompilerServices; using MonoMod.Utils; using System.Reflection.Emit; using System.Text; namespace MonoMod.UnitTest { [Collection("RuntimeDetour")] public class DetourEmptyTest { private bool DidNothing = true; [Fact] public void TestDetoursEmpty() { // The following use cases are not meant to be usage examples. // Please take a look at DetourTest and HookTest instead. Assert.True(DidNothing); using (Hook h = new Hook( // .GetNativeStart() to enforce a native detour. typeof(DetourEmptyTest).GetMethod("DoNothing"), new Action<DetourEmptyTest>(self => { DidNothing = false; }) )) { DoNothing(); Assert.False(DidNothing); } } public void DoNothing() { } } }
mit
C#
d38cc62c354e51bb6ab8f85fe0c470e7cd7bfecc
Disable GenerateSchemaTaskTest.cs
Ackara/Daterpillar
tests/MSTest.Daterpillar/Tests/GenerateSchemaTaskTest.cs
tests/MSTest.Daterpillar/Tests/GenerateSchemaTaskTest.cs
using Ackara.Daterpillar.MSBuild; using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; using System; using System.IO; using System.Linq; using System.Reflection; namespace MSTest.Daterpillar.Tests { [TestClass] public class GenerateSchemaTaskTest { //[TestMethod] public void Execute_should_generate_a_xml_schema_file_when_invoked() { // Arrange var assemblyFile = Assembly.GetExecutingAssembly().Location; var sut = new GenerateSchemaTask() { AssemblyFile = assemblyFile }; // Act if (File.Exists(sut.SchemaPath)) File.Delete(sut.SchemaPath); sut.Execute(); string content = File.ReadAllText(sut.SchemaPath); bool schemaWasGenerated = Helper.ValidateXml(content, out string errorMsg); // Assert content.ShouldNotBeNullOrWhiteSpace(); schemaWasGenerated.ShouldBeTrue(errorMsg); } } }
using Ackara.Daterpillar.MSBuild; using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; using System; using System.IO; using System.Linq; using System.Reflection; namespace MSTest.Daterpillar.Tests { [TestClass] public class GenerateSchemaTaskTest { [TestMethod] public void Execute_should_generate_a_xml_schema_file_when_invoked() { // Arrange var assemblyFile = Assembly.GetExecutingAssembly().Location; var sut = new GenerateSchemaTask() { AssemblyFile = assemblyFile }; // Act if (File.Exists(sut.SchemaPath)) File.Delete(sut.SchemaPath); sut.Execute(); string content = File.ReadAllText(sut.SchemaPath); bool schemaWasGenerated = Helper.ValidateXml(content, out string errorMsg); // Assert content.ShouldNotBeNullOrWhiteSpace(); schemaWasGenerated.ShouldBeTrue(errorMsg); } } }
mit
C#
ebb847ff40fd173a45dd4de6c2a7e1e442ba3c35
Test commit for identity.
predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus
Sensus.Tests.AppCenter.Shared/UnitTestsFixture.cs
Sensus.Tests.AppCenter.Shared/UnitTestsFixture.cs
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.UITest; using NUnit.Framework; using System; using System.Linq; namespace Sensus.Tests.AppCenter.Shared { [TestFixture] public class UnitTestsFixture { private IApp _app; [SetUp] public void BeforeEachTest() { _app = ConfigureApp #if __IOS__ .iOS #elif __ANDROID__ .Android #endif .StartApp(); } [Test] public void UnitTests() { // wait for the tests to complete TimeSpan timeout = TimeSpan.FromMinutes(5); #if __ANDROID__ string resultsStr = _app.WaitForElement(c => c.All().Marked("unit-test-results"), timeout: timeout).FirstOrDefault()?.Text; #elif __IOS__ _app.WaitForElement(c => c.ClassFull("UILabel").Text("Results"), timeout: timeout); string resultsStr = _app.Query(c => c.ClassFull("UILabel")).SingleOrDefault(c => c.Text.StartsWith("Passed"))?.Text; #endif Assert.NotNull(resultsStr); Console.Out.WriteLine("Test results: " + resultsStr); string[] results = resultsStr.Split(); Assert.AreEqual(results.Length, 1); int testsPassed = int.Parse(results[0].Split(':')[1]); int totalTests; #if __IOS__ totalTests = 154; #elif __ANDROID__ totalTests = 155; #endif Assert.AreEqual(testsPassed, totalTests); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.UITest; using NUnit.Framework; using System; using System.Linq; namespace Sensus.Tests.AppCenter.Shared { [TestFixture] public class UnitTestsFixture { private IApp _app; [SetUp] public void BeforeEachTest() { _app = ConfigureApp #if __IOS__ .iOS #elif __ANDROID__ .Android #endif .StartApp(); } [Test] public void UnitTests() { TimeSpan timeout = TimeSpan.FromMinutes(5); #if __ANDROID__ string resultsStr = _app.WaitForElement(c => c.All().Marked("unit-test-results"), timeout: timeout).FirstOrDefault()?.Text; #elif __IOS__ _app.WaitForElement(c => c.ClassFull("UILabel").Text("Results"), timeout: timeout); string resultsStr = _app.Query(c => c.ClassFull("UILabel")).SingleOrDefault(c => c.Text.StartsWith("Passed"))?.Text; #endif Assert.NotNull(resultsStr); Console.Out.WriteLine("Test results: " + resultsStr); string[] results = resultsStr.Split(); Assert.AreEqual(results.Length, 1); int testsPassed = int.Parse(results[0].Split(':')[1]); int totalTests; #if __IOS__ totalTests = 154; #elif __ANDROID__ totalTests = 155; #endif Assert.AreEqual(testsPassed, totalTests); } } }
apache-2.0
C#
0075fc88e610237ac80bf3be8080558f46f325b2
Add public property
StefanoFiumara/Harry-Potter-Unity
Assets/Scripts/HarryPotterUnity/Cards/BasicBehavior/DirectDamageSpell.cs
Assets/Scripts/HarryPotterUnity/Cards/BasicBehavior/DirectDamageSpell.cs
using System.Collections.Generic; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.BasicBehavior { public class DirectDamageSpell : BaseSpell { [Header("Direct Damage Spell Settings"), Space(10)] [UsedImplicitly, SerializeField] private int _damageAmount; public int DamageAmount { get { return _damageAmount; } } protected override void SpellAction(List<BaseCard> targets) { Player.OppositePlayer.TakeDamage(_damageAmount); } } }
using System.Collections.Generic; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.BasicBehavior { public class DirectDamageSpell : BaseSpell { [Header("Direct Damage Spell Settings"), Space(10)] [UsedImplicitly, SerializeField] private int _damageAmount; protected override void SpellAction(List<BaseCard> targets) { Player.OppositePlayer.TakeDamage(_damageAmount); } } }
mit
C#
0cafa81aa282031c7f934c178545cb0bff322b98
bump version
Fody/Obsolete
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("1.4.2.0")] [assembly: AssemblyFileVersion("1.4.2.0")]
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("1.4.1.0")] [assembly: AssemblyFileVersion("1.4.1.0")]
mit
C#
6f92b46999af97d5d43285679a23aa79b00d79f7
Make user voice content provider work with https.
e10/JabbR,ClarkL/test09jabbr,test0925/test0925,mogultest2/Project92104,aapttester/jack12051317,LookLikeAPro/JabbR,M-Zuber/JabbR,mogulTest1/Project13171109,test0925/test0925,mogulTest1/Project13231109,LookLikeAPro/JabbR,meebey/JabbR,AAPT/jean0226case1322,ClarkL/1317on17jabbr,MogulTestOrg914/Project91407,mogulTest1/Project13231113,mogulTest1/Project13231109,clarktestkudu1029/test08jabbr,mogulTest1/Project13171106,v-mohua/TestProject91001,mogulTest1/ProjectfoIssue6,MogulTestOrg2/JabbrApp,mogulTest1/Project13171205,KuduApps/TestDeploy123,Org1106/Project13221106,meebey/JabbR,mogultest2/Project13171008,KuduApps/TestDeploy123,mogulTest1/Project91404,MogulTestOrg2/JabbrApp,Org1106/Project13221106,mogulTest1/Project13171024,mogulTest1/Project13171024,lukehoban/JabbR,mogulTest1/Project91009,mogulTest1/ProjectfoIssue6,mogulTest1/MogulVerifyIssue5,mogulTest1/Project91101,mogultest2/Project13171008,mogultest2/Project92105,ClarkL/test09jabbr,mogultest2/Project13231008,M-Zuber/JabbR,mogultest2/Project92109,mogulTest1/Project91105,ajayanandgit/JabbR,CrankyTRex/JabbRMirror,JabbR/JabbR,MogulTestOrg9221/Project92108,AAPT/jean0226case1322,mogulTest1/Project90301,mogulTest1/ProjectJabbr01,fuzeman/vox,kudutest/FaizJabbr,mogulTest1/ProjectVerify912,mogulTest1/Project13171109,Org1106/Project13221113,mogulTest1/Project91409,mogulTest1/Project90301,meebey/JabbR,18098924759/JabbR,mogultest2/Project13171210,lukehoban/JabbR,e10/JabbR,18098924759/JabbR,mogulTest1/Project13231106,borisyankov/JabbR,mogultest2/Project13171010,LookLikeAPro/JabbR,mogulTest1/Project91009,yadyn/JabbR,mogultest2/Project13171010,mogulTest1/Project91101,mogultest2/Project13231008,mogulTest1/ProjectVerify912,timgranstrom/JabbR,mogulTest1/Project91409,JabbR/JabbR,borisyankov/JabbR,mogulTest1/Project91404,mogulTest1/Project13171205,mogulTest1/MogulVerifyIssue5,fuzeman/vox,mogultest2/Project92109,v-mohua/TestProject91001,Createfor1322/jessica0122-1322,mogultest2/Project13171210,yadyn/JabbR,SonOfSam/JabbR,mogulTest1/Project91105,mzdv/JabbR,MogulTestOrg911/Project91104,ClarkL/1323on17jabbr-,borisyankov/JabbR,mogulTest1/Project13171113,mogulTest1/Project13161127,ajayanandgit/JabbR,aapttester/jack12051317,lukehoban/JabbR,MogulTestOrg914/Project91407,CrankyTRex/JabbRMirror,Createfor1322/jessica0122-1322,CrankyTRex/JabbRMirror,MogulTestOrg1008/Project13221008,MogulTestOrg9221/Project92108,timgranstrom/JabbR,yadyn/JabbR,mogulTest1/Project13171009,mogulTest1/Project13231106,fuzeman/vox,mogulTest1/Project13161127,huanglitest/JabbRTest2,huanglitest/JabbRTest2,mogulTest1/Project13231113,MogulTestOrg/JabbrApp,ClarkL/1317on17jabbr,ClarkL/new09,Org1106/Project13221113,mogulTest1/Project13231205,mogulTest1/Project13171106,mogulTest1/Project13171009,mzdv/JabbR,mogulTest1/Project13231212,SonOfSam/JabbR,clarktestkudu1029/test08jabbr,MogulTestOrg/JabbrApp,ClarkL/new09,mogulTest1/Project13231212,ClarkL/new1317,mogulTest1/Project13231213,mogulTest1/Project13231213,MogulTestOrg1008/Project13221008,mogulTest1/ProjectJabbr01,mogulTest1/Project13231205,ClarkL/new1317,mogulTest1/Project13171113,ClarkL/1323on17jabbr-,kudutest/FaizJabbr,MogulTestOrg911/Project91104,mogultest2/Project92104,huanglitest/JabbRTest2,mogultest2/Project92105
JabbR/ContentProviders/UserVoiceContentProvider.cs
JabbR/ContentProviders/UserVoiceContentProvider.cs
using System; using System.Threading.Tasks; using JabbR.ContentProviders.Core; using JabbR.Infrastructure; namespace JabbR.ContentProviders { public class UserVoiceContentProvider : CollapsibleContentProvider { private static readonly string _uservoiceAPIURL = "https://{0}/api/v1/oembed.json?url={1}"; protected override Task<ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { return FetchArticle(request.RequestUri).Then(article => { return new ContentProviderResult() { Title = article.title, Content = article.html }; }); } private static Task<dynamic> FetchArticle(Uri url) { return Http.GetJsonAsync(String.Format(_uservoiceAPIURL, url.Host, url.AbsoluteUri)); } public override bool IsValidContent(Uri uri) { return uri.Host.IndexOf("uservoice.com", StringComparison.OrdinalIgnoreCase) >= 0; } } }
using System; using System.Threading.Tasks; using JabbR.ContentProviders.Core; using JabbR.Infrastructure; namespace JabbR.ContentProviders { public class UserVoiceContentProvider : CollapsibleContentProvider { private static readonly string _uservoiceAPIURL = "http://{0}/api/v1/oembed.json?url={1}"; protected override Task<ContentProviderResult> GetCollapsibleContent(ContentProviderHttpRequest request) { return FetchArticle(request.RequestUri).Then(article => { return new ContentProviderResult() { Title = article.title, Content = article.html }; }); } private static Task<dynamic> FetchArticle(Uri url) { return Http.GetJsonAsync(String.Format(_uservoiceAPIURL, url.Host, url.AbsoluteUri)); } public override bool IsValidContent(Uri uri) { return uri.Host.IndexOf("uservoice.com", StringComparison.OrdinalIgnoreCase) >= 0; } } }
mit
C#
cb3f142a849bd21547f6256501ee80ab379dd983
Update AutoMapperConfiguration.cs - update SkillEntity mapping
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.BusinessLayer/AutoMapperConfiguration.cs
NinjaHive.BusinessLayer/AutoMapperConfiguration.cs
using AutoMapper; using NinjaHive.Contract.DTOs; using NinjaHive.Domain; namespace NinjaHive.BusinessLayer { public class AutoMapperConfiguration { public static void Configure() { Mapper.CreateMap<EquipmentItemEntity, EquipmentItem>() .ForMember(destination => destination.UpgradeElement, options => options.MapFrom(source => source.IsUpgrader)) .ForMember(destination => destination.CraftingElement, options => options.MapFrom(source => source.IsCrafter)) .ForMember(destination => destination.QuestItem, options => options.MapFrom(source => source.IsQuestItem)); Mapper.CreateMap<SkillEntity, Skill>() .ForMember(destination => destination.TargetCount, options => options.MapFrom(source => source.Targets)) .ForMember(destination => destination.StatInfoId, options => options.MapFrom(source => source.StatInfo.Id)); Mapper.CreateMap<StatInfoEntity, StatInfo>(); } }; }
using AutoMapper; using NinjaHive.Contract.DTOs; using NinjaHive.Domain; namespace NinjaHive.BusinessLayer { public class AutoMapperConfiguration { public static void Configure() { Mapper.CreateMap<EquipmentItemEntity, EquipmentItem>() .ForMember(destination => destination.UpgradeElement, options => options.MapFrom(source => source.IsUpgrader)) .ForMember(destination => destination.CraftingElement, options => options.MapFrom(source => source.IsCrafter)) .ForMember(destination => destination.QuestItem, options => options.MapFrom(source => source.IsQuestItem)); Mapper.CreateMap<SkillEntity, Skill>() .ForMember(destination => destination.TargetCount, options => options.MapFrom(source => source.Targets)); Mapper.CreateMap<StatInfoEntity, StatInfo>(); } }; }
apache-2.0
C#
81d49852455c85b58a9efac2acda25b0357d3a28
fix silly null ref mistake
dabutvin/ImgBot,dabutvin/ImgBot,dabutvin/ImgBot
OpenPrFunction/OpenPr.cs
OpenPrFunction/OpenPr.cs
using System; using System.IO; using System.Threading.Tasks; using Common; using Common.Messages; using Common.TableModels; using Install; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; namespace OpenPrFunction { public static class OpenPr { [Singleton("{InstallationId}")] // https://github.com/Azure/azure-webjobs-sdk/wiki/Singleton#scenarios [FunctionName("OpenPr")] public static async Task Run( [QueueTrigger("openprmessage")]OpenPrMessage openPrMessage, [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation, ILogger logger, ExecutionContext context) { if (installation == null) { logger.LogError("No installation found for {InstallationId}", openPrMessage.InstallationId); throw new Exception($"No installation found for InstallationId: {openPrMessage.InstallationId}"); } var installationTokenParameters = new InstallationTokenParameters { AccessTokensUrl = string.Format(KnownGitHubs.AccessTokensUrlFormat, installation.InstallationId), AppId = KnownGitHubs.AppId, }; var installationToken = await InstallationToken.GenerateAsync( installationTokenParameters, File.OpenText(Path.Combine(context.FunctionDirectory, $"../{KnownGitHubs.AppPrivateKey}"))); logger.LogInformation("OpenPrFunction: Opening pull request for {Owner}/{RepoName}", installation.Owner, installation.RepoName); var id = await PullRequest.OpenAsync(new PullRequestParameters { Password = installationToken.Token, RepoName = installation.RepoName, RepoOwner = installation.Owner, }); if (id > 0) { logger.LogInformation("OpenPrFunction: Successfully opened pull request (#{PullRequestId}) for {Owner}/{RepoName}", id, installation.Owner, installation.RepoName); } } } }
using System; using System.IO; using System.Threading.Tasks; using Common; using Common.Messages; using Common.TableModels; using Install; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; namespace OpenPrFunction { public static class OpenPr { [Singleton("{InstallationId}")] // https://github.com/Azure/azure-webjobs-sdk/wiki/Singleton#scenarios [FunctionName("OpenPr")] public static async Task Run( [QueueTrigger("openprmessage")]OpenPrMessage openPrMessage, [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation, ILogger logger, ExecutionContext context) { if (installation == null) { logger.LogError("No installation found for {InstallationId}", installation.InstallationId); throw new Exception($"No installation found for InstallationId: {installation.InstallationId}"); } var installationTokenParameters = new InstallationTokenParameters { AccessTokensUrl = string.Format(KnownGitHubs.AccessTokensUrlFormat, installation.InstallationId), AppId = KnownGitHubs.AppId, }; var installationToken = await InstallationToken.GenerateAsync( installationTokenParameters, File.OpenText(Path.Combine(context.FunctionDirectory, $"../{KnownGitHubs.AppPrivateKey}"))); logger.LogInformation("OpenPrFunction: Opening pull request for {Owner}/{RepoName}", installation.Owner, installation.RepoName); var id = await PullRequest.OpenAsync(new PullRequestParameters { Password = installationToken.Token, RepoName = installation.RepoName, RepoOwner = installation.Owner, }); if (id > 0) { logger.LogInformation("OpenPrFunction: Successfully opened pull request (#{PullRequestId}) for {Owner}/{RepoName}", id, installation.Owner, installation.RepoName); } } } }
mit
C#
b66566e96d4f22d7e4351443ea8d999fd7f9bce7
Use explicit culture info rather than `null`
NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu
osu.Game/Overlays/Settings/Sections/SizeSlider.cs
osu.Game/Overlays/Settings/Sections/SizeSlider.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.Globalization; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings.Sections { /// <summary> /// A slider intended to show a "size" multiplier number, where 1x is 1.0. /// </summary> internal class SizeSlider<T> : OsuSliderBar<T> where T : struct, IEquatable<T>, IComparable<T>, IConvertible, IFormattable { public override LocalisableString TooltipText => Current.Value.ToString(@"0.##x", NumberFormatInfo.CurrentInfo); } }
// 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 osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings.Sections { /// <summary> /// A slider intended to show a "size" multiplier number, where 1x is 1.0. /// </summary> internal class SizeSlider<T> : OsuSliderBar<T> where T : struct, IEquatable<T>, IComparable<T>, IConvertible, IFormattable { public override LocalisableString TooltipText => Current.Value.ToString(@"0.##x", null); } }
mit
C#
e3b8d8ee1875d357db0198894fb8c475969f090e
Add support for overlay-coloured links
UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,ppy/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu
osu.Game/Online/Chat/DrawableLinkCompiler.cs
osu.Game/Online/Chat/DrawableLinkCompiler.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays; using osuTK; namespace osu.Game.Online.Chat { /// <summary> /// An invisible drawable that brings multiple <see cref="Drawable"/> pieces together to form a consumable clickable link. /// </summary> public class DrawableLinkCompiler : OsuHoverContainer { /// <summary> /// Each word part of a chat link (split for word-wrap support). /// </summary> public readonly List<Drawable> Parts; [Resolved(CanBeNull = true)] private OverlayColourProvider overlayColourProvider { get; set; } public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos)); protected override HoverClickSounds CreateHoverClickSounds(HoverSampleSet sampleSet) => new LinkHoverSounds(sampleSet, Parts); public DrawableLinkCompiler(IEnumerable<Drawable> parts) { Parts = parts.ToList(); } [BackgroundDependencyLoader] private void load(OsuColour colours) { IdleColour = overlayColourProvider?.Light2 ?? colours.Blue; } protected override IEnumerable<Drawable> EffectTargets => Parts; private class LinkHoverSounds : HoverClickSounds { private readonly List<Drawable> parts; public LinkHoverSounds(HoverSampleSet sampleSet, List<Drawable> parts) : base(sampleSet) { this.parts = parts; } public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos)); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Online.Chat { /// <summary> /// An invisible drawable that brings multiple <see cref="Drawable"/> pieces together to form a consumable clickable link. /// </summary> public class DrawableLinkCompiler : OsuHoverContainer { /// <summary> /// Each word part of a chat link (split for word-wrap support). /// </summary> public List<Drawable> Parts; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos)); protected override HoverClickSounds CreateHoverClickSounds(HoverSampleSet sampleSet) => new LinkHoverSounds(sampleSet, Parts); public DrawableLinkCompiler(IEnumerable<Drawable> parts) { Parts = parts.ToList(); } [BackgroundDependencyLoader] private void load(OsuColour colours) { IdleColour = colours.Blue; } protected override IEnumerable<Drawable> EffectTargets => Parts; private class LinkHoverSounds : HoverClickSounds { private readonly List<Drawable> parts; public LinkHoverSounds(HoverSampleSet sampleSet, List<Drawable> parts) : base(sampleSet) { this.parts = parts; } public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => parts.Any(d => d.ReceivePositionalInputAt(screenSpacePos)); } } }
mit
C#
24494db95ddd6c6b102400f7be3ecf9e39ab696b
Update CrossSettings.cs
LostBalloon1/Xamarin.Plugins,JC-Chris/Xamarin.Plugins,labdogg1003/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins,monostefan/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins,tim-hoff/Xamarin.Plugins
Settings/Refractored.Xam.Settings/CrossSettings.cs
Settings/Refractored.Xam.Settings/CrossSettings.cs
/* * MvxSettings: * Copyright (C) 2014 Refractored: * * Contributors: * http://github.com/JamesMontemagno * * 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. * * Original concept for Internal IoC came from: http://pclstorage.codeplex.com under Microsoft Public License (Ms-PL) * */ using System; using Refractored.Xam.Settings.Abstractions; namespace Refractored.Xam.Settings { public static class CrossSettings { static Lazy<ISettings> settings = new Lazy<ISettings>(() => CreateSettings(), System.Threading.LazyThreadSafetyMode.PublicationOnly); public static ISettings Current { get { ISettings ret = settings.Value; if (ret == null) { throw NotImplementedInReferenceAssembly(); } return ret; } } static ISettings CreateSettings() { #if PORTABLE return null; #else return new Settings(); #endif } internal static Exception NotImplementedInReferenceAssembly() { return new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the Xam.Plugins.Settings NuGet package from your main application project in order to reference the platform-specific implementation."); } } }
/* * MvxSettings: * Copyright (C) 2014 Refractored: * * Contributors: * http://github.com/JamesMontemagno * * 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. * * Original concept for Internal IoC came from: http://pclstorage.codeplex.com under Microsoft Public License (Ms-PL) * */ using System; using Refractored.Xam.Settings.Abstractions; namespace Refractored.Xam.Settings { public static class CrossSettings { static Lazy<ISettings> settings = new Lazy<ISettings>(() => CreateSettings(), System.Threading.LazyThreadSafetyMode.PublicationOnly); /// <summary> /// The implementation of <see cref="IFileSystem"/> for the current platform /// </summary> public static ISettings Current { get { ISettings ret = settings.Value; if (ret == null) { throw NotImplementedInReferenceAssembly(); } return ret; } } static ISettings CreateSettings() { #if PORTABLE return null; #else return new Settings(); #endif } internal static Exception NotImplementedInReferenceAssembly() { return new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the PCLStorage NuGet package from your main application project in order to reference the platform-specific implementation."); } } }
mit
C#
5ab8c688da25178a6c0522b33288e4315b8a1d73
Fix baseline tests.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
tests/SideBySide/CharacterSetTests.cs
tests/SideBySide/CharacterSetTests.cs
using Dapper; #if !BASELINE using MySql.Data.Serialization; #endif using Xunit; namespace SideBySide { public class CharacterSetTests : IClassFixture<DatabaseFixture> { public CharacterSetTests(DatabaseFixture database) { m_database = database; } #if !BASELINE [Fact] public void MaxLength() { using (var reader = m_database.Connection.ExecuteReader(@"select coll.ID, cs.MAXLEN from information_schema.collations coll inner join information_schema.character_sets cs using(CHARACTER_SET_NAME);")) { while (reader.Read()) { var characterSet = (CharacterSet) reader.GetInt32(0); var maxLength = reader.GetInt32(1); Assert.Equal(maxLength, SerializationUtility.GetBytesPerCharacter(characterSet)); } } } #endif readonly DatabaseFixture m_database; } }
using Dapper; using MySql.Data.Serialization; using Xunit; namespace SideBySide { public class CharacterSetTests : IClassFixture<DatabaseFixture> { public CharacterSetTests(DatabaseFixture database) { m_database = database; } #if !BASELINE [Fact] public void MaxLength() { using (var reader = m_database.Connection.ExecuteReader(@"select coll.ID, cs.MAXLEN from information_schema.collations coll inner join information_schema.character_sets cs using(CHARACTER_SET_NAME);")) { while (reader.Read()) { var characterSet = (CharacterSet) reader.GetInt32(0); var maxLength = reader.GetInt32(1); Assert.Equal(maxLength, SerializationUtility.GetBytesPerCharacter(characterSet)); } } } #endif readonly DatabaseFixture m_database; } }
mit
C#