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
9a17d2b1fd325410549b9c5cfb45d952cd24c602
remove log4net references, see if that helps fix bamboo
rryk/omp-server,AlphaStaxLLC/taiga,QuillLittlefeather/opensim-1,justinccdev/opensim,ft-/arribasim-dev-extras,justinccdev/opensim,bravelittlescientist/opensim-performance,TechplexEngineer/Aurora-Sim,Michelle-Argus/ArribasimExtract,Michelle-Argus/ArribasimExtract,rryk/omp-server,N3X15/VoxelSim,TechplexEngineer/Aurora-Sim,AlphaStaxLLC/taiga,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,allquixotic/opensim-autobackup,zekizeki/agentservice,ft-/arribasim-dev-tests,QuillLittlefeather/opensim-1,zekizeki/agentservice,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip,rryk/omp-server,RavenB/opensim,M-O-S-E-S/opensim,BogusCurry/arribasim-dev,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,ft-/arribasim-dev-tests,N3X15/VoxelSim,BogusCurry/arribasim-dev,intari/OpenSimMirror,BogusCurry/arribasim-dev,zekizeki/agentservice,TomDataworks/opensim,N3X15/VoxelSim,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-tests,AlphaStaxLLC/taiga,TomDataworks/opensim,BogusCurry/arribasim-dev,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,cdbean/CySim,ft-/opensim-optimizations-wip-tests,RavenB/opensim,intari/OpenSimMirror,TomDataworks/opensim,intari/OpenSimMirror,RavenB/opensim,AlphaStaxLLC/taiga,cdbean/CySim,OpenSimian/opensimulator,RavenB/opensim,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,bravelittlescientist/opensim-performance,ft-/arribasim-dev-extras,AlexRa/opensim-mods-Alex,cdbean/CySim,AlphaStaxLLC/taiga,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,OpenSimian/opensimulator,rryk/omp-server,Michelle-Argus/ArribasimExtract,TechplexEngineer/Aurora-Sim,justinccdev/opensim,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-tests,bravelittlescientist/opensim-performance,OpenSimian/opensimulator,AlphaStaxLLC/taiga,TomDataworks/opensim,zekizeki/agentservice,ft-/arribasim-dev-extras,rryk/omp-server,M-O-S-E-S/opensim,bravelittlescientist/opensim-performance,allquixotic/opensim-autobackup,bravelittlescientist/opensim-performance,ft-/arribasim-dev-extras,N3X15/VoxelSim,ft-/arribasim-dev-tests,N3X15/VoxelSim,intari/OpenSimMirror,OpenSimian/opensimulator,intari/OpenSimMirror,TomDataworks/opensim,ft-/opensim-optimizations-wip-tests,allquixotic/opensim-autobackup,rryk/omp-server,zekizeki/agentservice,TechplexEngineer/Aurora-Sim,cdbean/CySim,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip-extras,OpenSimian/opensimulator,ft-/arribasim-dev-extras,RavenB/opensim,cdbean/CySim,Michelle-Argus/ArribasimExtract,justinccdev/opensim,QuillLittlefeather/opensim-1,TomDataworks/opensim,ft-/opensim-optimizations-wip,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,AlexRa/opensim-mods-Alex,zekizeki/agentservice,Michelle-Argus/ArribasimExtract,cdbean/CySim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,intari/OpenSimMirror,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip,allquixotic/opensim-autobackup,AlexRa/opensim-mods-Alex,Michelle-Argus/ArribasimExtract,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-tests,AlphaStaxLLC/taiga,bravelittlescientist/opensim-performance,RavenB/opensim,ft-/arribasim-dev-tests,N3X15/VoxelSim,ft-/arribasim-dev-tests,M-O-S-E-S/opensim,AlphaStaxLLC/taiga,justinccdev/opensim,M-O-S-E-S/opensim,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,ft-/opensim-optimizations-wip-extras,justinccdev/opensim,QuillLittlefeather/opensim-1,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-tests,N3X15/VoxelSim,N3X15/VoxelSim,ft-/opensim-optimizations-wip-extras,AlexRa/opensim-mods-Alex,OpenSimian/opensimulator
OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs
OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Collections.Generic; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenSim.Framework; using OpenSim.Data.Tests; using OpenSim.Data.MySQL; using OpenSim.Region.Environment.Scenes; using OpenMetaverse; using log4net; namespace OpenSim.Data.MySQL.Tests { [TestFixture] public class MySQLInventoryTest : BasicInventoryTest { public string file; public string connect; [TestFixtureSetUp] public void Init() { SuperInit(); Assert.Ignore(); file = Path.GetTempFileName() + ".db"; connect = "URI=file:" + file + ",version=3"; } [TestFixtureTearDown] public void Cleanup() { } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Collections.Generic; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenSim.Framework; using OpenSim.Data.Tests; using OpenSim.Data.MySQL; using OpenSim.Region.Environment.Scenes; using OpenMetaverse; using log4net; namespace OpenSim.Data.MySQL.Tests { [TestFixture] public class MySQLInventoryTest : BasicInventoryTest { public string file; public string connect; [TestFixtureSetUp] public void Init() { SuperInit(); try { log4net.Config.XmlConfigurator.Configure(); } catch (Exception) { // I don't care, just leave log4net off } Assert.Ignore(); file = Path.GetTempFileName() + ".db"; connect = "URI=file:" + file + ",version=3"; } [TestFixtureTearDown] public void Cleanup() { db.Dispose(); } } }
bsd-3-clause
C#
774ee18ca62eaf1179b0bc939deeafb0949ed3a7
Bump version
rabbit-link/rabbit-link,rabbit-link/rabbit-link
src/RabbitLink/Properties/AssemblyInfo.cs
src/RabbitLink/Properties/AssemblyInfo.cs
#region Usings using System.Reflection; using System.Runtime.InteropServices; #endregion // 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("RabbitLink")] [assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RabbitLink")] [assembly: AssemblyCopyright("Copyright © Artur Kraev 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b2148830-a507-44a5-bc99-efda7f36e21d")] // 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.3.3.0")] [assembly: AssemblyFileVersion("0.3.3.0")]
#region Usings using System.Reflection; using System.Runtime.InteropServices; #endregion // 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("RabbitLink")] [assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RabbitLink")] [assembly: AssemblyCopyright("Copyright © Artur Kraev 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b2148830-a507-44a5-bc99-efda7f36e21d")] // 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.3.2.0")] [assembly: AssemblyFileVersion("0.3.2.0")]
mit
C#
447d4cf2e427ae6aec187d19d694ef159cdf063b
Add public API comments to UnityAutoMoqExtensions
thedersen/UnityAutoMoq,azarkevich/UnityAutoMoq,thedersen/UnityAutoMoq,thedersen/UnityAutoMoq,Henadz/UnityAutoMoq,azarkevich/UnityAutoMoq,Henadz/UnityAutoMoq,Henadz/UnityAutoMoq,azarkevich/UnityAutoMoq
src/UnityAutoMoq/UnityAutoMoqExtension.cs
src/UnityAutoMoq/UnityAutoMoqExtension.cs
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; namespace UnityAutoMoq { /// <summary> /// Provide extensions for Unity Auto Moq /// </summary> public class UnityAutoMoqExtension : UnityContainerExtension { private readonly UnityAutoMoqContainer autoMoqContainer; /// <summary> /// Initializes a new instance of the <see cref="UnityAutoMoqExtension"/> class. /// </summary> /// <param name="autoMoqContainer">The auto moq container.</param> public UnityAutoMoqExtension(UnityAutoMoqContainer autoMoqContainer) { this.autoMoqContainer = autoMoqContainer; } /// <summary> /// Initialize the <see cref="UnityAutoMoqExtension"/>. /// </summary> protected override void Initialize() { Context.Strategies.Add(new UnityAutoMoqBuilderStrategy(autoMoqContainer), UnityBuildStage.PreCreation); } } }
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; namespace UnityAutoMoq { /// <summary> /// Provide extensions for Unity Auto Moq /// </summary> public class UnityAutoMoqExtension : UnityContainerExtension { private readonly UnityAutoMoqContainer autoMoqContainer; public UnityAutoMoqExtension(UnityAutoMoqContainer autoMoqContainer) { this.autoMoqContainer = autoMoqContainer; } protected override void Initialize() { Context.Strategies.Add(new UnityAutoMoqBuilderStrategy(autoMoqContainer), UnityBuildStage.PreCreation); } } }
mit
C#
ebc8bb3bb7e8798590f3036414f5902645359df1
use random teste db name
ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian,ZA-PT/Obsidian
test/Obsidian.Persistence.Test/Repositories/MongoRepositoryTest.cs
test/Obsidian.Persistence.Test/Repositories/MongoRepositoryTest.cs
using MongoDB.Driver; using Obsidian.Domain.Shared; using System; namespace Obsidian.Persistence.Test.Repositories { public abstract class MongoRepositoryTest<TAggregate> : RepositoryTest<TAggregate> where TAggregate : class, IAggregateRoot { private static readonly Random rand = new Random(); private const string dbUri = "mongodb://127.0.0.1:27017"; private readonly string testDbName = "ObsidianTest_" + rand.Next(0, 1000000).ToString("X"); protected IMongoDatabase Database => new MongoClient(dbUri).GetDatabase(testDbName); protected override void CleanupDatabase() { var client = new MongoClient(dbUri); client.DropDatabase(testDbName); } } }
using MongoDB.Driver; using Obsidian.Domain.Shared; namespace Obsidian.Persistence.Test.Repositories { public abstract class MongoRepositoryTest<TAggregate> : RepositoryTest<TAggregate> where TAggregate : class, IAggregateRoot { private const string dbUri = "mongodb://127.0.0.1:27017"; private const string testDbName = "ObsidianTest"; protected IMongoDatabase Database => new MongoClient(dbUri).GetDatabase(testDbName); protected override void CleanupDatabase() { var client = new MongoClient(dbUri); client.DropDatabase(testDbName); } } }
apache-2.0
C#
ab510cea704fa4a210e73f90cad77d8325492f80
Add more features to vector 2 -> vector 3 conversion
PearMed/Pear-Interaction-Engine
Scripts/Converters/Vector2ToVector3.cs
Scripts/Converters/Vector2ToVector3.cs
using System; using System.Collections.Generic; using UnityEngine; namespace Pear.InteractionEngine.Converters { /// <summary> /// Converts a Vector2 to Vector3 /// </summary> public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3> { [Tooltip("Where should the X value be set")] public VectorFields SetXOn = VectorFields.X; [Tooltip("Multiplied on the X value when it's set")] public float XMultiplier = 1; [Tooltip("Where should the Y value be set")] public VectorFields SetYOn = VectorFields.X; [Tooltip("Multiplied on the Y value when it's set")] public float YMultiplier = 1; public Vector3 Convert(Vector2 convertFrom) { float x = 0; float y = 0; float z = 0; Dictionary<VectorFields, Action<float>> setActions = new Dictionary<VectorFields, Action<float>>() { { VectorFields.X, val => x = val }, { VectorFields.Y, val => y = val }, { VectorFields.Z, val => z = val }, }; setActions[SetXOn](convertFrom.x * XMultiplier); setActions[SetYOn](convertFrom.y * YMultiplier); return new Vector3(x, y, z); } } public enum VectorFields { X, Y, Z, } }
using UnityEngine; namespace Pear.InteractionEngine.Converters { /// <summary> /// Converts a Vector2 to Vector3 /// </summary> public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3> { public Vector3 Convert(Vector2 convertFrom) { return convertFrom; } } }
mit
C#
532bc1c98ae469cc889dc9756996a16240942729
Refactor pipe drawing.
michaellperry/flappy
Shared/Flappy.Logic/Characters/Pipe.cs
Shared/Flappy.Logic/Characters/Pipe.cs
using Flappy.Logic.Sprites; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Flappy.Logic.Characters { public class Pipe { private const float SegmentWidth = 55.0f; private const float SegmentHeight = 25.0f; private const float SegmentHorizontalCenter = SegmentWidth / 2.0f; private const float SegmentVerticalCenter = SegmentHeight / 2.0f; private static readonly Vector2 Origin = new Vector2(SegmentHorizontalCenter, SegmentVerticalCenter); private const int GapSize = 7; private Texture2D _capTop; private Texture2D _capBottom; private Texture2D _segment; public void LoadContent(ContentManager contentManager) { _capTop = contentManager.Load<Texture2D>("CapTop"); _capBottom = contentManager.Load<Texture2D>("CapBottom"); _segment = contentManager.Load<Texture2D>("Segment"); } public void Draw(SpriteBatch spriteBatch, Rectangle bounds, Camera camera) { int gapStart = 5; int gapEnd = gapStart + GapSize; int segmentCount = (int)Math.Ceiling(bounds.Height / SegmentHeight); for (int segmentIndex = 0; segmentIndex < gapStart; ++segmentIndex) { DrawSegment(spriteBatch, camera, segmentIndex, _segment); } DrawSegment(spriteBatch, camera, gapStart, _capBottom); DrawSegment(spriteBatch, camera, gapEnd, _capTop); for (int segmentIndex = gapEnd + 1; segmentIndex < segmentCount; ++segmentIndex) { DrawSegment(spriteBatch, camera, segmentIndex, _segment); } } private static void DrawSegment( SpriteBatch spriteBatch, Camera camera, int segmentIndex, Texture2D image) { Vector2 position = new Vector2(800.0f, SegmentVerticalCenter + segmentIndex * SegmentHeight); spriteBatch.Draw(image, position: position - camera.Position, origin: Origin); } } }
using Flappy.Logic.Sprites; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Flappy.Logic.Characters { public class Pipe { private static readonly Vector2 Origin = new Vector2(27.0f, 12.0f); private Texture2D _capTop; private Texture2D _capBottom; private Texture2D _segment; public void LoadContent(ContentManager contentManager) { _capTop = contentManager.Load<Texture2D>("CapTop"); _capBottom = contentManager.Load<Texture2D>("CapBottom"); _segment = contentManager.Load<Texture2D>("Segment"); } public void Draw(SpriteBatch spriteBatch, Rectangle bounds, Camera camera) { int gapStart = 5; int gapEnd = 12; int segmentCount = (int)Math.Ceiling(bounds.Height / 25.0f); for (int segmentIndex = 0; segmentIndex < segmentCount; ++segmentIndex) { if (gapStart < segmentIndex && segmentIndex < gapEnd) continue; Vector2 position = new Vector2(800.0f, 12.0f + segmentIndex * 25.0f); Texture2D image; if (segmentIndex == gapStart) image = _capBottom; else if (segmentIndex == gapEnd) image = _capTop; else image = _segment; spriteBatch.Draw(image, position: position - camera.Position, origin: Origin); } } } }
mit
C#
0386ea6dd94acbe4f9ac65659ffee9bf0281c4ec
remove ContextualItemsHelper.Start
AlejandroCano/framework,signumsoftware/framework,avifatal/framework,signumsoftware/framework,AlejandroCano/framework,avifatal/framework
Signum.Web/ButtonBar/ContextualItem.cs
Signum.Web/ButtonBar/ContextualItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Signum.Utilities; using System.Text; using Signum.Entities; namespace Signum.Web { public class SelectedItemsMenuContext { public UrlHelper Url { get; set; } public ControllerContext ControllerContext { get; set; } public List<Lite<IdentifiableEntity>> Lites { get; set; } public object QueryName { get; set; } public Implementations Implementations { get; set; } public string Prefix { get; set; } } public static class ContextualItemsHelper { public static bool SelectedItemsMenuInSearchPage = true; public static event Func<SelectedItemsMenuContext, List<IMenuItem>> GetContextualItemsForLites; public static List<IMenuItem> GetContextualItemListForLites(SelectedItemsMenuContext ctx) { List<IMenuItem> items = new List<IMenuItem>(); if (!ctx.Lites.IsNullOrEmpty()) { if (GetContextualItemsForLites != null) { foreach (var d in GetContextualItemsForLites.GetInvocationListTyped()) { var newItems = d(ctx); if (newItems != null) { if (items.Any() && newItems.NotNull().Any()) items.Add(new MenuItemSeparator()); items.AddRange(newItems.NotNull()); } } } } return items; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Signum.Utilities; using System.Text; using Signum.Entities; namespace Signum.Web { public class SelectedItemsMenuContext { public UrlHelper Url { get; set; } public ControllerContext ControllerContext { get; set; } public List<Lite<IdentifiableEntity>> Lites { get; set; } public object QueryName { get; set; } public Implementations Implementations { get; set; } public string Prefix { get; set; } } public static class ContextualItemsHelper { public static bool SelectedItemsMenuInSearchPage = false; public static event Func<SelectedItemsMenuContext, List<IMenuItem>> GetContextualItemsForLites; public static void Start() { SelectedItemsMenuInSearchPage = true; } public static List<IMenuItem> GetContextualItemListForLites(SelectedItemsMenuContext ctx) { List<IMenuItem> items = new List<IMenuItem>(); if (!ctx.Lites.IsNullOrEmpty()) { if (GetContextualItemsForLites != null) { foreach (var d in GetContextualItemsForLites.GetInvocationListTyped()) { var newItems = d(ctx); if (newItems != null) { if (items.Any() && newItems.NotNull().Any()) items.Add(new MenuItemSeparator()); items.AddRange(newItems.NotNull()); } } } } return items; } } }
mit
C#
5b9df408dce4e6e0128a8737240b3d8b2068cace
update version to 1.4.14.0
evitself/HTML-Renderer,Perspex/HTML-Renderer,Perspex/HTML-Renderer,windygu/HTML-Renderer,ArthurHub/HTML-Renderer,evitself/HTML-Renderer,todor-dk/HTML-Renderer,slagou/HTML-Renderer,drickert5/HTML-Renderer,ArthurHub/HTML-Renderer,verdesgrobert/HTML-Renderer,todor-dk/HTML-Renderer,windygu/HTML-Renderer,tinygg/graphic-HTML-Renderer,slagou/HTML-Renderer,verdesgrobert/HTML-Renderer,tinygg/graphic-HTML-Renderer,todor-dk/HTML-Renderer,drickert5/HTML-Renderer,tinygg/graphic-HTML-Renderer
Source/HtmlRenderer/Properties/AssemblyInfo.cs
Source/HtmlRenderer/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("HTML Renderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Open source hosted on CodePlex")] [assembly: AssemblyProduct("HTML Renderer")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.4.14.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HTML Renderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Open source hosted on CodePlex")] [assembly: AssemblyProduct("HTML Renderer")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.4.13.0")]
bsd-3-clause
C#
e7ff96c5bc327a0fc69941dc9715ea47bf2191db
Add Employee Standard Hours endpoints
KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet
src/keypay-dotnet/Properties/AssemblyInfo.cs
src/keypay-dotnet/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("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.13")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.13-rc1")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
aa0ae0c6447a36ad1ae0849cb517dfe082e44fda
Fix for CS0104
antoniusriha/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp
sample/GladeTest.cs
sample/GladeTest.cs
// GladeViewer.cs - Tests for LibGlade in C# // // Author: Ricardo Fernndez Pascual <[email protected]> // // (c) 2002 Ricardo Fernndez Pascual namespace GladeSamples { using System; using Gtk; using Gnome; using Glade; using GtkSharp; using System.IO; using System.Reflection; public class GladeTest : Program { public static void Main (string[] args) { new GladeTest (args).Run (); } public GladeTest (string[] args, params object[] props) : base ("GladeTest", "0.1", Modules.UI, args, props) { /* Note that we load the XML info from the assembly instead of using an external file. You don't have to distribute the .glade file if you don't want */ Glade.XML gxml = new Glade.XML (null, "test.glade", "main_window", null); gxml.Autoconnect (this); } public void OnWindowDeleteEvent (object o, DeleteEventArgs args) { Quit (); args.RetVal = true; } public void OnButton1Clicked (System.Object b, EventArgs e) { Console.WriteLine ("Button 1 clicked"); } public static void OnButton2Clicked (System.Object b, EventArgs e) { Console.WriteLine ("Button 2 clicked"); } public void OnButton2Entered (System.Object b, EventArgs e) { Console.WriteLine ("Button 2 entered"); } } }
// GladeViewer.cs - Tests for LibGlade in C# // // Author: Ricardo Fernndez Pascual <[email protected]> // // (c) 2002 Ricardo Fernndez Pascual namespace GladeSamples { using System; using Gtk; using Gnome; using Glade; using GtkSharp; using System.IO; using System.Reflection; public class GladeTest : Program { public static void Main (string[] args) { new GladeTest (args).Run (); } public GladeTest (string[] args, params object[] props) : base ("GladeTest", "0.1", Modules.UI, args, props) { /* Note that we load the XML info from the assembly instead of using an external file. You don't have to distribute the .glade file if you don't want */ Glade.XML gxml = new Glade.XML (null, "test.glade", "main_window", null); gxml.Autoconnect (this); } public void OnWindowDeleteEvent (object o, DeleteEventArgs args) { Quit (); args.RetVal = true; } public void OnButton1Clicked (Object b, EventArgs e) { Console.WriteLine ("Button 1 clicked"); } public static void OnButton2Clicked (Object b, EventArgs e) { Console.WriteLine ("Button 2 clicked"); } public void OnButton2Entered (Object b, EventArgs e) { Console.WriteLine ("Button 2 entered"); } } }
lgpl-2.1
C#
00d95ecfa1dc65b879b8d21c6b548d2d1e723e6c
Add code to allow vendo img to show on Azure
jnnfrlocke/VendingMachineNew,jnnfrlocke/VendingMachineNew,jnnfrlocke/VendingMachineNew
Views/Home/Index.cshtml
Views/Home/Index.cshtml
@{ ViewBag.Title = "Home Page"; } <div class="col-md-5"> <h1> Vendo 5.0 </h1> <p class="lead">The Future of Vending Machines</p> <p class="text-justify"> Vendo 5.0 is among the first digitally integrated vending machines of the 21st century. It's so great, that we skipped the first four versions and went straight to 5. With Vendo 5.0, you have the ability to access our machines through your smartphone or P.C. Create an account with us and explore the Vendo lifestyle. You'll have access to each the machines in your area and the ability to control what the machine grabs for you. Whether it's candy, chips or soda, Vendo 5.0 can satisfy your nourishment. So, sign up today and live life the Vendo way! </p> </div> <img src="~/img/Vendo.png" class="center-block" /> <img id="vendo" src='<%=ResolveUrl("~/img/Vendo.png") %>' /> <div class="row"> <div class="col-md-10 col-md-offset-1"> </div> </div>
@{ ViewBag.Title = "Home Page"; } <div class="col-md-5"> <h1> Vendo 5.0 </h1> <p class="lead">The Future of Vending Machines</p> <p class="text-justify"> Vendo 5.0 is among the first digitally integrated vending machines of the 21st century. It's so great, that we skipped the first four versions and went straight to 5. With Vendo 5.0, you have the ability to access our machines through your smartphone or P.C. Create an account with us and explore the Vendo lifestyle. You'll have access to each the machines in your area and the ability to control what the machine grabs for you. Whether it's candy, chips or soda, Vendo 5.0 can satisfy your nourishment. So, sign up today and live life the Vendo way! </p> </div> <img src="~/img/Vendo.png" class="center-block" /> <div class="row"> <div class="col-md-10 col-md-offset-1"> </div> </div> </div>
mit
C#
81441603283817abaf5d62987754510be51e2b33
Fix link
theplastictoy/webcamp2015-aspnet,theplastictoy/webcamp2015-aspnet
Views/Home/Index.cshtml
Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="row"> @foreach(var meetup in Model) { <div class="col-md-4"> <a href="@meetup.Link %>" target="blank"> <div style="width: 360px; height: 205px; overflow: hidden;"> <!-- <img class="img-responsive" src="http://placehold.it/700x400"> --> <img style="width: 100%" src="@meetup.Image"> </div> </a> <h3> <a href="@meetup.Link" target="blank">@meetup.Name</a> </h3> <p>@meetup.SafeDescription.Substring(0, Math.Min(meetup.SafeDescription.Length, 150))</p> </div> } </div>
@{ ViewData["Title"] = "Home Page"; } <div class="row"> @foreach(var meetup in Model) { <div class="col-md-4"> <a href="@meetup.Link %>" target="blank"> <div style="width: 360px; height: 205px; overflow: hidden;"> <!-- <img class="img-responsive" src="http://placehold.it/700x400"> --> <img style="width: 100%" src="@meetup.Image"> </div> </a> <h3> <a href="@meetup.Link %>" target="blank">@meetup.Name</a> </h3> <p>@meetup.SafeDescription.Substring(0, Math.Min(meetup.SafeDescription.Length, 150))</p> </div> } </div>
mit
C#
34bb80265464466fa66e6e00207391dbc124a329
update logging version
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
WebAPI.Common/Logging/LoggingConfig.cs
WebAPI.Common/Logging/LoggingConfig.cs
using System.IO; using System.Web; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Email; using Serilog.Sinks.GoogleCloudLogging; namespace WebAPI.Common.Logging { public static class LoggingConfig { public static void Register(string name) { var config = new GoogleCloudLoggingSinkOptions { UseJsonOutput = true, LogName = "api.mapserv.utah.gov", UseSourceContextAsLogName = false, ResourceType = "global", ServiceName = "api.mapserv.utah.gov", ServiceVersion = "1.12.4" }; #if DEBUG var projectId = "ut-dts-agrc-web-api-dv"; var fileName = "ut-dts-agrc-web-api-dv-log-writer.json"; var serviceAccount = File.ReadAllText(Path.Combine(HttpRuntime.AppDomainAppPath, fileName)); config.GoogleCredentialJson = serviceAccount; #else var projectId = "ut-dts-agrc-web-api-prod"; #endif config.ProjectId = projectId; var email = new EmailConnectionInfo { EmailSubject = "Geocoding Log Email", FromEmail = "[email protected]", ToEmail = "[email protected]" }; var levelSwitch = new LoggingLevelSwitch(); Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Email(email, restrictedToMinimumLevel: LogEventLevel.Error) .WriteTo.GoogleCloudLogging(config) .CreateLogger(); #if DEBUG levelSwitch.MinimumLevel = LogEventLevel.Verbose; #else levelSwitch.MinimumLevel = LogEventLevel.Warning; #endif Log.Debug("Logging initialized"); } } }
using System.IO; using System.Web; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Email; using Serilog.Sinks.GoogleCloudLogging; namespace WebAPI.Common.Logging { public static class LoggingConfig { public static void Register(string name) { var config = new GoogleCloudLoggingSinkOptions { UseJsonOutput = true, LogName = "api.mapserv.utah.gov", UseSourceContextAsLogName = false, ResourceType = "global", ServiceName = "api.mapserv.utah.gov", ServiceVersion = "1.12.2" }; #if DEBUG var projectId = "ut-dts-agrc-web-api-dv"; var fileName = "ut-dts-agrc-web-api-dv-log-writer.json"; var serviceAccount = File.ReadAllText(Path.Combine(HttpRuntime.AppDomainAppPath, fileName)); config.GoogleCredentialJson = serviceAccount; #else var projectId = "ut-dts-agrc-web-api-prod"; #endif config.ProjectId = projectId; var email = new EmailConnectionInfo { EmailSubject = "Geocoding Log Email", FromEmail = "[email protected]", ToEmail = "[email protected]" }; var levelSwitch = new LoggingLevelSwitch(); Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Email(email, restrictedToMinimumLevel: LogEventLevel.Error) .WriteTo.GoogleCloudLogging(config) .CreateLogger(); #if DEBUG levelSwitch.MinimumLevel = LogEventLevel.Verbose; #else levelSwitch.MinimumLevel = LogEventLevel.Warning; #endif Log.Debug("Logging initialized"); } } }
mit
C#
7c6a38886a704265fe9ac6f4f5cea889558c851f
move TODOs to github issues
dimaaan/pgEdit
PgEdit/Program.cs
PgEdit/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PgEdit { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PgEdit { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // TODO refresh table data button // TODO table schema, column type. If enumeration - display values in tooltip // TODO what table currently open? // TODO table Fields: more details // TODO navigation: clicking by foreight key cell send user to row with primary key // TODO navigation: clicking by primary key cell opens menu with depend tables. selecting table send user to table with dependent rows filtered // TODO navigation: forward and backward buttons, support mouse additional buttons // TODO SQL editor Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
mit
C#
efeefec579412967e7b5c658d48f1d816a3dcc81
Fix namespace of the AmbiguousImplementationException (#22291)
ptoonen/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,ptoonen/corefx,BrennanConroy/corefx,BrennanConroy/corefx,ericstj/corefx,ViktorHofer/corefx,wtgodbe/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,ptoonen/corefx,ptoonen/corefx,wtgodbe/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,ptoonen/corefx,BrennanConroy/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,ericstj/corefx,ericstj/corefx,wtgodbe/corefx,ViktorHofer/corefx,ptoonen/corefx,ViktorHofer/corefx,ericstj/corefx
src/Common/src/CoreLib/System/Runtime/AmbiguousImplementationException.cs
src/Common/src/CoreLib/System/Runtime/AmbiguousImplementationException.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.Serialization; namespace System.Runtime { [Serializable] public sealed class AmbiguousImplementationException : Exception { public AmbiguousImplementationException() : base(SR.AmbiguousImplementationException_NullMessage) { } public AmbiguousImplementationException(string message) : base(message) { } public AmbiguousImplementationException(string message, Exception innerException) : base(message, innerException) { } private AmbiguousImplementationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Globalization; namespace System.Runtime.Serialization { [Serializable] public sealed class AmbiguousImplementationException : Exception { public AmbiguousImplementationException() : base(SR.AmbiguousImplementationException_NullMessage) { } public AmbiguousImplementationException(string message) : base(message) { } public AmbiguousImplementationException(string message, Exception innerException) : base(message, innerException) { } private AmbiguousImplementationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
C#
68ba4388587ac8ca4644ece84f4ab140bd3d6be2
Increase project version number to 0.7.0
atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")]
apache-2.0
C#
fd1936626783f64d45d3142f77115ed5e85266b3
Add the ability to have a simple variable declared inline.
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
LINQToTTree/LINQToTTreeLib/Variables/VarSimple.cs
LINQToTTree/LINQToTTreeLib/Variables/VarSimple.cs
using System; using LinqToTTreeInterfacesLib; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } } }
using System; using LinqToTTreeInterfacesLib; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; } public IValue InitialValue { get; set; } public bool Declare { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }
lgpl-2.1
C#
96f29c5696946c6f1365ea8f9e8d2318776f7915
Use latest compat version in MvcSandbox
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/MvcSandbox/Startup.cs
samples/MvcSandbox/Startup.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.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MvcSandbox { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } public static void Main(string[] args) { var host = CreateWebHostBuilder(args) .Build(); host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureLogging(factory => { factory .AddConsole() .AddDebug(); }) .UseIISIntegration() .UseKestrel() .UseStartup<Startup>(); } }
// 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.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MvcSandbox { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } public static void Main(string[] args) { var host = CreateWebHostBuilder(args) .Build(); host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureLogging(factory => { factory .AddConsole() .AddDebug(); }) .UseIISIntegration() .UseKestrel() .UseStartup<Startup>(); } }
apache-2.0
C#
47df7f6a847173f7c8babbc853e7ce592b073d60
Fix CircularContainer using DrawSize too early
smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,default0/osu-framework,ppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,default0/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework
osu.Framework/Graphics/Containers/CircularContainer.cs
osu.Framework/Graphics/Containers/CircularContainer.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Caching; namespace osu.Framework.Graphics.Containers { /// <summary> /// A container which is rounded (via automatic corner-radius) on the shortest edge. /// </summary> public class CircularContainer : Container { private Cached cornerRadius = new Cached(); public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true) { bool result = base.Invalidate(invalidation, source, shallPropagate); if ((invalidation & (Invalidation.DrawInfo | Invalidation.RequiredParentSizeToFit)) > 0) cornerRadius.Invalidate(); return result; } protected override void Update() { base.Update(); if (!cornerRadius.IsValid) { CornerRadius = Math.Min(DrawSize.X, DrawSize.Y) / 2f; cornerRadius.Validate(); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Graphics.Containers { /// <summary> /// A container which is rounded (via automatic corner-radius) on the shortest edge. /// </summary> public class CircularContainer : Container { public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true) { bool result = base.Invalidate(invalidation, source, shallPropagate); if ((invalidation & (Invalidation.DrawInfo | Invalidation.RequiredParentSizeToFit)) > 0) CornerRadius = Math.Min(DrawSize.X, DrawSize.Y) / 2f; return result; } } }
mit
C#
f43a5245ee994ed9868321b5e577c3c459e03294
remove unnecessary using
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/Converters/MoneyConverters.cs
WalletWasabi.Fluent/Converters/MoneyConverters.cs
using Avalonia.Data.Converters; using NBitcoin; namespace WalletWasabi.Fluent.Converters { public static class MoneyConverters { public static readonly IValueConverter MoneyToString = new FuncValueConverter<Money?, string>(x => { return x switch { null => "Unknown", { } => x.ToString(fplus: false, trimExcessZero: true), }; }); } }
using Avalonia.Data.Converters; using Avalonia.Media; using NBitcoin; namespace WalletWasabi.Fluent.Converters { public static class MoneyConverters { public static readonly IValueConverter MoneyToString = new FuncValueConverter<Money?, string>(x => { return x switch { null => "Unknown", { } => x.ToString(fplus: false, trimExcessZero: true), }; }); } }
mit
C#
b79a2f368caa674286cc10c24fa65d8780453ef8
Make sure to store milliseconds in preferences for boss best time value.
Noxalus/Xmas-Hell
Xmas-Hell/Xmas-Hell-Core/PlayerData/PlayerData.cs
Xmas-Hell/Xmas-Hell-Core/PlayerData/PlayerData.cs
using XmasHell.Entities.Bosses; using System; namespace XmasHell.PlayerData { public class PlayerData { private IPreferences _preferences; public PlayerData(IPreferences preferences) { _preferences = preferences; } public void DeathCounter(int value) { _preferences.Editor().PutInt("deathCounter", value); _preferences.Editor().Apply(); } public int DeathCounter() { return _preferences.GetInt("deathCounter", 0); } // Boss specific data public void BossBeatenCounter(BossType type, int value) { _preferences.Editor().PutInt("BossBeatenCounter-" + type.ToString(), value); _preferences.Editor().Apply(); } public int BossBeatenCounter(BossType type) { return _preferences.GetInt("BossBeatenCounter-" + type.ToString(), 0); } public void BossAttempts(BossType type, int value) { _preferences.Editor().PutInt("BossAttempts-" + type.ToString(), value); _preferences.Editor().Apply(); } public int BossAttempts(BossType type) { return _preferences.GetInt("BossAttempts-" + type.ToString(), 0); } public void BossBestTime(BossType type, TimeSpan value) { _preferences.Editor().PutFloat("BossBestTime-" + type.ToString(), (float)value.TotalMilliseconds); _preferences.Editor().Apply(); } public TimeSpan BossBestTime(BossType type) { return TimeSpan.FromMilliseconds(_preferences.GetFloat("BossBestTime-" + type.ToString(), 0)); } public void BossPlayTime(BossType type, TimeSpan value) { _preferences.Editor().PutFloat("BossPlayTime-" + type.ToString(), (float)value.TotalSeconds); _preferences.Editor().Apply(); } public TimeSpan BossPlayTime(BossType type) { return TimeSpan.FromSeconds(_preferences.GetFloat("BossPlayTime-" + type.ToString(), 0)); } } }
using XmasHell.Entities.Bosses; using System; namespace XmasHell.PlayerData { public class PlayerData { private IPreferences _preferences; public PlayerData(IPreferences preferences) { _preferences = preferences; } public void DeathCounter(int value) { _preferences.Editor().PutInt("deathCounter", value); _preferences.Editor().Apply(); } public int DeathCounter() { return _preferences.GetInt("deathCounter", 0); } // Boss specific data public void BossBeatenCounter(BossType type, int value) { _preferences.Editor().PutInt("BossBeatenCounter-" + type.ToString(), value); _preferences.Editor().Apply(); } public int BossBeatenCounter(BossType type) { return _preferences.GetInt("BossBeatenCounter-" + type.ToString(), 0); } public void BossAttempts(BossType type, int value) { _preferences.Editor().PutInt("BossAttempts-" + type.ToString(), value); _preferences.Editor().Apply(); } public int BossAttempts(BossType type) { return _preferences.GetInt("BossAttempts-" + type.ToString(), 0); } public void BossBestTime(BossType type, TimeSpan value) { _preferences.Editor().PutFloat("BossBestTime-" + type.ToString(), (float)value.TotalSeconds); _preferences.Editor().Apply(); } public TimeSpan BossBestTime(BossType type) { return TimeSpan.FromSeconds(_preferences.GetFloat("BossBestTime-" + type.ToString(), 0)); } public void BossPlayTime(BossType type, TimeSpan value) { _preferences.Editor().PutFloat("BossPlayTime-" + type.ToString(), (float)value.TotalSeconds); _preferences.Editor().Apply(); } public TimeSpan BossPlayTime(BossType type) { return TimeSpan.FromSeconds(_preferences.GetFloat("BossPlayTime-" + type.ToString(), 0)); } } }
mit
C#
d7b543bc270b3ed6b0fd28e5182e524376d3e6d0
Improve log message.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/NadekoBot/Modules/Forum/Services/ForumService.cs
src/NadekoBot/Modules/Forum/Services/ForumService.cs
using System.Threading.Tasks; using Mitternacht.Services; using NLog; namespace Mitternacht.Modules.Forum.Services { public class ForumService : INService { private readonly IBotCredentials _creds; private readonly Logger _log; public GommeHDnetForumAPI.Forum Forum { get; private set; } public bool LoggedIn => Forum?.LoggedIn ?? false; private Task _loginTask; public ForumService(IBotCredentials creds) { _creds = creds; _log = LogManager.GetCurrentClassLogger(); InitForumInstance(); } public void InitForumInstance() { _loginTask?.Dispose(); _loginTask = Task.Run(() => { Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword); _log.Log(Forum.LoggedIn ? LogLevel.Info : LogLevel.Warn, $"Initialized new Forum instance. Login {(Forum.LoggedIn ? "successful" : "failed")}!"); }); } } }
using System.Threading.Tasks; using Mitternacht.Services; using NLog; namespace Mitternacht.Modules.Forum.Services { public class ForumService : INService { private readonly IBotCredentials _creds; private readonly Logger _log; public GommeHDnetForumAPI.Forum Forum { get; private set; } public bool LoggedIn => Forum?.LoggedIn ?? false; private Task _loginTask; public ForumService(IBotCredentials creds) { _creds = creds; _log = LogManager.GetCurrentClassLogger(); InitForumInstance(); } public void InitForumInstance() { _loginTask?.Dispose(); _loginTask = Task.Run(() => { Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword); _log.Log(Forum.LoggedIn ? LogLevel.Info : LogLevel.Warn, $"Initialized new Forum instance. Login {(Forum.LoggedIn ? "successful" : "failed, ignoring verification actions")}!"); }); } } }
mit
C#
32741e60edba09f5da4a381b0d8bf288a95c3c9d
update metrics to resolve to knowenums
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/CommonAbstractions/Infer/Metrics/Metrics.cs
src/Nest/CommonAbstractions/Infer/Metrics/Metrics.cs
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using Elastic.Transport; using Elastic.Transport.Extensions; using Elasticsearch.Net; namespace Nest { public class Metrics : IEquatable<Metrics>, IUrlParameter { private IndicesStatsMetric? _indicesStat; private NodesStatsMetric? _nodesStats; private NodesInfoMetric? _nodesInfo; private ClusterStateMetric? _clusterStateMetric; private WatcherStatsMetric? _watcherStatsMetric; private NodesUsageMetric? _nodesUsageMetric; internal Metrics(IndicesStatsMetric metric) => (Value, _indicesStat) = (metric, metric); internal Metrics(NodesStatsMetric metric) => (Value, _nodesStats) = (metric, metric); internal Metrics(NodesInfoMetric metric) => (Value, _nodesInfo) = (metric, metric); internal Metrics(ClusterStateMetric metric) => (Value, _clusterStateMetric) = (metric, metric); internal Metrics(WatcherStatsMetric metric) => (Value, _watcherStatsMetric) = (metric, metric); internal Metrics(NodesUsageMetric metric) => (Value, _nodesUsageMetric) = (metric, metric); internal Enum Value { get; } public bool Equals(Metrics other) => Value.Equals(other?.Value); public string GetString(IConnectionConfigurationValues settings) { if (_indicesStat != null) return _indicesStat.Value.GetStringValue(); else if (_nodesStats != null) return _nodesStats.Value.GetStringValue(); else if (_nodesInfo != null) return _nodesInfo.Value.GetStringValue(); else if (_clusterStateMetric != null) return _clusterStateMetric.Value.GetStringValue(); else if (_watcherStatsMetric != null) return _watcherStatsMetric.Value.GetStringValue(); else if (_nodesUsageMetric != null) return _nodesUsageMetric.Value.GetStringValue(); return Value.GetStringValue(); } public static implicit operator Metrics(IndicesStatsMetric metric) => new Metrics(metric); public static implicit operator Metrics(NodesStatsMetric metric) => new Metrics(metric); public static implicit operator Metrics(NodesInfoMetric metric) => new Metrics(metric); public static implicit operator Metrics(ClusterStateMetric metric) => new Metrics(metric); public static implicit operator Metrics(WatcherStatsMetric metric) => new Metrics(metric); public static implicit operator Metrics(NodesUsageMetric metric) => new Metrics(metric); public bool Equals(Enum other) => Value.Equals(other); public override bool Equals(object obj) => obj is Enum e ? Equals(e) : obj is Metrics m && Equals(m.Value); public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0; public static bool operator ==(Metrics left, Metrics right) => Equals(left, right); public static bool operator !=(Metrics left, Metrics right) => !Equals(left, right); } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using Elastic.Transport; using Elastic.Transport.Extensions; using Elasticsearch.Net; namespace Nest { public class Metrics : IEquatable<Metrics>, IUrlParameter { internal Metrics(IndicesStatsMetric metric) => Value = metric; internal Metrics(NodesStatsMetric metric) => Value = metric; internal Metrics(NodesInfoMetric metric) => Value = metric; internal Metrics(ClusterStateMetric metric) => Value = metric; internal Metrics(WatcherStatsMetric metric) => Value = metric; internal Metrics(NodesUsageMetric metric) => Value = metric; internal Enum Value { get; } public bool Equals(Metrics other) => Value.Equals(other?.Value); public string GetString(IConnectionConfigurationValues settings) => Value.GetStringValue(); public static implicit operator Metrics(IndicesStatsMetric metric) => new Metrics(metric); public static implicit operator Metrics(NodesStatsMetric metric) => new Metrics(metric); public static implicit operator Metrics(NodesInfoMetric metric) => new Metrics(metric); public static implicit operator Metrics(ClusterStateMetric metric) => new Metrics(metric); public static implicit operator Metrics(WatcherStatsMetric metric) => new Metrics(metric); public static implicit operator Metrics(NodesUsageMetric metric) => new Metrics(metric); public bool Equals(Enum other) => Value.Equals(other); public override bool Equals(object obj) => obj is Enum e ? Equals(e) : obj is Metrics m && Equals(m.Value); public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0; public static bool operator ==(Metrics left, Metrics right) => Equals(left, right); public static bool operator !=(Metrics left, Metrics right) => !Equals(left, right); } }
apache-2.0
C#
ae0da67520b7279feddef8a9f70cbd1d1a321dbd
Fix schema filter
ASP-NET-Core-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates
Source/Boilerplate.Templates/Content/ApiTemplate/ViewModelSchemaFilters/PageResultCarSchemaFilter.cs
Source/Boilerplate.Templates/Content/ApiTemplate/ViewModelSchemaFilters/PageResultCarSchemaFilter.cs
namespace ApiTemplate.ViewModelSchemaFilters { using System.Collections.Generic; using ApiTemplate.ViewModels; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; public class PageResultCarSchemaFilter : ISchemaFilter { public void Apply(Schema model, SchemaFilterContext context) { model.Default = new PageResult<Car>() { Count = 2, Items = new List<Car>() { new Car() { CarId = 1, Cylinders = 6, Make = "Honda", Model = "Civic" }, new Car() { CarId = 2, Cylinders = 8, Make = "Lambourghini", Model = "Countach" } }, Page = 1, TotalCount = 50, TotalPages = 10 }; } } }
namespace ApiTemplate.ViewModelSchemaFilters { using System.Collections.Generic; using ApiTemplate.ViewModels; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; public class PageResultCarSchemaFilter : ISchemaFilter { public void Apply(Schema model, SchemaFilterContext context) { model.Default = new PageResult<Car>() { Count = 2, Items = new List<Car>() { new Car() { CarId = 1, Cylinders = 6, Make = "Honda", Model = "Civic" }, new Car() { CarId = 2, Cylinders = 8, Make = "Lambourghini", Model = "Countach" } }, Page = 1, Total = 10 }; } } }
mit
C#
972a8d2143a5c07bef84f73083234b5347f39b28
Update UploadResultJson.cs
mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,down4u/WeiXinMPSDK,wanddy/WeiXinMPSDK,down4u/WeiXinMPSDK,wanddy/WeiXinMPSDK,lishewen/WeiXinMPSDK,JeffreySu/WxOpen,jiehanlin/WeiXinMPSDK,JeffreySu/WxOpen,mc7246/WeiXinMPSDK,wanddy/WeiXinMPSDK,lishewen/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK
Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Media/UploadResultJson.cs
Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Media/UploadResultJson.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Senparc.Weixin.MP.Entities; namespace Senparc.Weixin.MP.AdvancedAPIs { /// <summary> /// 上传媒体文件返回结果 /// </summary> public class UploadResultJson : WxJsonResult { public UploadMediaFileType type { get; set; } public string media_id { get; set; } public string thumb_media_id { get; set; } // 上传缩略图返回的meidia_id参数. public long created_at { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Senparc.Weixin.MP.Entities; namespace Senparc.Weixin.MP.AdvancedAPIs { /// <summary> /// 上传媒体文件返回结果 /// </summary> public class UploadResultJson : WxJsonResult { public UploadMediaFileType type { get; set; } public string media_id { get; set; } public long created_at { get; set; } } }
apache-2.0
C#
665ef5fdcc06c9d8bcdb8bfb705b1ebee8e61047
Add test coverage for API-incompatible rulesets wrt mods
peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
osu.Game.Tests/Rulesets/TestSceneBrokenRulesetHandling.cs
osu.Game.Tests/Rulesets/TestSceneBrokenRulesetHandling.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.UI; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Rulesets { [HeadlessTest] public class TestSceneBrokenRulesetHandling : OsuTestScene { [Resolved] private OsuGameBase gameBase { get; set; } = null!; [SetUpSteps] public void SetUpSteps() { AddStep("reset ruleset", () => Ruleset.Value = new OsuRuleset().RulesetInfo); } [Test] public void TestNullModsReturnedByRulesetAreIgnored() { AddStep("set ruleset with null mods", () => Ruleset.Value = new TestRulesetWithNullMods().RulesetInfo); AddAssert("no null mods in available mods", () => gameBase.AvailableMods.Value.SelectMany(kvp => kvp.Value).All(mod => mod != null)); } [Test] public void TestRulesetRevertedIfModsCannotBeRetrieved() { RulesetInfo ruleset = null!; AddStep("store current ruleset", () => ruleset = Ruleset.Value); AddStep("set API incompatible ruleset", () => Ruleset.Value = new TestAPIIncompatibleRuleset().RulesetInfo); AddAssert("ruleset not changed", () => Ruleset.Value.Equals(ruleset)); } #nullable disable // purposefully disabling nullability to simulate broken or unannotated API user code. private class TestRulesetWithNullMods : Ruleset { public override string ShortName => "nullmods"; public override string Description => "nullmods"; public override IEnumerable<Mod> GetModsFor(ModType type) => new Mod[] { null }; public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => null; public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => null; public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => null; } private class TestAPIIncompatibleRuleset : Ruleset { public override string ShortName => "incompatible"; public override string Description => "incompatible"; // simulate API incompatibility by throwing similar exceptions. public override IEnumerable<Mod> GetModsFor(ModType type) => throw new MissingMethodException(); public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => null; public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => null; public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => null; } #nullable enable } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Rulesets { [HeadlessTest] public class TestSceneBrokenRulesetHandling : OsuTestScene { [Resolved] private OsuGameBase gameBase { get; set; } = null!; [Test] public void TestNullModsReturnedByRulesetAreIgnored() { AddStep("set ruleset with null mods", () => Ruleset.Value = new TestRulesetWithNullMods().RulesetInfo); AddAssert("no null mods in available mods", () => gameBase.AvailableMods.Value.SelectMany(kvp => kvp.Value).All(mod => mod != null)); } #nullable disable // purposefully disabling nullability to simulate broken or unannotated API user code. private class TestRulesetWithNullMods : Ruleset { public override string ShortName => "nullmods"; public override string Description => "nullmods"; public override IEnumerable<Mod> GetModsFor(ModType type) => new Mod[] { null }; public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => null; public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => null; public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => null; } #nullable enable } }
mit
C#
64fd3bd854aa87ea4e1125623da84aca3b93c5cc
Fix compile warning (#1602)
exercism/xcsharp,exercism/xcsharp
generators/Exercises/Generators/Sieve.cs
generators/Exercises/Generators/Sieve.cs
using System; using System.Collections.Generic; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { internal class Sieve : ExerciseGenerator { protected override void UpdateNamespaces(ISet<string> namespaces) => namespaces.Add(typeof(ArgumentOutOfRangeException).Namespace!); protected override void UpdateTestClass(TestClass testClass) => AddTestCase(testClass); private static readonly string throwExceptionTestCase = @" [Fact(Skip = ""Remove this Skip property to run this test"")] public void No_negative_numbers() { Assert.Throws<ArgumentOutOfRangeException>(() => Sieve.Primes(-1)); }"; private static void AddTestCase(TestClass testClass) => testClass.AdditionalMethods.Add(throwExceptionTestCase); } }
using System; using System.Collections.Generic; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { internal class Sieve : ExerciseGenerator { protected override void UpdateNamespaces(ISet<string> namespaces) => namespaces.Add(typeof(ArgumentOutOfRangeException).Namespace); protected override void UpdateTestClass(TestClass testClass) => AddTestCase(testClass); private static readonly string throwExceptionTestCase = @" [Fact(Skip = ""Remove this Skip property to run this test"")] public void No_negative_numbers() { Assert.Throws<ArgumentOutOfRangeException>(() => Sieve.Primes(-1)); }"; private static void AddTestCase(TestClass testClass) => testClass.AdditionalMethods.Add(throwExceptionTestCase); } }
mit
C#
aa0639ac54889fd46ba4374951544198ac49a749
Fix deserialization of scheduled job.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
src/Squidex.Domain.Apps.Entities/Contents/ScheduleJob.cs
src/Squidex.Domain.Apps.Entities/Contents/ScheduleJob.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using NodaTime; using Squidex.Domain.Apps.Core.Contents; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Contents { public sealed class ScheduleJob { public Guid Id { get; } public Status Status { get; } public RefToken ScheduledBy { get; } public Instant DueTime { get; } public ScheduleJob(Guid id, Status status, RefToken scheduledBy, Instant due) { Id = id; ScheduledBy = scheduledBy; Status = status; DueTime = due; } public static ScheduleJob Build(Status status, RefToken by, Instant due) { return new ScheduleJob(Guid.NewGuid(), status, by, due); } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using NodaTime; using Squidex.Domain.Apps.Core.Contents; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Contents { public sealed class ScheduleJob { public Guid Id { get; } public Status Status { get; } public RefToken ScheduledBy { get; } public Instant DueTime { get; } public ScheduleJob(Guid id, Status status, RefToken by, Instant due) { Id = id; ScheduledBy = by; Status = status; DueTime = due; } public static ScheduleJob Build(Status status, RefToken by, Instant due) { return new ScheduleJob(Guid.NewGuid(), status, by, due); } } }
mit
C#
628e642b36d89a71a1a13c12c60c71a38be462d7
Add ConverterTypeName to SettingMetadata
NFig/NFig
NFig/SettingMetadata.cs
NFig/SettingMetadata.cs
using System; using NFig.Converters; namespace NFig { /// <summary> /// Describes all information about an individual setting, except for its values. /// </summary> public class SettingMetadata : IBySettingDictionaryItem { /// <summary> /// The name of the setting. Dots in the name represent nesting levels. /// </summary> public string Name { get; } /// <summary> /// User-provided description of the setting. /// </summary> public string Description { get; } /// <summary> /// The full name of the setting's type. /// </summary> public string TypeName { get; } /// <summary> /// If true, all default and override values are encrypted. /// </summary> public bool IsEncrypted { get; } /// <summary> /// True if the setting type is an enum. Use integer values when setting overrides for enum settings (e.g. to assign the value MyEnum.Two, use "2", not /// "Two"). /// </summary> public bool IsEnum { get; } /// <summary> /// The fully-qualified type name of the setting's converter. All built-in converters begin with "NFig.Converters." /// </summary> public string ConverterTypeName { get; } /// <summary> /// True if the setting was marked with the [ChangeRequiresRestart] attribute. This indicates that any edits to this setting likely won't have any /// affect until the application is restarted. /// </summary> public bool ChangeRequiresRestart { get; } internal SettingMetadata(string name, string description, Type type, bool isEncrypted, ISettingConverter converter, bool changeRequiresRestart) { Name = name; Description = description; TypeName = type.FullName; IsEncrypted = isEncrypted; IsEnum = type.IsEnum; ConverterTypeName = converter.GetType().FullName; ChangeRequiresRestart = changeRequiresRestart; } } }
using System; namespace NFig { /// <summary> /// Describes all information about an individual setting, except for its values. /// </summary> public class SettingMetadata : IBySettingDictionaryItem { /// <summary> /// The name of the setting. Dots in the name represent nesting levels. /// </summary> public string Name { get; } /// <summary> /// User-provided description of the setting. /// </summary> public string Description { get; } /// <summary> /// The runtime type of the setting's values. /// </summary> public Type Type { get; } /// <summary> /// The full name of the setting's type. /// </summary> public string TypeName => Type.FullName; /// <summary> /// If true, all default and override values are encrypted. /// </summary> public bool IsEncrypted { get; } /// <summary> /// True if the setting type is an enum. Use integer values when setting overrides for enum settings (e.g. to assign the value MyEnum.Two, use "2", not /// "Two"). /// </summary> public bool IsEnum { get; } /// <summary> /// True if the setting was marked with the [ChangeRequiresRestart] attribute. This indicates that any edits to this setting likely won't have any /// affect until the application is restarted. /// </summary> public bool ChangeRequiresRestart { get; } internal SettingMetadata(string name, string description, Type type, bool isEncrypted, bool changeRequiresRestart) { Name = name; Description = description; Type = type; IsEncrypted = isEncrypted; IsEnum = type.IsEnum; ChangeRequiresRestart = changeRequiresRestart; } } }
mit
C#
981dba4dde7fb08f48cd10b0926c0c04e1bb1e3c
Add special http method to return unprocessable entities
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
src/Diploms.WebUI/Configuration/ControllerExtensions.cs
src/Diploms.WebUI/Configuration/ControllerExtensions.cs
using System.Linq; using Diploms.Dto; using Microsoft.AspNetCore.Mvc; namespace Diploms.WebUI { public static class ControllerExtensions { public static OperationResult GetErrors(this Controller controller, object model) { var result = new OperationResult(); if (model == null) { result.Errors.Add("Ошибка ввода данных"); } result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors .Where(b => !string.IsNullOrEmpty(b.ErrorMessage)) .Select(b => b.ErrorMessage))); return result; } public static IActionResult Unprocessable(this Controller controller, object value) { return controller.StatusCode(422, value); } } }
using System.Linq; using Diploms.Dto; using Microsoft.AspNetCore.Mvc; namespace Diploms.WebUI { public static class ControllerExtensions { public static OperationResult GetErrors(this Controller controller, object model) { var result = new OperationResult(); if (model == null) { result.Errors.Add("Ошибка ввода данных"); } result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors .Where(b => !string.IsNullOrEmpty(b.ErrorMessage)) .Select(b => b.ErrorMessage))); return result; } } }
mit
C#
067263cdaa8f98cd0caa0289b345b094e887715e
Change timeout to 15 sec and document findings
agray/nunit,mikkelbu/nunit,appel1/nunit,jadarnel27/nunit,mikkelbu/nunit,NikolayPianikov/nunit,agray/nunit,OmicronPersei/nunit,ggeurts/nunit,nunit/nunit,appel1/nunit,mjedrzejek/nunit,JustinRChou/nunit,JustinRChou/nunit,OmicronPersei/nunit,ggeurts/nunit,agray/nunit,nunit/nunit,jadarnel27/nunit,NikolayPianikov/nunit,mjedrzejek/nunit
src/NUnitFramework/tests/Internal/ThreadUtilityTests.cs
src/NUnitFramework/tests/Internal/ThreadUtilityTests.cs
#if !NETSTANDARD1_3 && !NETSTANDARD1_6 using System.Runtime.InteropServices; using System.Threading; using NUnit.TestUtilities; namespace NUnit.Framework.Internal { [TestFixture] public class ThreadUtilityTests { [Platform("Win")] [TestCase(false, TestName = "Abort")] [TestCase(true, TestName = "Kill")] public void AbortOrKillThreadWithMessagePump(bool kill) { using (var isThreadAboutToWait = new ManualResetEvent(false)) { var nativeId = 0; var thread = new Thread(() => { nativeId = ThreadUtility.GetCurrentThreadNativeId(); isThreadAboutToWait.Set(); while (true) WaitMessage(); }); thread.Start(); isThreadAboutToWait.WaitOne(); Thread.Sleep(1); if (kill) ThreadUtility.Kill(thread, nativeId); else ThreadUtility.Abort(thread, nativeId); // When not under CPU load, we expect the thread to take between 100 and 200 ms to abort. // However we get spurious failures in CI if we only wait 1000 ms. // Using AbortOrKillThreadWithMessagePump_StressTest (times: 1000, maxParallelism: 20), // I measured timer callbacks to be firing around ten times later than the 100 ms requested. // All this number does is manage how long we can tolerate waiting for a build if a bug // is introduced and the thread never aborts. const int waitTime = 15000; Assert.That(thread.Join(waitTime), "Native message pump was not able to be interrupted to enable a managed thread abort."); } } [Platform("Win")] [Test, Explicit("For diagnostic purposes; slow")] public void AbortOrKillThreadWithMessagePump_StressTest() { StressUtility.RunParallel( () => AbortOrKillThreadWithMessagePump(kill: true), times: 1000, maxParallelism: 20); } [DllImport("user32.dll")] private static extern bool WaitMessage(); } } #endif
#if !NETSTANDARD1_3 && !NETSTANDARD1_6 using System.Runtime.InteropServices; using System.Threading; using NUnit.TestUtilities; namespace NUnit.Framework.Internal { [TestFixture] public class ThreadUtilityTests { [Platform("Win")] [TestCase(false, TestName = "Abort")] [TestCase(true, TestName = "Kill")] public void AbortOrKillThreadWithMessagePump(bool kill) { using (var isThreadAboutToWait = new ManualResetEvent(false)) { var nativeId = 0; var thread = new Thread(() => { nativeId = ThreadUtility.GetCurrentThreadNativeId(); isThreadAboutToWait.Set(); while (true) WaitMessage(); }); thread.Start(); isThreadAboutToWait.WaitOne(); Thread.Sleep(1); if (kill) ThreadUtility.Kill(thread, nativeId); else ThreadUtility.Abort(thread, nativeId); Assert.That(thread.Join(1000), "Native message pump was not able to be interrupted to enable a managed thread abort."); } } [Platform("Win")] [Test, Explicit("For diagnostic purposes; slow")] public void AbortOrKillThreadWithMessagePump_StressTest() { StressUtility.RunParallel( () => AbortOrKillThreadWithMessagePump(kill: true), times: 1000, maxParallelism: 20); } [DllImport("user32.dll")] private static extern bool WaitMessage(); } } #endif
mit
C#
5e6e38f3658ac51b48d5b7fa9a472d1cd1e733bc
Add interface methods.
kyourek/Pagination,kyourek/Pagination,kyourek/Pagination
sln/Pagination/IPageSource.cs
sln/Pagination/IPageSource.cs
using System.Linq; namespace Pagination { public interface IPageSource { IPageConfig Config { get; } IPageRequest Request { get; } IPageSource SetItemsPerPage(int value); IPageSource SetPageBaseZero(int value); } public interface IPageSource<TItem> : IPageSource { IOrderedQueryable<TItem> ItemsSource { get; } IPage<TItem> FindPage(); } public interface IPageSource<TItem, TFilter> : IPageSource<TItem> { TFilter Filter { get; } new IPage<TItem, TFilter> FindPage(); } }
using System.Linq; namespace Pagination { public interface IPageSource { IPageConfig Config { get; } IPageRequest Request { get; } } public interface IPageSource<TItem> : IPageSource { IOrderedQueryable<TItem> ItemsSource { get; } IPage<TItem> FindPage(); } public interface IPageSource<TItem, TFilter> : IPageSource<TItem> { TFilter Filter { get; } new IPage<TItem, TFilter> FindPage(); } }
mit
C#
6434968696631f270d63a6138e0cd4bd653f7681
update entities in sample
stombeur/IdentityServer3.Samples,ravibisht27/IdentityServer3.Samples,codedecay/IdentityServer3.Samples,JaonDong/IdentityServer3.Samples,pirumpi/IdentityServer3.Samples,kouweizhong/IdentityServer3.Samples,andyshao/IdentityServer3.Samples,ccccccmd/IdentityServer3.Samples,gavinbarron/IdentityServer3.Samples,sumedhmeshram/IdentityServer3.Samples,IdentityServer/IdentityServer3.Samples,jmalca14/IdentityServer3.Samples,daptiv/IdentityServer3.Samples,jhoerr/IdentityServer3.Samples,feanz/Thinktecture.IdentityServer3.Samples,eric-swann-q2/IdentityServer3.Samples,nicklv/IdentityServer3.Samples,DosGuru/IdentityServer3.Samples,codedecay/IdentityServer3.Samples,lvjunlei/IdentityServer3.Samples,yanjustino/IdentityServer3.Samples,faithword/IdentityServer3.Samples,MetSystem/IdentityServer3.Samples,18098924759/IdentityServer3.Samples,codehedgehog/IdentityServer3.Samples,MartinKip/IdentityServer3.Samples,jmalca14/IdentityServer3.Samples,nguyentk90/IdentityServer3.Samples,TomKearney/IdentityServer3.Samples,nguyentk90/IdentityServer3.Samples,daptiv/IdentityServer3.Samples,MetSystem/IdentityServer3.Samples,ccccccmd/IdentityServer3.Samples,ravibisht27/IdentityServer3.Samples,EternalXw/IdentityServer3.Samples,codedecay/IdentityServer3.Samples,nicklv/IdentityServer3.Samples,gavinbarron/IdentityServer3.Samples,ryanvgates/IdentityServer3.Samples,MartinKip/IdentityServer3.Samples,18098924759/IdentityServer3.Samples,lvjunlei/IdentityServer3.Samples,tuyndv/IdentityServer3.Samples,codehedgehog/IdentityServer3.Samples,DosGuru/IdentityServer3.Samples,JaonDong/IdentityServer3.Samples,lvjunlei/IdentityServer3.Samples,carlos-sarmiento/IdentityServer3.Samples,TomKearney/IdentityServer3.Samples,MartinKip/IdentityServer3.Samples,tuyndv/IdentityServer3.Samples,EternalXw/IdentityServer3.Samples,atul221282/IdentityServer3.Samples,vebin/IdentityServer3.Samples,jhoerr/IdentityServer3.Samples,ryanvgates/IdentityServer3.Samples,jmalca14/IdentityServer3.Samples,stombeur/IdentityServer3.Samples,yanjustino/IdentityServer3.Samples,IdentityServer/IdentityServer3.Samples,codeice/IdentityServer3.Samples,yanjustino/IdentityServer3.Samples,codeice/IdentityServer3.Samples,ryanvgates/IdentityServer3.Samples,carlos-sarmiento/IdentityServer3.Samples,geffzhang/Thinktecture.IdentityServer.v3.Samples,geffzhang/Thinktecture.IdentityServer.v3.Samples,andyshao/IdentityServer3.Samples,faithword/IdentityServer3.Samples,nicklv/IdentityServer3.Samples,EternalXw/IdentityServer3.Samples,sumedhmeshram/IdentityServer3.Samples,feanz/Thinktecture.IdentityServer3.Samples,vebin/IdentityServer3.Samples,eric-swann-q2/IdentityServer3.Samples,codeice/IdentityServer3.Samples,gavinbarron/IdentityServer3.Samples,jhoerr/IdentityServer3.Samples,IdentityServer/IdentityServer3.Samples,codehedgehog/IdentityServer3.Samples,stombeur/IdentityServer3.Samples,pirumpi/IdentityServer3.Samples,stombeur/IdentityServer3.Samples,feanz/Thinktecture.IdentityServer3.Samples,ravibisht27/IdentityServer3.Samples,andyshao/IdentityServer3.Samples,sumedhmeshram/IdentityServer3.Samples,faithword/IdentityServer3.Samples,ccccccmd/IdentityServer3.Samples,kouweizhong/IdentityServer3.Samples,atul221282/IdentityServer3.Samples,carlos-sarmiento/IdentityServer3.Samples,nguyentk90/IdentityServer3.Samples,pirumpi/IdentityServer3.Samples,daptiv/IdentityServer3.Samples,atul221282/IdentityServer3.Samples,eric-swann-q2/IdentityServer3.Samples,DosGuru/IdentityServer3.Samples,18098924759/IdentityServer3.Samples,TomKearney/IdentityServer3.Samples,geffzhang/Thinktecture.IdentityServer.v3.Samples,MetSystem/IdentityServer3.Samples,vebin/IdentityServer3.Samples,JaonDong/IdentityServer3.Samples,kouweizhong/IdentityServer3.Samples,tuyndv/IdentityServer3.Samples
source/AspNetIdentity/SelfHost/AspId/SimpleEntities.cs
source/AspNetIdentity/SelfHost/AspId/SimpleEntities.cs
/* * Copyright 2014 Dominick Baier, Brock Allen * * 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.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Web; namespace SelfHost.AspId { public class User : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } } public class Role : IdentityRole { } public class Context : IdentityDbContext<User, Role, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> { public Context(string connString) : base(connString) { } } public class UserStore : UserStore<User, Role, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> { public UserStore(Context ctx) : base(ctx) { } } public class UserManager : UserManager<User, string> { public UserManager(UserStore store) : base(store) { this.ClaimsIdentityFactory = new ClaimsFactory(); } } public class ClaimsFactory : ClaimsIdentityFactory<User, string> { public ClaimsFactory() { this.UserIdClaimType = Thinktecture.IdentityServer.Core.Constants.ClaimTypes.Subject; this.UserNameClaimType = Thinktecture.IdentityServer.Core.Constants.ClaimTypes.PreferredUserName; this.RoleClaimType = Thinktecture.IdentityServer.Core.Constants.ClaimTypes.Role; } public override async System.Threading.Tasks.Task<System.Security.Claims.ClaimsIdentity> CreateAsync(UserManager<User, string> manager, User user, string authenticationType) { var ci = await base.CreateAsync(manager, user, authenticationType); if (!String.IsNullOrWhiteSpace(user.FirstName)) { ci.AddClaim(new Claim("given_name", user.FirstName)); } if (!String.IsNullOrWhiteSpace(user.LastName)) { ci.AddClaim(new Claim("family_name", user.LastName)); } return ci; } } public class RoleStore : RoleStore<Role> { public RoleStore(Context ctx) : base(ctx) { } } public class RoleManager : RoleManager<Role> { public RoleManager(RoleStore store) : base(store) { } } }
/* * Copyright 2014 Dominick Baier, Brock Allen * * 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.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SelfHost.AspId { public class User : IdentityUser { } public class Role : IdentityRole { } public class Context : IdentityDbContext<User, Role, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> { public Context(string connString) : base(connString) { } } public class UserStore : UserStore<User> { public UserStore(Context ctx) : base(ctx) { } } public class UserManager : UserManager<User> { public UserManager(UserStore store) : base(store) { } } public class RoleStore : RoleStore<Role> { public RoleStore(Context ctx) : base(ctx) { } } public class RoleManager : RoleManager<Role> { public RoleManager(RoleStore store) : base(store) { } } }
apache-2.0
C#
18d935b13e6601286a394d0df690ace3c3b098a4
Update SMSTodayAMController.cs
dkitchen/bpcc,dkitchen/bpcc
src/BPCCScheduler.Web/Controllers/SMSTodayAMController.cs
src/BPCCScheduler.Web/Controllers/SMSTodayAMController.cs
using BPCCScheduler.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Twilio; namespace BPCCScheduler.Controllers { public class SMSTodayAMController : SMSApiController { //public IEnumerable<SMSMessage> Get() public IEnumerable<Appointment> Get() { //any appointment today after last-night midnight, but before today noon var lastNightMidnight = DateTime.Now.Date; var todayNoon = lastNightMidnight.AddHours(12); var appts = base.AppointmentContext.Appointments.ToList() //materialize for date conversion //.Where(i => i.Date.ToLocalTime() > lastNightMidnight && i.Date.ToLocalTime() < todayNoon); .Select(i => new Appointment { Date = i.Date.ToLocalTime(), ClientName = i.ClientName, Cell = i.Cell}); return appts; var messages = new List<SMSMessage>(); foreach (var appt in appts) { var body = string.Format("BPCC Reminder: Appointment this morning at {0}", appt.Date.ToLocalTime().ToShortTimeString()); var cell = string.Format("+1{0}", appt.Cell); messages.Add(base.SendSmsMessage(cell, body)); } //return messages; } } }
using BPCCScheduler.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Twilio; namespace BPCCScheduler.Controllers { public class SMSTodayAMController : SMSApiController { //public IEnumerable<SMSMessage> Get() public IEnumerable<Appointment> Get() { //any appointment today after last-night midnight, but before today noon var lastNightMidnight = DateTime.Now.Date; var ret = ""; ret += lastNightMidnight.ToLongDateString(); ret += " " + lastNightMidnight.ToLongTimeString(); var todayNoon = lastNightMidnight.AddHours(12); ret += " " + todayNoon.ToLongDateString(); ret += " " + todayNoon.ToLongTimeString(); return ret; var appts = base.AppointmentContext.Appointments.ToList() //materialize for date conversion //.Where(i => i.Date.ToLocalTime() > lastNightMidnight && i.Date.ToLocalTime() < todayNoon); .Select(i => new Appointment { Date = i.Date.ToLocalTime(), ClientName = i.ClientName, Cell = i.Cell}); return appts; var messages = new List<SMSMessage>(); foreach (var appt in appts) { var body = string.Format("BPCC Reminder: Appointment this morning at {0}", appt.Date.ToLocalTime().ToShortTimeString()); var cell = string.Format("+1{0}", appt.Cell); messages.Add(base.SendSmsMessage(cell, body)); } //return messages; } } }
mit
C#
00553a352720376a10acbf20f2b56175961c1be7
Define Service.BindAndDispose() which can be used to bind a model to a service that is also a disposable and disposes the service when the binding is disposed.
bordoley/RxApp
RxApp/Service.cs
RxApp/Service.cs
using System; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Reactive.Disposables; using System.Windows.Input; using ReactiveUI; namespace RxApp { public interface IService: INotifyPropertyChanged { bool IsStarted { get; } void Start(); void Stop(); } public interface IServiceViewModel { ICommand Start { get; } ICommand Stop { get; } } public interface IServiceControllerModel { bool CanStart { set; } bool CanStop { set; } IObservable<object> Start { get; } IObservable<object> Stop { get; } } public static class Service { public static IDisposable BindAndDispose<TDisposableService> (this IServiceControllerModel model, TDisposableService service) where TDisposableService: IDisposable, IService { CompositeDisposable retval = new CompositeDisposable(); retval.Add(model.Bind(service)); retval.Add(service); return retval; } public static IDisposable Bind(this IServiceControllerModel model, IService service) { Contract.Requires(model != null); Contract.Requires(service != null); CompositeDisposable subscription = new CompositeDisposable(); subscription.Add(service.WhenAnyValue(x => x.IsStarted).Subscribe(isStarted => { model.CanStart = !isStarted; model.CanStop = isStarted; })); subscription.Add (model.Start.Subscribe(_ => service.Start())); subscription.Add (model.Stop.Subscribe(_ => service.Stop())); return subscription; } } }
using System; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Reactive.Disposables; using System.Windows.Input; using ReactiveUI; namespace RxApp { public interface IService: INotifyPropertyChanged { bool IsStarted { get; } void Start(); void Stop(); } public interface IServiceViewModel { ICommand Start { get; } ICommand Stop { get; } } public interface IServiceControllerModel { bool CanStart { set; } bool CanStop { set; } IObservable<object> Start { get; } IObservable<object> Stop { get; } } public static class Service { public static IDisposable Bind(this IServiceControllerModel model, IService service) { Contract.Requires(model != null); Contract.Requires(service != null); CompositeDisposable subscription = new CompositeDisposable(); subscription.Add(service.WhenAnyValue(x => x.IsStarted).Subscribe(isStarted => { model.CanStart = !isStarted; model.CanStop = isStarted; })); subscription.Add (model.Start.Subscribe(_ => service.Start())); subscription.Add (model.Stop.Subscribe(_ => service.Stop())); return subscription; } } }
apache-2.0
C#
9654e22a1c09162f623e147a0718055de4d8a76e
Adjust namespace
pardahlman/RawRabbit,northspb/RawRabbit
src/RawRabbit/Consumer/Eventing/EventingRawConsumer.cs
src/RawRabbit/Consumer/Eventing/EventingRawConsumer.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Exceptions; using RawRabbit.Consumer.Contract; using RawRabbit.Logging; namespace RawRabbit.Consumer.Eventing { internal class EventingRawConsumer : EventingBasicConsumer, IRawConsumer { private readonly ILogger _logger = LogManager.GetLogger<EventingRawConsumer>(); public List<ulong> NackedDeliveryTags { get; private set; } public EventingRawConsumer(IModel channel) : base(channel) { NackedDeliveryTags = new List<ulong>(); SetupLogging(this); } private void SetupLogging(EventingBasicConsumer rawConsumer) { rawConsumer.Shutdown += (sender, args) => { _logger.LogInformation($"Consumer {rawConsumer.ConsumerTag} has been shut down.\n Reason: {args.Cause}\n Initiator: {args.Initiator}\n Reply Text: {args.ReplyText}"); }; rawConsumer.ConsumerCancelled += (sender, args) => _logger.LogDebug($"The consumer with tag '{args.ConsumerTag}' has been cancelled."); rawConsumer.Unregistered += (sender, args) => _logger.LogDebug($"The consumer with tag '{args.ConsumerTag}' has been unregistered."); } public Func<object, BasicDeliverEventArgs, Task> OnMessageAsync { get; set; } public void Disconnect() { if (string.IsNullOrEmpty(ConsumerTag)) { // broker has not given a tag yet. return; } try { Model.BasicCancel(ConsumerTag); } catch (AlreadyClosedException) { // Perfect, someone allready closed this. } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Exceptions; using RawRabbit.Consumer.Contract; using RawRabbit.Logging; namespace RawRabbit.Consumer { internal class EventingRawConsumer : EventingBasicConsumer, IRawConsumer { private readonly ILogger _logger = LogManager.GetLogger<EventingRawConsumer>(); public List<ulong> NackedDeliveryTags { get; private set; } public EventingRawConsumer(IModel channel) : base(channel) { NackedDeliveryTags = new List<ulong>(); SetupLogging(this); } private void SetupLogging(EventingBasicConsumer rawConsumer) { rawConsumer.Shutdown += (sender, args) => { _logger.LogInformation($"Consumer {rawConsumer.ConsumerTag} has been shut down.\n Reason: {args.Cause}\n Initiator: {args.Initiator}\n Reply Text: {args.ReplyText}"); }; rawConsumer.ConsumerCancelled += (sender, args) => _logger.LogDebug($"The consumer with tag '{args.ConsumerTag}' has been cancelled."); rawConsumer.Unregistered += (sender, args) => _logger.LogDebug($"The consumer with tag '{args.ConsumerTag}' has been unregistered."); } public Func<object, BasicDeliverEventArgs, Task> OnMessageAsync { get; set; } public void Disconnect() { if (string.IsNullOrEmpty(ConsumerTag)) { // broker has not given a tag yet. return; } try { Model.BasicCancel(ConsumerTag); } catch (AlreadyClosedException) { // Perfect, someone allready closed this. } } } }
mit
C#
9533d44f62025c47f89e606397abb812d0c4c589
Add some skiahelper extensions methods that allow for convenient layering within a rendering context.
SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia
src/Skia/Avalonia.Skia/Helpers/DrawingContextHelper.cs
src/Skia/Avalonia.Skia/Helpers/DrawingContextHelper.cs
using System; using Avalonia.Platform; using Avalonia.Rendering; using SkiaSharp; namespace Avalonia.Skia.Helpers { public static class DrawingContextHelper { /// <summary> /// Wrap Skia canvas in drawing context so we can use Avalonia api to render to external skia canvas /// this is useful in scenarios where canvas is not controlled by application, but received from another non avalonia api /// like: SKCanvas canvas = SKDocument.BeginPage(...); /// </summary> /// <param name="canvas"></param> /// <param name="dpi"></param> /// <param name="visualBrushRenderer"></param> /// <returns>DrawingContext</returns> public static IDrawingContextImpl WrapSkiaCanvas(SKCanvas canvas, Vector dpi, IVisualBrushRenderer visualBrushRenderer = null) { var createInfo = new DrawingContextImpl.CreateInfo { Canvas = canvas, Dpi = dpi, VisualBrushRenderer = visualBrushRenderer, DisableTextLcdRendering = true, }; return new DrawingContextImpl(createInfo); } /// <summary> /// Unsupported - Wraps a GPU Backed SkiaSurface in an Avalonia DrawingContext. /// </summary> [Obsolete] public static IDrawingContextImpl WrapSkiaSurface(this SKSurface surface, GRContext grContext, Vector dpi, IVisualBrushRenderer visualBrushRenderer = null) { var createInfo = new DrawingContextImpl.CreateInfo { GrContext = grContext, Surface = surface, Dpi = dpi, VisualBrushRenderer = visualBrushRenderer, DisableTextLcdRendering = false, }; return new DrawingContextImpl(createInfo); } /// <summary> /// Unsupported - Wraps a non-GPU Backed SkiaSurface in an Avalonia DrawingContext. /// </summary> [Obsolete] public static IDrawingContextImpl WrapSkiaSurface(this SKSurface surface, Vector dpi, IVisualBrushRenderer visualBrushRenderer = null) { var createInfo = new DrawingContextImpl.CreateInfo { Surface = surface, Dpi = dpi, VisualBrushRenderer = visualBrushRenderer, DisableTextLcdRendering = false, }; return new DrawingContextImpl(createInfo); } [Obsolete] public static void DrawSurfaceTo(this ISkiaDrawingContextImpl source, ISkiaDrawingContextImpl destination, Size size, SKImageFilter imageFilter = null) { using (var blurSnapPaint = new SKPaint { ImageFilter = imageFilter, IsAntialias = true }) { destination.SkCanvas.DrawSurface(source.SkSurface, new SKPoint(0, 0), blurSnapPaint); } } } }
using Avalonia.Platform; using Avalonia.Rendering; using SkiaSharp; namespace Avalonia.Skia.Helpers { public class DrawingContextHelper { /// <summary> /// Wrap Skia canvas in drawing context so we can use Avalonia api to render to external skia canvas /// this is useful in scenarios where canvas is not controlled by application, but received from another non avalonia api /// like: SKCanvas canvas = SKDocument.BeginPage(...); /// </summary> /// <param name="canvas"></param> /// <param name="dpi"></param> /// <param name="visualBrushRenderer"></param> /// <returns>DrawingContext</returns> public static IDrawingContextImpl WrapSkiaCanvas(SKCanvas canvas, Vector dpi, IVisualBrushRenderer visualBrushRenderer = null) { var createInfo = new DrawingContextImpl.CreateInfo { Canvas = canvas, Dpi = dpi, VisualBrushRenderer = visualBrushRenderer, DisableTextLcdRendering = true, }; return new DrawingContextImpl(createInfo); } } }
mit
C#
059638790a1fdadad38977515c4d92ca7cd99e60
Add test for protocol.
gigya/KafkaNetClient,Jroland/kafka-net,bridgewell/kafka-net,nightkid1027/kafka-net,CenturyLinkCloud/kafka-net,EranOfer/KafkaNetClient,martijnhoekstra/kafka-net,geffzhang/kafka-net,BDeus/KafkaNetClient,aNutForAJarOfTuna/kafka-net,PKRoma/kafka-net
kafka-tests/Unit/ProtocolMessageTests.cs
kafka-tests/Unit/ProtocolMessageTests.cs
using System.Linq; using KafkaNet; using KafkaNet.Protocol; using NUnit.Framework; namespace kafka_tests { [TestFixture] [Category("Unit")] public class ProtocolMessageTests { [Test] [ExpectedException(typeof(FailCrcCheckException))] public void DecodeMessageShouldThrowWhenCrcFails() { var testMessage = new Message { Key = "test", Value = "kafka test message." }; var encoded = Message.EncodeMessage(testMessage); encoded[0] += 1; var result = Message.DecodeMessage(0, encoded).First(); } [Test] [TestCase("test key", "test message")] [TestCase(null, "test message")] [TestCase("test key", null)] [TestCase(null, null)] public void EnsureMessageEncodeAndDecodeAreCompatible(string key, string value) { var testMessage = new Message { Key = key, Value = value }; var encoded = Message.EncodeMessage(testMessage); var result = Message.DecodeMessage(0, encoded).First(); Assert.That(testMessage.Key, Is.EqualTo(result.Key)); Assert.That(testMessage.Value, Is.EqualTo(result.Value)); } [Test] public void EncodeMessageSetEncodesMultipleMessages() { //expected generated from python library var expected = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 45, 70, 24, 62, 0, 0, 0, 0, 0, 1, 49, 0, 0, 0, 1, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 90, 65, 40, 168, 0, 0, 0, 0, 0, 1, 49, 0, 0, 0, 1, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 195, 72, 121, 18, 0, 0, 0, 0, 0, 1, 49, 0, 0, 0, 1, 50 }; var messages = new[] { new Message {Value = "0", Key = "1"}, new Message {Value = "1", Key = "1"}, new Message {Value = "2", Key = "1"} }; var result = Message.EncodeMessageSet(messages); Assert.That(expected, Is.EqualTo(result)); } } }
using System.Linq; using KafkaNet; using KafkaNet.Protocol; using NUnit.Framework; namespace kafka_tests { [TestFixture] [Category("Unit")] public class ProtocolMessageTests { [Test] [ExpectedException(typeof(FailCrcCheckException))] public void DecodeMessageShouldThrowWhenCrcFails() { var testMessage = new Message { Key = "test", Value = "kafka test message." }; var encoded = Message.EncodeMessage(testMessage); encoded[0] += 1; var result = Message.DecodeMessage(0, encoded).First(); } [Test] [TestCase("test key", "test message")] [TestCase(null, "test message")] [TestCase("test key", null)] [TestCase(null, null)] public void EnsureMessageEncodeAndDecodeAreCompatible(string key, string value) { var testMessage = new Message { Key = key, Value = value }; var encoded = Message.EncodeMessage(testMessage); var result = Message.DecodeMessage(0, encoded).First(); Assert.That(testMessage.Key, Is.EqualTo(result.Key)); Assert.That(testMessage.Value, Is.EqualTo(result.Value)); } } }
apache-2.0
C#
0ed190e3a587520a7b03b3a5a711ce72919fb3fc
Add missing using in Silverlight build
nazim9214/NLog,babymechanic/NLog,rajk987/NLog,ilya-g/NLog,BrandonLegault/NLog,RRUZ/NLog,ArsenShnurkov/NLog,michaeljbaird/NLog,zbrad/NLog,RichiCoder1/NLog,bhaeussermann/NLog,vbfox/NLog,vladikk/NLog,vladikk/NLog,breyed/NLog,BrandonLegault/NLog,AqlaSolutions/NLog-Unity3D,rajeshgande/NLog,BrandonLegault/NLog,littlesmilelove/NLog,BrutalCode/NLog,hubo0831/NLog,tetrodoxin/NLog,rajeshgande/NLog,AqlaSolutions/NLog-Unity3D,ajayanandgit/NLog,AndreGleichner/NLog,ilya-g/NLog,sean-gilliam/NLog,kevindaub/NLog,NLog/NLog,campbeb/NLog,bryjamus/NLog,mikkelxn/NLog,breyed/NLog,hubo0831/NLog,pwelter34/NLog,fringebits/NLog,mikkelxn/NLog,FeodorFitsner/NLog,Niklas-Peter/NLog,babymechanic/NLog,fringebits/NLog,FeodorFitsner/NLog,ie-zero/NLog,luigiberrettini/NLog,vladikk/NLog,MoaidHathot/NLog,matteobruni/NLog,czema/NLog,tetrodoxin/NLog,kevindaub/NLog,bhaeussermann/NLog,ArsenShnurkov/NLog,thomkinson/NLog,littlesmilelove/NLog,pwelter34/NLog,matteobruni/NLog,czema/NLog,vladikk/NLog,bryjamus/NLog,thomkinson/NLog,ajayanandgit/NLog,bjornbouetsmith/NLog,ie-zero/NLog,304NotModified/NLog,bjornbouetsmith/NLog,rajk987/NLog,czema/NLog,snakefoot/NLog,AqlaSolutions/NLog-Unity3D,AndreGleichner/NLog,Niklas-Peter/NLog,RRUZ/NLog,BrutalCode/NLog,tohosnet/NLog,thomkinson/NLog,thomkinson/NLog,BrandonLegault/NLog,UgurAldanmaz/NLog,rajk987/NLog,tmusico/NLog,luigiberrettini/NLog,fringebits/NLog,mikkelxn/NLog,rajk987/NLog,mikkelxn/NLog,UgurAldanmaz/NLog,michaeljbaird/NLog,MoaidHathot/NLog,vbfox/NLog,nazim9214/NLog,MartinTherriault/NLog,MartinTherriault/NLog,RichiCoder1/NLog,fringebits/NLog,zbrad/NLog,campbeb/NLog,czema/NLog,tmusico/NLog,AqlaSolutions/NLog-Unity3D,tohosnet/NLog
src/NLog/LayoutRenderers/AssemblyVersionLayoutRenderer.cs
src/NLog/LayoutRenderers/AssemblyVersionLayoutRenderer.cs
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT2 namespace NLog.LayoutRenderers { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using NLog.Config; using NLog.Internal; #if SILVERLIGHT using System.Windows.Application; #else using System.Reflection; #endif /// <summary> /// Assembly version. /// </summary> [LayoutRenderer("assembly-version")] public class AssemblyVersionLayoutRenderer : LayoutRenderer { /// <summary> /// Renders assembly version and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { #if SILVERLIGHT var assembly = Application.Current.GetType().Assembly; #else var assembly = Assembly.GetEntryAssembly(); #endif var assemblyVersion = assembly == null ? "Could not find entry assembly" : assembly.GetName().Version.ToString(); builder.Append(assemblyVersion); } } } #endif
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT2 namespace NLog.LayoutRenderers { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Reflection; using System.Text; using NLog.Config; using NLog.Internal; /// <summary> /// Assembly version. /// </summary> [LayoutRenderer("assembly-version")] public class AssemblyVersionLayoutRenderer : LayoutRenderer { /// <summary> /// Renders assembly version and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { #if SILVERLIGHT var assembly = Application.Current.GetType().Assembly; #else var assembly = Assembly.GetEntryAssembly(); #endif var assemblyVersion = assembly == null ? "Could not find entry assembly" : assembly.GetName().Version.ToString(); builder.Append(assemblyVersion); } } } #endif
bsd-3-clause
C#
2ccc0d05bafcee76963738fdad80448dcb647678
Address potential stutering/deadlocks in NetworkMovementSendMovementChangeEventListeners
HelloKitty/Booma.Proxy
src/Booma.Proxy.Client.Unity.Ship/Engine/Initializables/NetworkMovementSendMovementChangeEventListener.cs
src/Booma.Proxy.Client.Unity.Ship/Engine/Initializables/NetworkMovementSendMovementChangeEventListener.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GladNet; using Nito.AsyncEx; using UnityEngine; namespace Booma.Proxy { //This current design could put the movement a frame or two behind the actual local movement //probably doesn't matter for PSO though. [SceneTypeCreate(GameSceneType.LobbyDefault)] public sealed class NetworkMovementSendMovementChangeEventListener : BaseSingleEventListenerInitializable<IMovementInputChangedEventSubscribable, MovementInputChangedEventArgs>, IGameTickable { //Dependencies private IReadonlyEntityGuidMappable<GameObject> WorldObjectMap { get; } private ILocalPlayerNetworkMovementController LocalPlayerNetworkController { get; } private ICharacterSlotSelectedModel SlotModel { get; } //Local state private MovementInputChangedEventArgs CurrentMovementArgs { get; set; } = new MovementInputChangedEventArgs(0.0f, 0.0f); private AsyncLock SyncObj = new AsyncLock(); //TODO: We need better state handling than a bool private bool isMoving = false; /// <inheritdoc /> public NetworkMovementSendMovementChangeEventListener(IMovementInputChangedEventSubscribable subscriptionService, [NotNull] ILocalPlayerNetworkMovementController localPlayerNetworkController, [NotNull] IReadonlyEntityGuidMappable<GameObject> worldObjectMap, ICharacterSlotSelectedModel slotModel) : base(subscriptionService) { LocalPlayerNetworkController = localPlayerNetworkController ?? throw new ArgumentNullException(nameof(localPlayerNetworkController)); WorldObjectMap = worldObjectMap ?? throw new ArgumentNullException(nameof(worldObjectMap)); SlotModel = slotModel; } /// <inheritdoc /> protected override async void OnEventFired(object source, MovementInputChangedEventArgs args) { //State doesn't need to change if this is true //but it SHOULDN'T be true, as the event should not be //broadcasted if(CurrentMovementArgs == args) return; //It's ok to capture the sync context here, we'll need it to touch the GameObject //and the Transform. using(var l = await SyncObj.LockAsync()) { //If the input says NOT MOVING but we are MOVING //then we need to end the movement and then send a movement finished command if(!CurrentMovementArgs.isMoving && isMoving) { GameObject worldObject = WorldObjectMap[EntityGuid.ComputeEntityGuid(EntityType.Player, SlotModel.SlotSelected)]; //It's important that this doesn't capture the sync context otheriwse it could block Update from finishing (causing deadlock) //since it needs to wait on SyncContext to be serviced by Unity3D in fixed update. It's CRITICAL that we do NOT block on the main thread //or such a deadlock will occur. await LocalPlayerNetworkController.StopMovementAsync(worldObject.transform.position, worldObject.transform.rotation) .ConfigureAwait(false); //We tell the controller to stop moving and we set our movement here to false. isMoving = false; } CurrentMovementArgs = args; } } /// <inheritdoc /> public void Tick() { using(SyncObj.Lock()) { GameObject worldObject = WorldObjectMap[EntityGuid.ComputeEntityGuid(EntityType.Player, SlotModel.SlotSelected)]; LocalPlayerNetworkController.UpdatedMovementLocation(worldObject.transform.position, worldObject.transform.rotation); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GladNet; using Nito.AsyncEx; using UnityEngine; namespace Booma.Proxy { //This current design could put the movement a frame or two behind the actual local movement //probably doesn't matter for PSO though. [SceneTypeCreate(GameSceneType.LobbyDefault)] public sealed class NetworkMovementSendMovementChangeEventListener : BaseSingleEventListenerInitializable<IMovementInputChangedEventSubscribable, MovementInputChangedEventArgs>, IGameTickable { //Dependencies private IReadonlyEntityGuidMappable<GameObject> WorldObjectMap { get; } private ILocalPlayerNetworkMovementController LocalPlayerNetworkController { get; } private ICharacterSlotSelectedModel SlotModel { get; } //Local state private MovementInputChangedEventArgs CurrentMovementArgs { get; set; } = new MovementInputChangedEventArgs(0.0f, 0.0f); private AsyncLock SyncObj = new AsyncLock(); //TODO: We need better state handling than a bool private bool isMoving = false; /// <inheritdoc /> public NetworkMovementSendMovementChangeEventListener(IMovementInputChangedEventSubscribable subscriptionService, [NotNull] ILocalPlayerNetworkMovementController localPlayerNetworkController, [NotNull] IReadonlyEntityGuidMappable<GameObject> worldObjectMap, ICharacterSlotSelectedModel slotModel) : base(subscriptionService) { LocalPlayerNetworkController = localPlayerNetworkController ?? throw new ArgumentNullException(nameof(localPlayerNetworkController)); WorldObjectMap = worldObjectMap ?? throw new ArgumentNullException(nameof(worldObjectMap)); SlotModel = slotModel; } /// <inheritdoc /> protected override async void OnEventFired(object source, MovementInputChangedEventArgs args) { //State doesn't need to change if this is true //but it SHOULDN'T be true, as the event should not be //broadcasted if(CurrentMovementArgs == args) return; using(var l = await SyncObj.LockAsync()) { //If the input says NOT MOVING but we are MOVING //then we need to end the movement and then send a movement finished command if(!CurrentMovementArgs.isMoving && isMoving) { GameObject worldObject = WorldObjectMap[EntityGuid.ComputeEntityGuid(EntityType.Player, SlotModel.SlotSelected)]; await LocalPlayerNetworkController.StopMovementAsync(worldObject.transform.position, worldObject.transform.rotation); //We tell the controller to stop moving and we set our movement here to false. isMoving = false; } CurrentMovementArgs = args; } } /// <inheritdoc /> public void Tick() { using(SyncObj.Lock()) { GameObject worldObject = WorldObjectMap[EntityGuid.ComputeEntityGuid(EntityType.Player, SlotModel.SlotSelected)]; LocalPlayerNetworkController.UpdatedMovementLocation(worldObject.transform.position, worldObject.transform.rotation); } } } }
agpl-3.0
C#
0778e30c45b30db772ed56b8c58320d970c63b3e
comment for UILayout
bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL
CSharpGL/OpenGLObjects/UILayout/UIRenderer.cs
CSharpGL/OpenGLObjects/UILayout/UIRenderer.cs
 using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpGL { /// <summary> /// 支持UI布局的渲染器 /// </summary> public partial class UIRenderer : RendererBase, IUILayout { protected Renderer renderer; public Renderer Renderer { get { return renderer; } } /// <summary> /// 支持UI布局的渲染器 /// </summary> /// <param name="modernRenderer">要渲染的对象,确保其顶点范围在(-1, -1, -1)和(1, 1, 1)之间。</param> /// <param name="Anchor">绑定到窗口的哪些边?</param> /// <param name="Margin">到绑定边的距离</param> /// <param name="Size">UI大小</param> /// <param name="zNear"></param> /// <param name="zFar"></param> public UIRenderer( Renderer modernRenderer, System.Windows.Forms.AnchorStyles Anchor, System.Windows.Forms.Padding Margin, System.Drawing.Size Size, int zNear = -1000, int zFar = 1000 ) { this.renderer = modernRenderer; this.Anchor = Anchor; this.Margin = Margin; this.Size = Size; this.zNear = zNear; this.zFar = zFar; } protected override void DoInitialize() { this.renderer.Initialize(); } protected override void DoRender(RenderEventArgs arg) { this.renderer.Render(arg); } protected override void DisposeUnmanagedResources() { this.renderer.Dispose(); } public System.Windows.Forms.AnchorStyles Anchor { get; set; } public System.Windows.Forms.Padding Margin { get; set; } public System.Drawing.Size Size { get; set; } public int zNear { get; set; } public int zFar { get; set; } } }
 using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpGL { /// <summary> /// 支持UI布局的渲染器 /// </summary> public partial class UIRenderer : RendererBase, IUILayout { protected Renderer renderer; public Renderer Renderer { get { return renderer; } } /// <summary> /// 支持UI布局的渲染器 /// </summary> /// <param name="modernRenderer">要渲染的对象</param> /// <param name="Anchor">绑定到窗口的哪些边?</param> /// <param name="Margin">到绑定边的距离</param> /// <param name="Size">UI大小</param> /// <param name="zNear"></param> /// <param name="zFar"></param> public UIRenderer( Renderer modernRenderer, System.Windows.Forms.AnchorStyles Anchor, System.Windows.Forms.Padding Margin, System.Drawing.Size Size, int zNear = -1000, int zFar = 1000 ) { this.renderer = modernRenderer; this.Anchor = Anchor; this.Margin = Margin; this.Size = Size; this.zNear = zNear; this.zFar = zFar; } protected override void DoInitialize() { this.renderer.Initialize(); } protected override void DoRender(RenderEventArgs arg) { this.renderer.Render(arg); } protected override void DisposeUnmanagedResources() { this.renderer.Dispose(); } public System.Windows.Forms.AnchorStyles Anchor { get; set; } public System.Windows.Forms.Padding Margin { get; set; } public System.Drawing.Size Size { get; set; } public int zNear { get; set; } public int zFar { get; set; } } }
mit
C#
c539707271e3f4d7944f3860d41ed79f7d93f79a
Fix expected test output following behavior change in 1124126
abock/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,tmat/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,eriawan/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,wvdd007/roslyn,nguerrera/roslyn,weltkante/roslyn,panopticoncentral/roslyn,weltkante/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,AmadeusW/roslyn,MichalStrehovsky/roslyn,jasonmalinowski/roslyn,xasx/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,stephentoub/roslyn,brettfo/roslyn,physhi/roslyn,VSadov/roslyn,agocke/roslyn,davkean/roslyn,weltkante/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,tannergooding/roslyn,bartdesmet/roslyn,nguerrera/roslyn,tmat/roslyn,gafter/roslyn,aelij/roslyn,DustinCampbell/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,abock/roslyn,xasx/roslyn,diryboy/roslyn,mavasani/roslyn,aelij/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,VSadov/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,genlu/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,jcouv/roslyn,tmat/roslyn,diryboy/roslyn,jcouv/roslyn,MichalStrehovsky/roslyn,physhi/roslyn,davkean/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,brettfo/roslyn,AlekseyTs/roslyn,sharwell/roslyn,reaction1989/roslyn,eriawan/roslyn,abock/roslyn,jcouv/roslyn,physhi/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,dotnet/roslyn,reaction1989/roslyn,reaction1989/roslyn,DustinCampbell/roslyn,sharwell/roslyn,davkean/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,genlu/roslyn,aelij/roslyn,wvdd007/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,swaroop-sridhar/roslyn,stephentoub/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,VSadov/roslyn,MichalStrehovsky/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,jmarolf/roslyn,agocke/roslyn,heejaechang/roslyn,tannergooding/roslyn,xasx/roslyn,stephentoub/roslyn
src/EditorFeatures/CSharpTest/Formatting/FormattingAnalyzerTests.cs
src/EditorFeatures/CSharpTest/Formatting/FormattingAnalyzerTests.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new FormattingDiagnosticAnalyzer(), new FormattingCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TrailingWhitespace() { var testCode = "class X[| |]" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; var expected = "class X" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; await TestInRegularAndScriptAsync(testCode, expected); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TestMissingSpace() { var testCode = @" class TypeName { void Method() { if$$(true)return; } } "; var expected = @" class TypeName { void Method() { if (true) return; } } "; await TestInRegularAndScriptAsync(testCode, expected); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new FormattingDiagnosticAnalyzer(), new FormattingCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TrailingWhitespace() { var testCode = "class X[| |]" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; var expected = "class X" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; await TestInRegularAndScriptAsync(testCode, expected); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TestMissingSpace() { var testCode = @" class TypeName { void Method() { if$$(true)return; } } "; var expected = @" class TypeName { void Method() { if (true)return; } } "; await TestInRegularAndScriptAsync(testCode, expected); } } }
mit
C#
f319a72d2a400ee73459e7b48b9b7db1c5aee880
Fix OracleQuoterTest
spaccabit/fluentmigrator,spaccabit/fluentmigrator
src/FluentMigrator.Tests/Unit/Generators/Oracle/OracleQuoterTest.cs
src/FluentMigrator.Tests/Unit/Generators/Oracle/OracleQuoterTest.cs
using System; using System.Globalization; using System.Threading; using FluentMigrator.Model; using FluentMigrator.Runner.Generators; using FluentMigrator.Runner.Generators.Generic; using FluentMigrator.Runner.Generators.Jet; using FluentMigrator.Runner.Generators.MySql; using FluentMigrator.Runner.Generators.Oracle; using FluentMigrator.Runner.Generators.SQLite; using FluentMigrator.Runner.Generators.SqlServer; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Unit.Generators.Oracle { [TestFixture] public class OracleQuoterTest { private IQuoter quoter = default(OracleQuoter); private readonly CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; [SetUp] public void SetUp() { quoter = new OracleQuoter(); } [Test] public void TimeSpanIsFormattedQuotes() { quoter.QuoteValue(new TimeSpan(1,2, 13, 65)) .ShouldBe("'1 2:14:5.0'"); } } }
using System; using System.Globalization; using System.Threading; using FluentMigrator.Model; using FluentMigrator.Runner.Generators; using FluentMigrator.Runner.Generators.Generic; using FluentMigrator.Runner.Generators.Jet; using FluentMigrator.Runner.Generators.MySql; using FluentMigrator.Runner.Generators.Oracle; using FluentMigrator.Runner.Generators.SQLite; using FluentMigrator.Runner.Generators.SqlServer; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Unit.Generators.Oracle { [TestFixture] public class OracleQuoterTest { private IQuoter quoter = default(OracleQuoter); private readonly CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; [SetUp] public void SetUp() { quoter = new OracleQuoter(); } [Test] public void TimeSpanIsFormattedQuotes() { quoter.QuoteValue(new TimeSpan(1,2, 13, 65)) .ShouldBe("'1 2:14:05'"); } } }
apache-2.0
C#
29091f3fe2c7febbccf2d01b98ce798d95670547
Fix some formatting for Teams
laurentkempe/HipChatConnect,laurentkempe/HipChatConnect
src/HipChatConnect/Controllers/Listeners/Github/GithubAggregator.cs
src/HipChatConnect/Controllers/Listeners/Github/GithubAggregator.cs
using System.Linq; using System.Text; using System.Threading.Tasks; using HipChatConnect.Controllers.Listeners.Github.Models; using HipChatConnect.Controllers.Listeners.TeamCity; namespace HipChatConnect.Controllers.Listeners.Github { public class GithubAggregator { private IHipChatRoom Room { get; } public GithubAggregator(IHipChatRoom room) { Room = room; } public async Task Handle(GithubPushNotification notification) { await SendTeamsInformationAsync(notification); } private async Task SendTeamsInformationAsync(GithubPushNotification notification) { var githubModel = notification.GithubModel; (var title, var text) = BuildMessage(githubModel); var cardData = new SuccessfulTeamsActivityCardData { Title = title, Text = text }; await Room.SendTeamsActivityCardAsync(cardData); } private static (string Title, string Text) BuildMessage(GithubModel model) { var branch = model.Ref.Replace("refs/heads/", ""); var authorNames = model.Commits.Select(c => c.Author.Name).Distinct().ToList(); var title = $"{string.Join(", ", authorNames)} committed on {branch}"; var stringBuilder = new StringBuilder(); stringBuilder.AppendLine( $"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})"); foreach (var commit in model.Commits) { stringBuilder.AppendLine($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})"); stringBuilder.AppendLine(); } return (title, stringBuilder.ToString()); } } }
using System.Linq; using System.Text; using System.Threading.Tasks; using HipChatConnect.Controllers.Listeners.Github.Models; using HipChatConnect.Controllers.Listeners.TeamCity; namespace HipChatConnect.Controllers.Listeners.Github { public class GithubAggregator { private IHipChatRoom Room { get; } public GithubAggregator(IHipChatRoom room) { Room = room; } public async Task Handle(GithubPushNotification notification) { await SendTeamsInformationAsync(notification); } private async Task SendTeamsInformationAsync(GithubPushNotification notification) { var githubModel = notification.GithubModel; (var title, var text) = BuildMessage(githubModel); var cardData = new SuccessfulTeamsActivityCardData { Title = title, Text = text }; await Room.SendTeamsActivityCardAsync(cardData); } private static (string Title, string Text) BuildMessage(GithubModel model) { var branch = model.Ref.Replace("refs/heads/", ""); var authorNames = model.Commits.Select(c => c.Author.Name).Distinct(); var title = $"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})"; var stringBuilder = new StringBuilder(); foreach (var commit in model.Commits) { stringBuilder.Append($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})"); } return (title, stringBuilder.ToString()); } } }
mit
C#
12dfa1635af3cb6ff6b4c9bd4da82a33688e7a5a
Fix typo in MenuViewModel.cs
serenabenny/Caliburn.Micro,Caliburn-Micro/Caliburn.Micro
samples/features/Features.CrossPlatform.Shared/ViewModels/MenuViewModel.cs
samples/features/Features.CrossPlatform.Shared/ViewModels/MenuViewModel.cs
using System; using Caliburn.Micro; #if XAMARINFORMS using INavigationService = Caliburn.Micro.Xamarin.Forms.INavigationService; #endif namespace Features.CrossPlatform.ViewModels { public class MenuViewModel : Screen { private readonly INavigationService navigationService; public MenuViewModel(INavigationService navigationService) { this.navigationService = navigationService; Features = new BindableCollection<FeatureViewModel> { new FeatureViewModel("Binding Conventions", "Binding view model properties to your view.", typeof(BindingsViewModel)), new FeatureViewModel("Action Conventions", "Wiring view events to view model methods.", typeof(ActionsViewModel)), new FeatureViewModel("Coroutines", "Using IEnumerable<IResult>", typeof(CoroutineViewModel)), new FeatureViewModel("Execute", "Using Execute to execute code on the UI thread.", typeof(ExecuteViewModel)), new FeatureViewModel("Event Aggregator", "Send events between uncoupled view models.", typeof(EventAggregationViewModel)), #if !XAMARINFORMS new FeatureViewModel("Design Time", "Conventions in the xaml designer and design mode detection.", typeof(DesignTimeViewModel)), #endif new FeatureViewModel("Conductors", "Composing view models together with lifecycle events", typeof(ConductorViewModel)), new FeatureViewModel("Bubbling Actions", "How to bubble actions from a child view model to a parent", typeof(BubblingViewModel)), new FeatureViewModel("Navigation", "Using a navigation service to switch between view models.", typeof(NavigationSourceViewModel)), // Context Menus // Navigation // Window Manager }; } public BindableCollection<FeatureViewModel> Features { get; } public void ShowFeature(FeatureViewModel feature) { navigationService.NavigateToViewModel(feature.ViewModel); } } }
using System; using Caliburn.Micro; #if XAMARINFORMS using INavigationService = Caliburn.Micro.Xamarin.Forms.INavigationService; #endif namespace Features.CrossPlatform.ViewModels { public class MenuViewModel : Screen { private readonly INavigationService navigationService; public MenuViewModel(INavigationService navigationService) { this.navigationService = navigationService; Features = new BindableCollection<FeatureViewModel> { new FeatureViewModel("Binding Conventions", "Binding view model properties to your view.", typeof(BindingsViewModel)), new FeatureViewModel("Action Conventions", "Wiring view events to view model methods.", typeof(ActionsViewModel)), new FeatureViewModel("Coroutines", "Using IEnumerable<IResult>", typeof(CoroutineViewModel)), new FeatureViewModel("Execute", "Using Execute to execute code on the UI thread.", typeof(ExecuteViewModel)), new FeatureViewModel("Event Aggregator", "Send events between uncoupled view models.", typeof(EventAggregationViewModel)), #if !XAMARINFORMS new FeatureViewModel("Design Time", "Conventions in the xaml desginer and design mode detection.", typeof(DesignTimeViewModel)), #endif new FeatureViewModel("Conductors", "Composing view models together with lifecycle events", typeof(ConductorViewModel)), new FeatureViewModel("Bubbling Actions", "How to bubble actions from a child view model to a parent", typeof(BubblingViewModel)), new FeatureViewModel("Navigation", "Using a navigation service to switch between view models.", typeof(NavigationSourceViewModel)), // Context Menus // Navigation // Window Manager }; } public BindableCollection<FeatureViewModel> Features { get; } public void ShowFeature(FeatureViewModel feature) { navigationService.NavigateToViewModel(feature.ViewModel); } } }
mit
C#
bf1a7dfb850c7ea143372ea48e628edeb1cbd981
Add Layer to scene. Currently breaking on asset load
HotPrawns/Jiemyu_Unity,HotPrawns/Jiemyu
src/Chess-Demo/AppDelegate.cs
src/Chess-Demo/AppDelegate.cs
using System.Reflection; using Microsoft.Xna.Framework; using CocosDenshion; using CocosSharp; namespace Chess_Demo { class AppDelegate : CCApplicationDelegate { static CCWindow sharedWindow; public static CCWindow SharedWindow { get { return sharedWindow; } } public static CCSize DefaultResolution; public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow) { application.ContentRootDirectory = "assets"; sharedWindow = mainWindow; DefaultResolution = new CCSize( application.MainWindow.WindowSizeInPixels.Width, application.MainWindow.WindowSizeInPixels.Height); CCScene scene = new CCScene(sharedWindow); scene.AddChild(new ChessLayer()); sharedWindow.RunWithScene(scene); } public override void ApplicationDidEnterBackground(CCApplication application) { application.Paused = true; } public override void ApplicationWillEnterForeground(CCApplication application) { application.Paused = false; } } }
using System.Reflection; using Microsoft.Xna.Framework; using CocosDenshion; using CocosSharp; namespace Chess_Demo { class AppDelegate : CCApplicationDelegate { static CCWindow sharedWindow; public static CCWindow SharedWindow { get { return sharedWindow; } } public static CCSize DefaultResolution; public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow) { application.ContentRootDirectory = "assets"; sharedWindow = mainWindow; DefaultResolution = new CCSize( application.MainWindow.WindowSizeInPixels.Width, application.MainWindow.WindowSizeInPixels.Height); CCScene scene = new CCScene(sharedWindow); sharedWindow.RunWithScene(scene); } public override void ApplicationDidEnterBackground(CCApplication application) { application.Paused = true; } public override void ApplicationWillEnterForeground(CCApplication application) { application.Paused = false; } } }
mit
C#
70d87d88a54caa005a58065530f24c28124f4f26
Update Class1.cs
Jolka/babajaga
DokumentyPacjenci/DokumentyPacjenci/Class1.cs
DokumentyPacjenci/DokumentyPacjenci/Class1.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DokumentyPacjenci { public class Class1 { void a() { } int b = 5; string = "Witaj w pliku" } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DokumentyPacjenci { public class Class1 { void a() { } int b = 5; } }
mit
C#
49a20ac087709fca315f6eef91972ede88998cfc
ADD interfaces and Install/InstallAsync
lightlikeD/DSACharacterSheet,lightlike/DSACharacterSheet
Drachenhorn.Xml/Template/ITemplateMetadata.cs
Drachenhorn.Xml/Template/ITemplateMetadata.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Drachenhorn.Xml.Template { public interface ITemplateMetadata : IEquatable<ITemplateMetadata>, INotifyPropertyChanged { double Version { get; set; } string Name { get; set; } bool IsInstalled { get; } bool Install(); Task<bool> InstallAsync(); } /// <summary> /// Extension Methods for ITemplateMetadata /// </summary> public static partial class Extension { internal static void SetVersionAndNameFromXmlLine(this ITemplateMetadata meta, string line) { var versionMatch = new Regex("Version=\"[0-9]+[.]?[0-9]*\"").Match(line).Value; if (!string.IsNullOrEmpty(versionMatch)) meta.Version = double.Parse(versionMatch.Substring(9, versionMatch.Length - 10), CultureInfo.InvariantCulture); var nameMatch = new Regex("Name=\"[^\"]*\"").Match(line).Value; meta.Name = !string.IsNullOrEmpty(nameMatch) ? nameMatch.Substring(6, nameMatch.Length - 7) : "unnamed"; } #region Equals internal static bool Equals(this ITemplateMetadata meta, object obj) { return obj is ITemplateMetadata metadata && meta.Equals(metadata); } internal static int GetHashCode(this ITemplateMetadata meta) { unchecked { return (meta.Version.GetHashCode() * 397) ^ (meta.Name != null ? meta.Name.GetHashCode() : 1); } } internal static bool Equals(this ITemplateMetadata meta, ITemplateMetadata obj) { if (obj == null) return false; return meta.Name == obj.Name && Math.Abs(meta.Version - obj.Version) < double.Epsilon; } #endregion Equals } }
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Text.RegularExpressions; namespace Drachenhorn.Xml.Template { public interface ITemplateMetadata : IEquatable<ITemplateMetadata> { double Version { get; set; } string Name { get; set; } bool IsInstalled { get; } } /// <summary> /// Extension Methods for ITemplateMetadata /// </summary> public static partial class Extension { internal static void SetVersionAndNameFromXmlLine(this ITemplateMetadata meta, string line) { var versionMatch = new Regex("Version=\"[0-9]+[.]?[0-9]*\"").Match(line).Value; if (!string.IsNullOrEmpty(versionMatch)) meta.Version = double.Parse(versionMatch.Substring(9, versionMatch.Length - 10), CultureInfo.InvariantCulture); var nameMatch = new Regex("Name=\"[^\"]*\"").Match(line).Value; meta.Name = !string.IsNullOrEmpty(nameMatch) ? nameMatch.Substring(6, nameMatch.Length - 7) : "unnamed"; } #region Equals internal static bool Equals(this ITemplateMetadata meta, object obj) { return obj is ITemplateMetadata metadata && meta.Equals(metadata); } internal static int GetHashCode(this ITemplateMetadata meta) { unchecked { return (meta.Version.GetHashCode() * 397) ^ (meta.Name != null ? meta.Name.GetHashCode() : 1); } } internal static bool Equals(this ITemplateMetadata meta, ITemplateMetadata obj) { if (obj == null) return false; return meta.Name == obj.Name && Math.Abs(meta.Version - obj.Version) < double.Epsilon; } #endregion Equals } }
mit
C#
06bde29fe9aa8d541baf4d0a03f9a4311757447d
Fix typo in ParserOptions.AdaptRegexp doc (#79)
sebastienros/esprima-dotnet,sebastienros/esprima-dotnet
src/Esprima/ParserOptions.cs
src/Esprima/ParserOptions.cs
namespace Esprima { public class ParserOptions { public ParserOptions() { ErrorHandler = new ErrorHandler(); } public ParserOptions(string source) { ErrorHandler = new ErrorHandler() { Source = source }; } public ParserOptions(IErrorHandler errorHandler) { ErrorHandler = errorHandler; } public bool Range { get; set; } = false; /// <summary> /// Gets or sets whether the parsed elements have their location included. /// </summary> public bool Loc { get; set; } = false; /// <summary> /// Gets or sets whether the tokens are included in the parsed tree. /// </summary> public bool Tokens { get; set; } = false; /// <summary> /// Gets or sets whether the comments are included in the parsed tree. /// </summary> public bool Comment { get; set; } = false; /// <summary> /// Gets or sets whether the parser is tolerant to errors. /// </summary> public bool Tolerant { get; set; } = true; /// <summary> /// Gets or sets whether the source represents a module or a script. /// </summary> public SourceType SourceType { get; set; } = SourceType.Script; /// <summary> /// Gets or sets the <see cref="IErrorHandler"/> to use. /// </summary> public IErrorHandler ErrorHandler { get; set; } /// <summary> /// Gets or sets whether the Regular Expression syntax should be converted to a .NET compatible one. /// </summary> public bool AdaptRegexp { get; set; } } }
namespace Esprima { public class ParserOptions { public ParserOptions() { ErrorHandler = new ErrorHandler(); } public ParserOptions(string source) { ErrorHandler = new ErrorHandler() { Source = source }; } public ParserOptions(IErrorHandler errorHandler) { ErrorHandler = errorHandler; } public bool Range { get; set; } = false; /// <summary> /// Gets or sets whether the parsed elements have their location included. /// </summary> public bool Loc { get; set; } = false; /// <summary> /// Gets or sets whether the tokens are included in the parsed tree. /// </summary> public bool Tokens { get; set; } = false; /// <summary> /// Gets or sets whether the comments are included in the parsed tree. /// </summary> public bool Comment { get; set; } = false; /// <summary> /// Gets or sets whether the parser is tolerant to errors. /// </summary> public bool Tolerant { get; set; } = true; /// <summary> /// Gets or sets whether the source represents a module or a script. /// </summary> public SourceType SourceType { get; set; } = SourceType.Script; /// <summary> /// Gets or sets the <see cref="IErrorHandler"/> to use. /// </summary> public IErrorHandler ErrorHandler { get; set; } /// <summary> /// Gets or sets wheter the Regular Expression syntax should be converted to a .NET compatible one. /// </summary> public bool AdaptRegexp { get; set; } } }
bsd-3-clause
C#
9aca04fc2049e939fb5644d578060eae3454f5a6
Add more info to xml doc of BitFormsAppCompatActivity's UseDefaultConfiguration in bit cs client
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/CSharpClient/Bit.CSharpClient.Prism/Droid/BitFormsAppCompatActivity.cs
src/CSharpClient/Bit.CSharpClient.Prism/Droid/BitFormsAppCompatActivity.cs
#if Android using Android.Content.PM; using Android.OS; using Android.Runtime; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace Bit.Droid { public class BitFormsAppCompatActivity : FormsAppCompatActivity { private bool _useDefaultConfiguration = false; /// <summary> /// Configures VersionTracking | RgPluginsPopup | Fast Renderers | Xamarin Essentials' Permissions /// </summary> protected virtual void UseDefaultConfiguration(Bundle savedInstanceState) { _useDefaultConfiguration = true; Forms.SetFlags("FastRenderers_Experimental"); Rg.Plugins.Popup.Popup.Init(this, savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); VersionTracking.Track(); } public override void OnBackPressed() { if (_useDefaultConfiguration == true) { Rg.Plugins.Popup.Popup.SendBackPressed(base.OnBackPressed); } else { base.OnBackPressed(); } } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults) { if (_useDefaultConfiguration == true) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); } base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } } #endif
#if Android using Android.Content.PM; using Android.OS; using Android.Runtime; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace Bit.Droid { public class BitFormsAppCompatActivity : FormsAppCompatActivity { private bool _useDefaultConfiguration = false; /// <summary> /// Configures VersionTracking | RgPluginsPopup | Fast Renderers /// </summary> protected virtual void UseDefaultConfiguration(Bundle savedInstanceState) { _useDefaultConfiguration = true; Forms.SetFlags("FastRenderers_Experimental"); Rg.Plugins.Popup.Popup.Init(this, savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); VersionTracking.Track(); } public override void OnBackPressed() { if (_useDefaultConfiguration == true) { Rg.Plugins.Popup.Popup.SendBackPressed(base.OnBackPressed); } else { base.OnBackPressed(); } } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults) { if (_useDefaultConfiguration == true) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); } base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } } #endif
mit
C#
d64289ae706a4a0366237c4a4177c7a5f322a21a
Fix null object pattern
AliakseiFutryn/dotnet-design-patterns-samples
Generating/NullObject/Entities/SpriteDrink.cs
Generating/NullObject/Entities/SpriteDrink.cs
using NullObject.Abstract; namespace NullObject.Entities { public class SpriteDrink : Drink { /// <summary> /// The drink name. /// </summary> public override string Name => string.Empty; /// <summary> /// The drink's cost in the US dollars. /// </summary> public override decimal Cost => default(decimal); } }
using NullObject.Abstract; namespace NullObject.Entities { public class SpriteDrink : Drink { /// <summary> /// The drink name. /// </summary> public override string Name => "Sprite"; /// <summary> /// The drink's cost in the US dollars. /// </summary> public override decimal Cost => 2; } }
mit
C#
db07178843e8c36b5cdf4651d98e712457d07efd
Update EntryType.cs
salmonthinlion/GoogleCloudPrintApi
GoogleCloudPrintApi/Models/Share/EntryType.cs
GoogleCloudPrintApi/Models/Share/EntryType.cs
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace GoogleCloudPrintApi.Models.Share { [JsonConverter(typeof(StringEnumConverter))] public enum EntryType { USER, GROUP, DOMAIN, PUBLIC } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace GoogleCloudPrintApi.Models.Share { [JsonConverter(typeof(StringEnumConverter))] public enum EntryType { USER, GROUP, DOMAIN } }
mit
C#
01aa5cb9364cdedec14379da08b4328caf8d9e80
fix test
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
test/WeihanLi.Common.Test/ProfilerTest.cs
test/WeihanLi.Common.Test/ProfilerTest.cs
using System.Threading; using Xunit; namespace WeihanLi.Common.Test { public class ProfilerTest { [Theory] [InlineData(200)] [InlineData(500)] [InlineData(1000)] public void StopWatchProfileTest(int delay) { var profiler = new StopwatchProfiler(); profiler.Start(); Thread.Sleep(delay * 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds >= delay); profiler.Restart(); Thread.Sleep(delay / 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds < delay); } } }
using System.Threading; using Xunit; namespace WeihanLi.Common.Test { public class ProfilerTest { [Theory] [InlineData(200)] [InlineData(500)] [InlineData(1000)] public void StopWatchProfileTest(int delay) { var profiler = new StopwatchProfiler(); profiler.Start(); Thread.Sleep(delay * 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds >= delay); profiler.Restart(); Thread.Sleep(delay / 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds < delay); profiler.Reset(); Assert.Equal(0, profiler.Elapsed.TotalMilliseconds); } } }
mit
C#
32ebde13fa16ed9d47e23ccc3c92ad9f7f47aefc
Update PathToEnlightenment.cs
NotMyself/DotNetCoreKoans
Koans/PathToEnlightenment.cs
Koans/PathToEnlightenment.cs
using System; using DotNetCoreKoans.Engine; namespace DotNetCoreKoans.Koans { public class PathToEnlightenment : Path { public PathToEnlightenment() { Types = new Type[] { typeof(AboutAsserts), typeof(AboutNull), typeof(AboutArrays), typeof(AboutArrayAssignment), typeof(AboutStrings), typeof(AboutFloats), typeof(AboutDecimals), typeof(AboutInheritance), typeof(AboutMethods), typeof(AboutControlStatements), typeof(AboutGenericContainers), typeof(AboutDelegates), typeof(AboutLambdas), typeof(AboutLinq), typeof(AboutBitwiseAndShiftOperator), typeof(AboutGlobalization) }; } } }
using System; using DotNetCoreKoans.Engine; namespace DotNetCoreKoans.Koans { public class PathToEnlightenment : Path { public PathToEnlightenment() { Types = new Type[] { typeof(AboutAsserts), typeof(AboutNull), typeof(AboutArrays), typeof(AboutArrayAssignment), typeof(AboutStrings), typeof(AboutFloats), typeof(AboutDecimals), typeof(AboutInheritance), typeof(AboutMethods), typeof(AboutControlStatements), typeof(AboutGenericContainers), typeof(AboutLambdas), typeof(AboutLinq), typeof(AboutBitwiseAndShiftOperator), typeof(AboutGlobalization) //TODO: disabled due to missing functionality in netcoreapp1.0 // it will be available in 1.1 see: // https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Array.cs#L1005 //typeof(AboutDelegates) }; } } }
mit
C#
35d0e96fb0803a839ff88e47b59cee21d4bfa949
Update FreezeFrogsTarget.cs
Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,uulltt/NitoriWare,Barleytree/NitoriWare
Assets/Resources/Microgames/FreezeFrogs/Scripts/FreezeFrogsTarget.cs
Assets/Resources/Microgames/FreezeFrogs/Scripts/FreezeFrogsTarget.cs
using UnityEngine; using System.Collections; public class FreezeFrogsTarget : MonoBehaviour { public float progress, progressFromBreath; public SpriteRenderer white; public Animator animator; public ParticleSystem[] particleSystems; new public AudioSource audio; void Start() { reset(); } public void reset() { progress = 0; animator.SetFloat("FrozenProgress", 0f); updateProgress(); for (int i = 0; i < particleSystems.Length; i++) { particleSystems[i].Stop(); particleSystems[i].SetParticles(new ParticleSystem.Particle[0], 0); } //transform.parent.GetComponent<Animator>().animation["bluh"].normalizedTime = 0f; } void Update () { if (progress < 1f) updateProgress(); } void updateProgress() { progress = Mathf.Min(1f, progress); Color color = white.color; color.a = progress; white.color = color; animator.SetFloat("FrozenProgress", progress); } void freeze() { progress = 1f; updateProgress(); for (int i = 0; i < particleSystems.Length;particleSystems[i].Play(), i++); audio.pitch = 1.35f * Time.timeScale; audio.Play(); } void OnTriggerEnter2D(Collider2D other) { if (progress < 1f && other.name == "Breath" && MicrogameTimer.instance.beatsLeft >= .5f) { progress += progressFromBreath; if (progress >= 1f) { freeze(); } } } }
using UnityEngine; using System.Collections; public class FreezeFrogsTarget : MonoBehaviour { public float progress, progressFromBreath; public SpriteRenderer white; public Animator animator; public ParticleSystem[] particleSystems; new public AudioSource audio; void Start() { reset(); } public void reset() { progress = 0; animator.SetFloat("FrozenProgress", 0f); updateProgress(); for (int i = 0; i < particleSystems.Length; i++) { particleSystems[i].Stop(); particleSystems[i].SetParticles(new ParticleSystem.Particle[0], 0); } //transform.parent.GetComponent<Animator>().animation["bluh"].normalizedTime = 0f; } void Update () { if (progress < 1f) updateProgress(); } void updateProgress() { progress = Mathf.Min(1f, progress); Color color = white.color; color.a = progress; white.color = color; animator.SetFloat("FrozenProgress", progress); } void freeze() { progress = 1f; updateProgress(); for (int i = 0; i < particleSystems.Length;particleSystems[i].Play(), i++); audio.pitch = 1.35f * Time.timeScale; audio.Play(); } void OnTriggerEnter2D(Collider2D other) { if (progress < 1f && other.name == "Breath" && MicrogameTimer.instance.beatsLeft >= .5f) { progress += progressFromBreath; } if (progress >= 1f) { freeze(); } } }
mit
C#
58d1364aeac0abfa0d6c577a31fc15b8c2f4565f
Bump for next version
BurningEnlightenment/libsodium-net,adamcaudill/libsodium-net,bitbeans/libsodium-net,fraga/libsodium-net,deckar01/libsodium-net,bitbeans/libsodium-net,fraga/libsodium-net,adamcaudill/libsodium-net,tabrath/libsodium-core,BurningEnlightenment/libsodium-net,deckar01/libsodium-net
libsodium-net/Properties/AssemblyInfo.cs
libsodium-net/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("libsodium-net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adam Caudill")] [assembly: AssemblyProduct("libsodium-net")] [assembly: AssemblyCopyright("Copyright © Adam Caudill 2013 - 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bac54bf6-5a39-4ab5-90f1-746a9d6b06f4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")]
using System.Reflection; using System.Runtime.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("libsodium-net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adam Caudill")] [assembly: AssemblyProduct("libsodium-net")] [assembly: AssemblyCopyright("Copyright © Adam Caudill 2013 - 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bac54bf6-5a39-4ab5-90f1-746a9d6b06f4")] // 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.7.0.0")] [assembly: AssemblyFileVersion("0.7.0.0")]
mit
C#
672604ffe649779254dda0aa7967396f7d5d464b
Build fix after namespace adjustment
madelson/MedallionOData,madelson/MedallionOData,madelson/MedallionOData
MedallionOData.Samples.Web/Models/Provider.cs
MedallionOData.Samples.Web/Models/Provider.cs
using Medallion.OData.Service.Sql; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Medallion.OData.Samples.Web.Models { public class Provider : DatabaseProvider { protected override string GetSqlTypeName(Trees.ODataExpressionType oDataType) { throw new NotImplementedException(); } protected override System.Collections.IEnumerable Execute(string sql, IReadOnlyList<Parameter> parameters, Type resultType) { throw new NotImplementedException(); } protected override int ExecuteCount(string sql, IReadOnlyList<Parameter> parameters) { throw new NotImplementedException(); } } }
using Medallion.OData.Sql; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Medallion.OData.Samples.Web.Models { public class Provider : DatabaseProvider { protected override string GetSqlTypeName(Trees.ODataExpressionType oDataType) { throw new NotImplementedException(); } protected override System.Collections.IEnumerable Execute(string sql, IReadOnlyList<Parameter> parameters, Type resultType) { throw new NotImplementedException(); } protected override int ExecuteCount(string sql, IReadOnlyList<Parameter> parameters) { throw new NotImplementedException(); } } }
mit
C#
604172bca0555166a6e99d96aa370e33f3872cc7
Add random position of card
TomaNikolov/MemoryGame
MemoryGames/MemoryGames/CardRandomPosition.cs
MemoryGames/MemoryGames/CardRandomPosition.cs
using System; using System.Collections.Generic; using System.Linq; namespace MemoryGames { public class CardRandomPosition { public static CardFace[,] GetRandomCardFace(int dimentionZero, int dimentionOne) { const int pair = 2; const int pairCount = 9; CardFace[,] cardFace = new CardFace[dimentionZero, dimentionOne]; Random randomGenerator = new Random(); List<CardFace> gameCard = new List<CardFace>(); int allCard = dimentionZero * dimentionOne; int currentGameCardPair = allCard / pair; string[] cardName = new string[pairCount] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; for (int element = 0, j = 0; element < allCard; element++, j++) { if (j == currentGameCardPair) { j = 0; } gameCard.Add(new CardFace(cardName[j])); } for (int row = 0; row < dimentionZero; row++) { for (int col = 0; col < dimentionOne; col++) { int randomElement = randomGenerator.Next(0, gameCard.Count); cardFace[row, col] = gameCard[randomElement]; gameCard.RemoveAt(randomElement); } } return cardFace; } } }
using System; using System.Collections.Generic; using System.Linq; namespace MemoryGames { public class CardRandomPosition { private List<CardFace> gameCard = new List<CardFace>(); private string[] cardName = new string[8];//here will be the name of the card private Random randomGenerator = new Random(); public static void FillMatrix() { } internal static CardFace[,] GetRandomCardFace() { throw new NotImplementedException(); } } }
mit
C#
fa56a0abd423ddaabe39513b262e13f96322ca5a
Add ReportGenerator.Format overload that calls on a instance
FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative
Creative/StatoBot/StatoBot.Reports/ReportGenerator.cs
Creative/StatoBot/StatoBot.Reports/ReportGenerator.cs
using System.IO; using Newtonsoft.Json; using StatoBot.Analytics; namespace StatoBot.Reports { public static class ReportGenerator { public static Report FromBot(AnalyzerBot bot) { return new Report( new ReportInput( bot.Analyzer.Statistics, BotInfo.FromBot(bot) ) ); } public static Report FromData(ReportInput input) { return new Report(input); } } }
using System.IO; using Newtonsoft.Json; using StatoBot.Analytics; namespace StatoBot.Reports { public static class ReportGenerator { public static Report ForAnalyzingBot(AnalyzerBot bot) { return new Report( new ReportInput( bot.Analyzer.Statistics, BotInfo.FromBot(bot) ) ); } public static Report ForData(ReportInput input) { return new Report(input); } } }
mit
C#
59b98d40c50beacb974b2d74d596cc9b2115c9d4
Remove unnecessary Any() clause before adding children
sergeyshushlyapin/Sitecore.FakeDb,hermanussen/Sitecore.FakeDb,pveller/Sitecore.FakeDb
src/Sitecore.FakeDb/DbItem.cs
src/Sitecore.FakeDb/DbItem.cs
namespace Sitecore.FakeDb { using System.Collections; using System.Collections.Generic; using System.Diagnostics; using Sitecore.Data; using Sitecore.Diagnostics; using Sitecore.FakeDb.Security.AccessControl; [DebuggerDisplay("{FullPath}, {ID.ToString()}")] public class DbItem : IEnumerable { public DbItem(string name) : this(name, ID.NewID) { } public DbItem(string name, ID id) : this(name, id, ID.Null) { } public DbItem(string name, ID id, ID templateId) { this.Name = !string.IsNullOrEmpty(name) ? name : id.ToShortID().ToString(); this.ID = id; this.TemplateID = templateId; this.Access = new DbItemAccess(); this.Fields = new DbFieldCollection(); this.Children = new DbItemChildCollection(this); this.VersionsCount = new Dictionary<string, int>(); } public DbItem(string name, ID id, ID templateId, params DbItem[] children) : this(name, id, templateId) { if (children != null) { foreach (var child in children) { this.Add(child); } } } public string Name { get; set; } public ID ID { get; private set; } public ID TemplateID { get; set; } public ID BranchId { get; set; } public DbFieldCollection Fields { get; private set; } public ID ParentID { get; set; } public string FullPath { get; set; } public ICollection<DbItem> Children { get; private set; } public DbItemAccess Access { get; set; } public IDictionary<string, int> VersionsCount { get; private set; } public void Add(string fieldName, string fieldValue) { Assert.ArgumentNotNull(fieldName, "fieldName"); this.Fields.Add(fieldName, fieldValue); } public void Add(ID fieldId, string fieldValue) { Assert.ArgumentNotNull(fieldId, "fieldId"); this.Fields.Add(fieldId, fieldValue); } public void Add(DbField field) { Assert.ArgumentNotNull(field, "field"); this.Fields.Add(field); } public void Add(DbItem child) { Assert.ArgumentNotNull(child, "child"); this.Children.Add(child); } IEnumerator IEnumerable.GetEnumerator() { return this.Children.GetEnumerator(); } } }
namespace Sitecore.FakeDb { using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Sitecore.Data; using Sitecore.Diagnostics; using Sitecore.FakeDb.Security.AccessControl; [DebuggerDisplay("{FullPath}, {ID.ToString()}")] public class DbItem : IEnumerable { public DbItem(string name) : this(name, ID.NewID) { } public DbItem(string name, ID id) : this(name, id, ID.Null) { } public DbItem(string name, ID id, ID templateId) { this.Name = !string.IsNullOrEmpty(name) ? name : id.ToShortID().ToString(); this.ID = id; this.TemplateID = templateId; this.Access = new DbItemAccess(); this.Fields = new DbFieldCollection(); this.Children = new DbItemChildCollection(this); this.VersionsCount = new Dictionary<string, int>(); } public DbItem(string name, ID id, ID templateId, params DbItem[] children) : this(name, id, templateId) { if (children != null && children.Any()) { foreach (var child in children) { this.Add(child); } } } public string Name { get; set; } public ID ID { get; private set; } public ID TemplateID { get; set; } public ID BranchId { get; set; } public DbFieldCollection Fields { get; private set; } public ID ParentID { get; set; } public string FullPath { get; set; } public ICollection<DbItem> Children { get; private set; } public DbItemAccess Access { get; set; } public IDictionary<string, int> VersionsCount { get; private set; } public void Add(string fieldName, string fieldValue) { Assert.ArgumentNotNull(fieldName, "fieldName"); this.Fields.Add(fieldName, fieldValue); } public void Add(ID fieldId, string fieldValue) { Assert.ArgumentNotNull(fieldId, "fieldId"); this.Fields.Add(fieldId, fieldValue); } public void Add(DbField field) { Assert.ArgumentNotNull(field, "field"); this.Fields.Add(field); } public void Add(DbItem child) { Assert.ArgumentNotNull(child, "child"); this.Children.Add(child); } IEnumerator IEnumerable.GetEnumerator() { return this.Children.GetEnumerator(); } } }
mit
C#
929b5c7951c29e8cf82ba56715d6e88a9aaaf96c
Add display attributes. Fix #98
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer/Models/InvoicingModels/CreateInvoiceModel.cs
BTCPayServer/Models/InvoicingModels/CreateInvoiceModel.cs
using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Validation; using System.ComponentModel; namespace BTCPayServer.Models.InvoicingModels { public class CreateInvoiceModel { public CreateInvoiceModel() { Currency = "USD"; } [Required] public decimal? Amount { get; set; } [Required] public string Currency { get; set; } [Required] public string StoreId { get; set; } public string OrderId { get; set; } [DisplayName("Item Description")] public string ItemDesc { get; set; } [DisplayName("POS Data")] public string PosData { get; set; } [EmailAddress] public string BuyerEmail { get; set; } [EmailAddress] [DisplayName("Notification Email")] public string NotificationEmail { get; set; } [Uri] [DisplayName("Notification Url")] public string NotificationUrl { get; set; } public SelectList Stores { get; set; } [DisplayName("Supported Transaction Currencies")] public List<string> SupportedTransactionCurrencies { get; set; } [DisplayName("Available Payment Methods")] public SelectList AvailablePaymentMethods { get; set; } } }
using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Validation; namespace BTCPayServer.Models.InvoicingModels { public class CreateInvoiceModel { public CreateInvoiceModel() { Currency = "USD"; } [Required] public decimal? Amount { get; set; } [Required] public string Currency { get; set; } [Required] public string StoreId { get; set; } public string OrderId { get; set; } public string ItemDesc { get; set; } public string PosData { get; set; } [EmailAddress] public string BuyerEmail { get; set; } [EmailAddress] public string NotificationEmail { get; set; } [Uri] public string NotificationUrl { get; set; } public SelectList Stores { get; set; } public List<string> SupportedTransactionCurrencies { get; set; } public SelectList AvailablePaymentMethods { get; set; } } }
mit
C#
8b970803cea8c03015079207478bb743dbb215a9
Revert "Update SocketThread"
sguertl/Flying_Pi,sguertl/Flying_Pi,sguertl/Flying_Pi,sguertl/Flying_Pi
Dronection/Android/WiFi/Android_Wifi_Test/Android_Wifi_Test/SocketThread.cs
Dronection/Android/WiFi/Android_Wifi_Test/Android_Wifi_Test/SocketThread.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 Java.Lang; using Java.Net; namespace Android_Wifi_Test { public class SocketThread : Thread { Socket mSocket; public SocketThread(ref Socket socket) { mSocket = socket; } public override void Run() { } } }
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 Java.Lang; using Java.Net; namespace Android_Wifi_Test { public class SocketThread : Thread { private Socket mSocket; private readonly string address = "172.24.1.1"; private readonly int port = 5050; public SocketThread(ref Socket socket) { mSocket = socket; } public override void Run() { mSocket = new Socket(address, port); } } }
apache-2.0
C#
abee6c62e7c6201fceae74cd169b000f94545e5d
Save List.aspx filter after insert new record
ernado-x/X.DynamicData,ernado-x/X.DynamicData,ernado-x/X.DynamicData
Site/DynamicData/PageTemplates/Insert.aspx.cs
Site/DynamicData/PageTemplates/Insert.aspx.cs
using System; using System.Web.DynamicData; using System.Web.UI.WebControls; using X.DynamicData.Core; namespace Site { public partial class Insert : XPage { protected void Page_Init(object sender, EventArgs e) { CheckPartialRendering(_table); FormView1.SetMetaTable(_table, _table.GetColumnValuesFromRoute(Context)); DetailsDataSource.EntityTypeFilter = _table.EntityType.Name; } protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e) { if (e.CommandName == DataControlCommands.CancelCommandName) { Response.Redirect(_table.ListActionPath); } } protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) { if (e.Exception == null || e.ExceptionHandled) { var url = _table.ListActionPath + Request.Url.Query; //for saving filter on table Response.Redirect(url); } else { ShowMessage(e.Exception); e.ExceptionHandled = true; } } } }
using System; using System.Web.DynamicData; using System.Web.UI.WebControls; using X.DynamicData.Core; namespace Site { public partial class Insert : XPage { protected void Page_Init(object sender, EventArgs e) { CheckPartialRendering(_table); FormView1.SetMetaTable(_table, _table.GetColumnValuesFromRoute(Context)); DetailsDataSource.EntityTypeFilter = _table.EntityType.Name; } protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e) { if (e.CommandName == DataControlCommands.CancelCommandName) { Response.Redirect(_table.ListActionPath); } } protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) { if (e.Exception == null || e.ExceptionHandled) { Response.Redirect(_table.ListActionPath); } else { ShowMessage(e.Exception); e.ExceptionHandled = true; } } } }
mit
C#
64f20d5b47ecfd62269764a8c360be60d3910614
Test needs to be public
zhoffice/nodejstools,hagb4rd/nodejstools,hoanhtien/nodejstools,necroscope/nodejstools,bowdenk7/nodejstools,mjbvz/nodejstools,paladique/nodejstools,Microsoft/nodejstools,redabakr/nodejstools,paladique/nodejstools,paladique/nodejstools,lukedgr/nodejstools,bowdenk7/nodejstools,paulvanbrenk/nodejstools,np83/nodejstools,avitalb/nodejstools,AustinHull/nodejstools,np83/nodejstools,kant2002/nodejstools,np83/nodejstools,redabakr/nodejstools,lukedgr/nodejstools,nareshjo/nodejstools,hoanhtien/nodejstools,AustinHull/nodejstools,paulvanbrenk/nodejstools,paladique/nodejstools,ahmad-farid/nodejstools,munyirik/nodejstools,np83/nodejstools,nareshjo/nodejstools,hoanhtien/nodejstools,chanchaldabriya/nodejstools,hagb4rd/nodejstools,mjbvz/nodejstools,munyirik/nodejstools,ahmad-farid/nodejstools,paulvanbrenk/nodejstools,mauricionr/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools,zhoffice/nodejstools,mauricionr/nodejstools,bowdenk7/nodejstools,necroscope/nodejstools,munyirik/nodejstools,bossvn/nodejstools,bowdenk7/nodejstools,kant2002/nodejstools,np83/nodejstools,zhoffice/nodejstools,redabakr/nodejstools,hoanhtien/nodejstools,nareshjo/nodejstools,lukedgr/nodejstools,ahmad-farid/nodejstools,hoanhtien/nodejstools,mjbvz/nodejstools,munyirik/nodejstools,mousetraps/nodejstools,munyirik/nodejstools,chanchaldabriya/nodejstools,hagb4rd/nodejstools,hagb4rd/nodejstools,lukedgr/nodejstools,necroscope/nodejstools,zhoffice/nodejstools,necroscope/nodejstools,mousetraps/nodejstools,chanchaldabriya/nodejstools,mjbvz/nodejstools,AustinHull/nodejstools,redabakr/nodejstools,paulvanbrenk/nodejstools,zhoffice/nodejstools,redabakr/nodejstools,ahmad-farid/nodejstools,paladique/nodejstools,bossvn/nodejstools,mjbvz/nodejstools,mauricionr/nodejstools,kant2002/nodejstools,mauricionr/nodejstools,lukedgr/nodejstools,nareshjo/nodejstools,kant2002/nodejstools,bowdenk7/nodejstools,bossvn/nodejstools,mauricionr/nodejstools,Microsoft/nodejstools,paulvanbrenk/nodejstools,nareshjo/nodejstools,ahmad-farid/nodejstools,avitalb/nodejstools,hagb4rd/nodejstools,bossvn/nodejstools,AustinHull/nodejstools,mousetraps/nodejstools,AustinHull/nodejstools,bossvn/nodejstools,mousetraps/nodejstools,kant2002/nodejstools,chanchaldabriya/nodejstools,Microsoft/nodejstools,avitalb/nodejstools,necroscope/nodejstools,chanchaldabriya/nodejstools,avitalb/nodejstools,avitalb/nodejstools,mousetraps/nodejstools
Nodejs/Tests/AnalysisTests/SerializedAnalysisTests.cs
Nodejs/Tests/AnalysisTests/SerializedAnalysisTests.cs
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using Microsoft.NodejsTools.Analysis; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AnalysisTests { [TestClass] public class SerializedAnalysisTests : AnalysisTests { internal override ModuleAnalysis ProcessText(string text) { return SerializationTests.RoundTrip(ProcessOneText(text)); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using Microsoft.NodejsTools.Analysis; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AnalysisTests { [TestClass] internal class SerializedAnalysisTests : AnalysisTests { internal override ModuleAnalysis ProcessText(string text) { return SerializationTests.RoundTrip(ProcessOneText(text)); } } }
apache-2.0
C#
ec79cd3123731a119f7e61f4a5751f28dcd01a8b
Set invariant culture for BooleanOpacityConverter parse operation. Closes #6.
hartez/TodotxtTouch.WindowsPhone
TodotxtTouch.WindowsPhone/ValueConverters/BooleanOpacityConverter.cs
TodotxtTouch.WindowsPhone/ValueConverters/BooleanOpacityConverter.cs
using System; using System.Globalization; using System.Windows.Data; namespace TodotxtTouch.WindowsPhone.ValueConverters { public class BooleanOpacityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double opacity = 1.0; if (parameter != null) { opacity = double.Parse(parameter.ToString(), CultureInfo.InvariantCulture); } if((bool)value) { return opacity; } return 1.0; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }
using System; using System.Globalization; using System.Windows.Data; namespace TodotxtTouch.WindowsPhone.ValueConverters { public class BooleanOpacityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double opacity = 1.0; if (parameter != null) { opacity = double.Parse(parameter.ToString()); } if((bool)value) { return opacity; } return 1.0; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }
mit
C#
e2e6b8e4cb174d46d50812887e13d8c8e1657654
Allow filtering weapons by unit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/API/WeaponsController.cs
Battery-Commander.Web/Controllers/API/WeaponsController.cs
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class WeaponsController : ApiController { public WeaponsController(Database db) : base(db) { // Nothing to do here } [HttpGet] public async Task<IActionResult> Get(int? unit) { // GET: api/weapons return Ok( await db .Weapons .Where(weapon => !unit.HasValue || weapon.UnitId == unit) .Select(_ => new { _.Id, _.OpticSerial, _.OpticType, _.Serial, _.StockNumber, _.Type, _.UnitId }) .ToListAsync()); } [HttpPost] public async Task<IActionResult> Post([FromBody]Weapon weapon) { await db.Weapons.AddAsync(weapon); await db.SaveChangesAsync(); return Ok(); } [HttpDelete] public async Task<IActionResult> Delete(int id) { var weapon = await db.Weapons.FindAsync(id); db.Weapons.Remove(weapon); await db.SaveChangesAsync(); return Ok(); } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class WeaponsController : ApiController { public WeaponsController(Database db) : base(db) { // Nothing to do here } [HttpGet] public async Task<IEnumerable<dynamic>> Get() { // GET: api/weapons return await db .Weapons .Select(_ => new { _.Id, _.OpticSerial, _.OpticType, _.Serial, _.StockNumber, _.Type, _.UnitId }) .ToListAsync(); } [HttpPost] public async Task<IActionResult> Post([FromBody]Weapon weapon) { await db.Weapons.AddAsync(weapon); await db.SaveChangesAsync(); return Ok(); } [HttpDelete] public async Task<IActionResult> Delete(int id) { var weapon = await db.Weapons.FindAsync(id); db.Weapons.Remove(weapon); await db.SaveChangesAsync(); return Ok(); } } }
mit
C#
bb4bbbb8a88ad9554a81975b29a173d1e47216c8
Make ReconnectTest async behavior consistent (#2728)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.IntegrationTests/Tests/Networking/ReconnectTest.cs
Content.IntegrationTests/Tests/Networking/ReconnectTest.cs
using System.Threading.Tasks; using NUnit.Framework; using Robust.Client.Console; using Robust.Shared.Interfaces.Network; using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests.Networking { [TestFixture] public class ReconnectTest : ContentIntegrationTest { [Test] public async Task Test() { var client = StartClient(); var server = StartServer(); await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); // Connect. client.SetConnectTarget(server); await client.WaitPost(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null)); // Run some ticks for the handshake to complete and such. await RunTicksSync(client, server, 10); await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); await client.WaitPost(() => IoCManager.Resolve<IClientConsole>().ProcessCommand("disconnect")); // Run some ticks for the disconnect to complete and such. await RunTicksSync(client, server, 5); await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); // Reconnect. client.SetConnectTarget(server); await client.WaitPost(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null)); // Run some ticks for the handshake to complete and such. await RunTicksSync(client, server, 10); await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); } } }
using System.Threading.Tasks; using NUnit.Framework; using Robust.Client.Console; using Robust.Shared.Interfaces.Network; using Robust.Shared.IoC; namespace Content.IntegrationTests.Tests.Networking { [TestFixture] public class ReconnectTest : ContentIntegrationTest { [Test] public async Task Test() { var client = StartClient(); var server = StartServer(); await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); // Connect. client.SetConnectTarget(server); client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null)); // Run some ticks for the handshake to complete and such. for (var i = 0; i < 10; i++) { server.RunTicks(1); await server.WaitIdleAsync(); client.RunTicks(1); await client.WaitIdleAsync(); } await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); client.Post(() => IoCManager.Resolve<IClientConsole>().ProcessCommand("disconnect")); // Run some ticks for the disconnect to complete and such. for (var i = 0; i < 5; i++) { server.RunTicks(1); await server.WaitIdleAsync(); client.RunTicks(1); await client.WaitIdleAsync(); } await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); // Reconnect. client.SetConnectTarget(server); client.Post(() => IoCManager.Resolve<IClientNetManager>().ClientConnect(null, 0, null)); // Run some ticks for the handshake to complete and such. for (var i = 0; i < 10; i++) { server.RunTicks(1); await server.WaitIdleAsync(); client.RunTicks(1); await client.WaitIdleAsync(); } await Task.WhenAll(client.WaitIdleAsync(), server.WaitIdleAsync()); } } }
mit
C#
f002dae2e57c0f2ac33b430f7117a08b12879ddd
Check configuration values are set in tests
auth0/auth0.net,auth0/auth0.net
tests/Auth0.ManagementApi.IntegrationTests/TestBase.cs
tests/Auth0.ManagementApi.IntegrationTests/TestBase.cs
using System; using System.Threading.Tasks; using Auth0.AuthenticationApi; using Auth0.AuthenticationApi.Models; using Microsoft.Extensions.Configuration; namespace Auth0.Tests.Shared { public class TestBase { private readonly IConfigurationRoot _config; public TestBase() { _config = new ConfigurationBuilder() .AddJsonFile("client-secrets.json", true) .AddEnvironmentVariables() .Build(); } protected async Task<string> GenerateManagementApiToken() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); // Get the access token var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest { ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"), Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE") }); return token.AccessToken; } protected string GetVariable(string variableName) { var value = _config[variableName]; if (String.IsNullOrEmpty(value)) throw new ArgumentOutOfRangeException($"Configuration value '{variableName}' has not been set."); return value; } } }
using System.Threading.Tasks; using Auth0.AuthenticationApi; using Auth0.AuthenticationApi.Models; using Microsoft.Extensions.Configuration; namespace Auth0.Tests.Shared { public class TestBase { private readonly IConfigurationRoot _config; public TestBase() { _config = new ConfigurationBuilder() .AddJsonFile("client-secrets.json", true) .AddEnvironmentVariables() .Build(); } protected async Task<string> GenerateManagementApiToken() { var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")); // Get the access token var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest { ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"), ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"), Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE") }); return token.AccessToken; } protected string GetVariable(string variableName) { return _config[variableName]; } } }
mit
C#
2a5654edb95f916d90c481f5a72f5e4c4c83413f
Remove an unused using
tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
tests/Tgstation.Server.Host.Tests/TestServerFactory.cs
tests/Tgstation.Server.Host.Tests/TestServerFactory.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using Tgstation.Server.Host.IO; using Tgstation.Server.Host.System; namespace Tgstation.Server.Host.Tests { /// <summary> /// Tests for <see cref="ServerFactory"/> /// </summary> [TestClass] public sealed class TestServerFactory { [TestMethod] public void TestContructor() { Assert.ThrowsException<ArgumentNullException>(() => new ServerFactory(null, null)); IAssemblyInformationProvider assemblyInformationProvider = Mock.Of<IAssemblyInformationProvider>(); Assert.ThrowsException<ArgumentNullException>(() => new ServerFactory(assemblyInformationProvider, null)); IIOManager ioManager = Mock.Of<IIOManager>(); new ServerFactory(assemblyInformationProvider, ioManager); } [TestMethod] public void TestWorksWithoutUpdatePath() { var factory = ServerFactory.CreateDefault(); Assert.ThrowsException<ArgumentNullException>(() => factory.CreateServer(null, null)); factory.CreateServer(Array.Empty<string>(), null); } [TestMethod] public void TestWorksWithUpdatePath() { var factory = ServerFactory.CreateDefault(); const string Path = "/test"; Assert.ThrowsException<ArgumentNullException>(() => factory.CreateServer(null, null)); Assert.ThrowsException<ArgumentNullException>(() => factory.CreateServer(null, Path)); factory.CreateServer(Array.Empty<string>(), Path); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using Tgstation.Server.Host.Core; using Tgstation.Server.Host.IO; using Tgstation.Server.Host.System; namespace Tgstation.Server.Host.Tests { /// <summary> /// Tests for <see cref="ServerFactory"/> /// </summary> [TestClass] public sealed class TestServerFactory { [TestMethod] public void TestContructor() { Assert.ThrowsException<ArgumentNullException>(() => new ServerFactory(null, null)); IAssemblyInformationProvider assemblyInformationProvider = Mock.Of<IAssemblyInformationProvider>(); Assert.ThrowsException<ArgumentNullException>(() => new ServerFactory(assemblyInformationProvider, null)); IIOManager ioManager = Mock.Of<IIOManager>(); new ServerFactory(assemblyInformationProvider, ioManager); } [TestMethod] public void TestWorksWithoutUpdatePath() { var factory = ServerFactory.CreateDefault(); Assert.ThrowsException<ArgumentNullException>(() => factory.CreateServer(null, null)); factory.CreateServer(Array.Empty<string>(), null); } [TestMethod] public void TestWorksWithUpdatePath() { var factory = ServerFactory.CreateDefault(); const string Path = "/test"; Assert.ThrowsException<ArgumentNullException>(() => factory.CreateServer(null, null)); Assert.ThrowsException<ArgumentNullException>(() => factory.CreateServer(null, Path)); factory.CreateServer(Array.Empty<string>(), Path); } } }
agpl-3.0
C#
72a2199894f07e5798d6b90aaa539f932cabf3e9
Set version 3.0.0.0
grantcolley/dipmapper
DevelopmentInProgress.DipMapper/Properties/AssemblyInfo.cs
DevelopmentInProgress.DipMapper/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("DipMapper")] [assembly: AssemblyDescription("A flyweight object mapper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Development In Progress Ltd")] [assembly: AssemblyProduct("DipMapper")] [assembly: AssemblyCopyright("Copyright © Development In Progress Ltd 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("1e8f6e16-736e-4d53-875b-c0921dfc20d1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.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("DipMapper")] [assembly: AssemblyDescription("A flyweight object mapper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Development In Progress Ltd")] [assembly: AssemblyProduct("DipMapper")] [assembly: AssemblyCopyright("Copyright © Development In Progress Ltd 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("1e8f6e16-736e-4d53-875b-c0921dfc20d1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
apache-2.0
C#
892f0729e7262dc48eb6a0a985f4a9fb7470f75a
Comment out the resource not found fix for .NET Core
quartz-software/kephas,quartz-software/kephas
Samples/Configuration/ConfigurationConsole/Program.cs
Samples/Configuration/ConfigurationConsole/Program.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the program class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConfigurationConsole { using System.Runtime.Loader; using System.Threading.Tasks; using StartupConsole.Application; class Program { public static async Task Main(string[] args) { //AssemblyLoadContext.Default.Resolving += (context, name) => // { // if (name.Name.EndsWith(".resources")) // { // return null; // } // return null; // }; await new ConsoleShell().BootstrapAsync(args); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Implements the program class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConfigurationConsole { using System.Runtime.Loader; using System.Threading.Tasks; using StartupConsole.Application; class Program { public static async Task Main(string[] args) { AssemblyLoadContext.Default.Resolving += (context, name) => { if (name.Name.EndsWith(".resources")) { return null; } return null; }; await new ConsoleShell().BootstrapAsync(args); } } }
mit
C#
04922088c3d1a4ff484adfb3476dae391f62bb99
increase version
tinohager/Nager.AmazonProductAdvertising,tinohager/Nager.AmazonProductAdvertising
Nager.AmazonProductAdvertising/Properties/AssemblyInfo.cs
Nager.AmazonProductAdvertising/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("Nager.AmazonProductAdvertising")] [assembly: AssemblyDescription("Amazon ProductAdvertising")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("nager.at")] [assembly: AssemblyProduct("Nager.AmazonProductAdvertising")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("026a9ee3-9a48-48a1-9026-1573f2e8a85e")] // 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.4.0")] [assembly: AssemblyFileVersion("1.0.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("Nager.AmazonProductAdvertising")] [assembly: AssemblyDescription("Amazon ProductAdvertising")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("nager.at")] [assembly: AssemblyProduct("Nager.AmazonProductAdvertising")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("026a9ee3-9a48-48a1-9026-1573f2e8a85e")] // 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.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")]
mit
C#
3667d5a7bf3f2eb7138f67af1b4e75389b014526
Add missing license banner
StefanoRaggi/Lean,StefanoRaggi/Lean,jameschch/Lean,jameschch/Lean,JKarathiya/Lean,jameschch/Lean,QuantConnect/Lean,AlexCatarino/Lean,AlexCatarino/Lean,JKarathiya/Lean,StefanoRaggi/Lean,QuantConnect/Lean,jameschch/Lean,StefanoRaggi/Lean,QuantConnect/Lean,AlexCatarino/Lean,QuantConnect/Lean,JKarathiya/Lean,jameschch/Lean,AlexCatarino/Lean,JKarathiya/Lean,StefanoRaggi/Lean
Tests/Algorithm/Framework/NotifiedSecurityChangesTests.cs
Tests/Algorithm/Framework/NotifiedSecurityChangesTests.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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; using NUnit.Framework; using QuantConnect.Algorithm.Framework; using QuantConnect.Data.UniverseSelection; using QuantConnect.Securities; using QuantConnect.Securities.Equity; namespace QuantConnect.Tests.Algorithm.Framework { [TestFixture] public class NotifiedSecurityChangesTests { [Test] public void UpdateCallsDisposeOnDisposableInstances() { var disposable = new Disposable(Symbols.SPY); var dictionary = new Dictionary<Symbol, Disposable> { [Symbols.SPY] = disposable }; var SPY = new Equity( Symbols.SPY, SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), new Cash("USD", 1m, 1m), SymbolProperties.GetDefault("USD"), ErrorCurrencyConverter.Instance, new RegisteredSecurityDataTypesProvider(), new SecurityCache() ); var changes = SecurityChanges.Removed(SPY); NotifiedSecurityChanges.UpdateDictionary(dictionary, changes, security => security.Symbol, security => new Disposable(security.Symbol) ); Assert.IsTrue(disposable.Disposed); } private class Disposable : IDisposable { public bool Disposed { get; private set; } public Symbol Symbol { get; private set; } public Disposable(Symbol symbol) { Symbol = symbol; } public void Dispose() { Disposed = true; } } } }
using System; using System.Collections.Generic; using NUnit.Framework; using QuantConnect.Algorithm.Framework; using QuantConnect.Data.UniverseSelection; using QuantConnect.Securities; using QuantConnect.Securities.Equity; namespace QuantConnect.Tests.Algorithm.Framework { [TestFixture] public class NotifiedSecurityChangesTests { [Test] public void UpdateCallsDisposeOnDisposableInstances() { var disposable = new Disposable(Symbols.SPY); var dictionary = new Dictionary<Symbol, Disposable> { [Symbols.SPY] = disposable }; var SPY = new Equity( Symbols.SPY, SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), new Cash("USD", 1m, 1m), SymbolProperties.GetDefault("USD"), ErrorCurrencyConverter.Instance, new RegisteredSecurityDataTypesProvider(), new SecurityCache() ); var changes = SecurityChanges.Removed(SPY); NotifiedSecurityChanges.UpdateDictionary(dictionary, changes, security => security.Symbol, security => new Disposable(security.Symbol) ); Assert.IsTrue(disposable.Disposed); } private class Disposable : IDisposable { public bool Disposed { get; private set; } public Symbol Symbol { get; private set; } public Disposable(Symbol symbol) { Symbol = symbol; } public void Dispose() { Disposed = true; } } } }
apache-2.0
C#
6ae7367c019a3b4360580e3e892bb73002a48eef
Prepare release 4.5.5 - update file version. Work Item #1926
CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork
trunk/Solutions/CslaGenFork/Properties/AssemblyInfo.cs
trunk/Solutions/CslaGenFork/Properties/AssemblyInfo.cs
using System; 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("Csla Generator Fork")] [assembly: AssemblyDescription("CSLA.NET Business Objects and Data Access Layer code generation tool.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CslaGenFork Project")] [assembly: AssemblyProduct("Csla Generator Fork")] [assembly: AssemblyCopyright("Copyright CslaGen Project 2007, 2009\r\nCopyright Tiago Freitas Leal 2009, 2015")] [assembly: AssemblyTrademark("All Rights Reserved.")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyVersion("4.5.5")] [assembly: AssemblyFileVersionAttribute("4.5.5")] [assembly: GuidAttribute("5c019c4f-d2ab-40dd-9860-70bd603b6017")] [assembly: ComVisibleAttribute(false)]
using System; 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("Csla Generator Fork")] [assembly: AssemblyDescription("CSLA.NET Business Objects and Data Access Layer code generation tool.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CslaGenFork Project")] [assembly: AssemblyProduct("Csla Generator Fork")] [assembly: AssemblyCopyright("Copyright CslaGen Project 2007, 2009\r\nCopyright Tiago Freitas Leal 2009, 2015")] [assembly: AssemblyTrademark("All Rights Reserved.")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyVersion("4.5.4")] [assembly: AssemblyFileVersionAttribute("4.5.4")] [assembly: GuidAttribute("5c019c4f-d2ab-40dd-9860-70bd603b6017")] [assembly: ComVisibleAttribute(false)]
mit
C#
6fdd3bf7d41b4ec0bb0306bafd11f859c51e666f
Fix filtering in logging
rowanmiller/UnicornStore,rowanmiller/UnicornStore,rowanmiller/UnicornStore
UnicornStore/src/UnicornStore/Logging/SqlLoggerProvider.cs
UnicornStore/src/UnicornStore/Logging/SqlLoggerProvider.cs
using System; using System.Linq; using Microsoft.Framework.Logging; using Microsoft.Data.Entity.Update; using Microsoft.Data.Entity.Query; namespace UnicornStore.Logging { public class SqlLoggerProvider : ILoggerProvider { private static readonly string[] _whitelist = new string[] { typeof(BatchExecutor).FullName, typeof(QueryContextFactory).FullName }; public ILogger CreateLogger(string name) { if(_whitelist.Contains(name)) { return new SqlLogger(); } return NullLogger.Instance; } public void Dispose() { } } }
using System; using System.Linq; using Microsoft.Framework.Logging; namespace UnicornStore.Logging { public class SqlLoggerProvider : ILoggerProvider { private static readonly string[] _whitelist = new string[] { "Microsoft.Data.Entity.Relational.Update.BatchExecutor", "Microsoft.Data.Entity.Query.QueryContextFactory" }; public ILogger CreateLogger(string name) { if(_whitelist.Contains(name)) { return new SqlLogger(); } return NullLogger.Instance; } public void Dispose() { } } }
apache-2.0
C#
55f7f0fbb66936d8133297e176b0dde794c4950f
Remove user service refs
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/API/UsersController.cs
Battery-Commander.Web/Controllers/API/UsersController.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class UsersController : ApiController { private static readonly HttpClient http = new HttpClient(); private readonly IOptions<Auth0Settings> auth0; public UsersController(Database db, IOptions<Auth0Settings> auth0) : base(db) { this.auth0 = auth0; } [HttpPost("~/api/auth"), AllowAnonymous] public async Task<IActionResult> Authenticate(String username, String password) { var request = JsonConvert.SerializeObject(new { client_id = auth0.Value.ClientId, client_secret = auth0.Value.ClientSecret, audience = auth0.Value.ApiIdentifier, grant_type = "password", username, password }); var result = await http.PostAsync($"https://{auth0.Value.Domain}/oauth/token", new StringContent(request, Encoding.UTF8, "application/json")); var json = await result.Content.ReadAsStringAsync(); var model = JsonConvert.DeserializeAnonymousType(json, new { access_token = "", token_type = "", expires_in = 0 }); return Json(model); } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class UsersController : ApiController { private static readonly HttpClient http = new HttpClient(); private readonly IOptions<Auth0Settings> auth0; private async Task<Soldier> CurrentUser() => await UserService.FindAsync(db, User); public UsersController(Database db, IOptions<Auth0Settings> auth0) : base(db) { this.auth0 = auth0; } [HttpPost("~/api/auth"), AllowAnonymous] public async Task<IActionResult> Authenticate(String username, String password) { var request = JsonConvert.SerializeObject(new { client_id = auth0.Value.ClientId, client_secret = auth0.Value.ClientSecret, audience = auth0.Value.ApiIdentifier, grant_type = "password", username, password }); var result = await http.PostAsync($"https://{auth0.Value.Domain}/oauth/token", new StringContent(request, Encoding.UTF8, "application/json")); var json = await result.Content.ReadAsStringAsync(); var model = JsonConvert.DeserializeAnonymousType(json, new { access_token = "", token_type = "", expires_in = 0 }); return Json(model); } [HttpGet("me")] public async Task<dynamic> Current() { // GET: api/users/me var user = await CurrentUser(); if (user == null) return StatusCode((int)HttpStatusCode.BadRequest); return new { user.Id, user.FirstName, user.LastName, user.CivilianEmail }; } } }
mit
C#
382b2648017a9b5f38b175d608652dddf65496b4
update interface
CatLib/Framework,yb199478/catlib
Assets/Scripts/System/Lib/API/Translator/ITranslator.cs
Assets/Scripts/System/Lib/API/Translator/ITranslator.cs
 using UnityEngine; namespace CatLib.API.Translator{ /// <summary> /// 翻译(国际化) /// </summary> public interface ITranslator{ /// <summary> /// 翻译内容 /// </summary> /// <param name="key">键</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string Trans(string key , params string[] replace); /// <summary> /// 翻译内容 /// </summary> /// <param name="key">键</param> /// <param name="local">本次翻译的语言</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string Trans(string key , SystemLanguage local , params string[] replace); /// <summary> /// 翻译内容的复数形式 /// </summary> /// <param name="key">键</param> /// <param name="number">数值</param> /// <param name="local">本次翻译的语言</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string TransChoice(string key, int number, SystemLanguage local , params string[] replace); /// <summary> /// 翻译内容的复数形式 /// </summary> /// <param name="key">键</param> /// <param name="num">数值</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string TransChoice(string key, int number, params string[] replace); /// <summary> /// 获取默认本地语言 /// </summary> /// <returns></returns> SystemLanguage GetLocale(); /// <summary> /// 设定默认本地语言 /// </summary> /// <param name="local">设定默认本地语言</param> /// <returns></returns> void SetLocale(SystemLanguage local); } }
 using UnityEngine; namespace CatLib.API.Translator{ /// <summary> /// 翻译(国际化) /// </summary> public interface ITranslator{ /// <summary> /// 翻译内容 /// </summary> /// <param name="key">键</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string Trans(string key , params string[] replace); /// <summary> /// 翻译内容 /// </summary> /// <param name="key">键</param> /// <param name="local">本次翻译的语言</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string Trans(string key , SystemLanguage local , params string[] replace); /// <summary> /// 翻译内容的复数形式 /// </summary> /// <param name="key">键</param> /// <param name="number">数值</param> /// <param name="local">本次翻译的语言</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string TransChoice(string key, int number, SystemLanguage local , params string[] replace); /// <summary> /// 翻译内容的复数形式 /// </summary> /// <param name="key">键</param> /// <param name="num">数值</param> /// <param name="replace">替换翻译内容的占位符</param> /// <returns></returns> string TransChoice(string key, int number, params string[] replace); /// <summary> /// 获取默认本地语言 /// </summary> /// <returns></returns> string GetLocale(); /// <summary> /// 设定默认本地语言 /// </summary> /// <param name="local">设定默认本地语言</param> /// <returns></returns> void SetLocale(SystemLanguage local); } }
unknown
C#
e4053e2a7a8f9cfdabc15b1b579c1a3483d98140
Change widget action bar "Margin" default value
danielchalmers/DesktopWidgets
DesktopWidgets/WidgetBase/Styles/WidgetActionBarStyle.cs
DesktopWidgets/WidgetBase/Styles/WidgetActionBarStyle.cs
using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.WidgetBase.Styles { [ExpandableObject] [DisplayName("Action Bar Style")] public class WidgetActionBarStyle : BorderStyleBase { public WidgetActionBarStyle() { BackgroundOpacity = 0.5; CornerRadius = new CornerRadius(4); BackgroundColor = Color.FromRgb(32, 32, 32); TextColor = Colors.WhiteSmoke; HorizontalAlignment = HorizontalAlignment.Center; VerticalAlignment = VerticalAlignment.Top; } [DisplayName("Visibility")] public TitlebarVisibilityMode VisibilityMode { get; set; } = TitlebarVisibilityMode.OnHover; [DisplayName("Dock")] public Dock Dock { get; set; } = Dock.Right; [DisplayName("Margin")] public Thickness Margin { get; set; } = new Thickness(10, 0, 0, 0); [DisplayName("Orientation")] public Orientation Orientation { get; set; } = Orientation.Vertical; [Category("Buttons")] [DisplayName("Button Font Size")] public int ButtonFontSize { get; set; } = 16; [Category("Buttons")] [DisplayName("Button Size (px)")] public double ButtonSize { get; set; } = 24; [Category("Buttons")] [DisplayName("Button Margin")] public Thickness ButtonMargin { get; set; } = new Thickness(0, 2, 0, 2); [Category("Name")] [DisplayName("Show Name")] public bool ShowName { get; set; } = false; [DisplayName("Stay Open Duration (ms)")] public int StayOpenDuration { get; set; } = 1500; } }
using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.WidgetBase.Styles { [ExpandableObject] [DisplayName("Action Bar Style")] public class WidgetActionBarStyle : BorderStyleBase { public WidgetActionBarStyle() { BackgroundOpacity = 0.5; CornerRadius = new CornerRadius(4); BackgroundColor = Color.FromRgb(32, 32, 32); TextColor = Colors.WhiteSmoke; HorizontalAlignment = HorizontalAlignment.Center; VerticalAlignment = VerticalAlignment.Top; } [DisplayName("Visibility")] public TitlebarVisibilityMode VisibilityMode { get; set; } = TitlebarVisibilityMode.OnHover; [DisplayName("Dock")] public Dock Dock { get; set; } = Dock.Right; [DisplayName("Margin")] public Thickness Margin { get; set; } = new Thickness(0); [DisplayName("Orientation")] public Orientation Orientation { get; set; } = Orientation.Vertical; [Category("Buttons")] [DisplayName("Button Font Size")] public int ButtonFontSize { get; set; } = 16; [Category("Buttons")] [DisplayName("Button Size (px)")] public double ButtonSize { get; set; } = 24; [Category("Buttons")] [DisplayName("Button Margin")] public Thickness ButtonMargin { get; set; } = new Thickness(0, 2, 0, 2); [Category("Name")] [DisplayName("Show Name")] public bool ShowName { get; set; } = false; [DisplayName("Stay Open Duration (ms)")] public int StayOpenDuration { get; set; } = 1500; } }
apache-2.0
C#
2da95e15e5902252789f95034966543c62e916b8
store in weather station's timezone
bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather
api/src/BellRichM.Weather.Api/Mapping/ConvertEpochTime.cs
api/src/BellRichM.Weather.Api/Mapping/ConvertEpochTime.cs
using AutoMapper; using BellRichM.Weather.Api.Data; using BellRichM.Weather.Api.Models; using System; namespace BellRichM.Weather.Api.Mapping { /// <summary> /// Converts the unix time on the observation model to a date and time on the observation. /// </summary> /// <remarks> /// <seealso cref="IMappingAction{src, dest}" /> /// </remarks> public class ConvertEpochTime : IMappingAction<ObservationModel, Observation> { /// <summary> /// Converts the unix time on the observation model to a date and time on the observation. /// </summary> /// <param name="source">The observation model.</param> /// <param name="destination">The observation.</param> /// <param name="context">The context.</param> public void Process(ObservationModel source, Observation destination, ResolutionContext context) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var dateTime = epoch.AddSeconds(destination.DateTime); var easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); // platform dependent var easternDateTime = TimeZoneInfo.ConvertTimeFromUtc(dateTime, easternTimeZone); destination.Year = easternDateTime.Year; destination.Month = easternDateTime.Month; destination.Day = easternDateTime.Day; destination.Hour = easternDateTime.Hour; destination.Minute = easternDateTime.Minute; var dayOfYearDate = new DateTime(2016, easternDateTime.Month, easternDateTime.Day); destination.DayOfYear = dayOfYearDate.DayOfYear; destination.Week = (destination.DayOfYear + 6) / 7; } } }
using AutoMapper; using BellRichM.Weather.Api.Data; using BellRichM.Weather.Api.Models; using System; namespace BellRichM.Weather.Api.Mapping { /// <summary> /// Converts the unix time on the observation model to a date and time on the observation. /// </summary> /// <remarks> /// <seealso cref="IMappingAction{src, dest}" /> /// </remarks> public class ConvertEpochTime : IMappingAction<ObservationModel, Observation> { /// <summary> /// Converts the unix time on the observation model to a date and time on the observation. /// </summary> /// <param name="source">The observation model.</param> /// <param name="destination">The observation.</param> /// <param name="context">The context.</param> public void Process(ObservationModel source, Observation destination, ResolutionContext context) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // UTC vs Eastern...??? var dateTime = epoch.AddSeconds(destination.DateTime); destination.Year = dateTime.Year; destination.Month = dateTime.Month; destination.Day = dateTime.Day; destination.Hour = dateTime.Hour; destination.Minute = dateTime.Minute; var dayOfYearDate = new DateTime(2016, dateTime.Month, dateTime.Day); destination.DayOfYear = dayOfYearDate.DayOfYear; destination.Week = (destination.DayOfYear + 6) / 7; } } }
mit
C#
49873ecfa7fba7a8978ddaac285dc79e1463b9cd
Fix Edit
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
src/backend/SO115App.Models/Servizi/CQRS/Commands/GestioneSoccorso/GestionePOS/EditPos/EditPosCommandHandler.cs
src/backend/SO115App.Models/Servizi/CQRS/Commands/GestioneSoccorso/GestionePOS/EditPos/EditPosCommandHandler.cs
//----------------------------------------------------------------------- // <copyright file="EditPosCommandHandler.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // SOVVF is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> //----------------------------------------------------------------------- using CQRS.Commands; using Newtonsoft.Json; using SO115App.Models.Classi.Pos; using SO115App.Models.Servizi.Infrastruttura.GestionePOS; using System.Collections.Generic; using System.IO; namespace SO115App.Models.Servizi.CQRS.Commands.GestioneSoccorso.GestionePOS.EditPos { public class EditPosCommandHandler : ICommandHandler<EditPosCommand> { internal string _resultPath { get => ResultPath; set => DirectoryCheck(value); } private string ResultPath; private readonly IEditPos _editPos; public EditPosCommandHandler(IEditPos editPos) => _editPos = editPos; public void Handle(EditPosCommand command) { command.Pos.ListaTipologieConvert = JsonConvert.DeserializeObject<List<TipologiaPos>>(command.Pos.ListaTipologie); _editPos.Edit(command.Pos); } private void DirectoryCheck(string path) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); ResultPath = path; } } }
//----------------------------------------------------------------------- // <copyright file="EditPosCommandHandler.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // SOVVF is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> //----------------------------------------------------------------------- using CQRS.Commands; using SO115App.Models.Servizi.Infrastruttura.GestionePOS; using System.IO; namespace SO115App.Models.Servizi.CQRS.Commands.GestioneSoccorso.GestionePOS.EditPos { public class EditPosCommandHandler : ICommandHandler<EditPosCommand> { internal string _resultPath { get => ResultPath; set => DirectoryCheck(value); } private string ResultPath; private readonly IEditPos _editPos; public EditPosCommandHandler(IEditPos editPos) => _editPos = editPos; public void Handle(EditPosCommand command) { _editPos.Edit(command.Pos); } private void DirectoryCheck(string path) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); ResultPath = path; } } }
agpl-3.0
C#
a8d30f6aee41f38fcbdd35df05e3a010675e9f5b
remove unused using
johnneijzen/osu,UselessToucan/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,naoey/osu,UselessToucan/osu,naoey/osu,NeoAdonis/osu,NeoAdonis/osu,ZLima12/osu,2yangk23/osu,johnneijzen/osu,ppy/osu,ZLima12/osu,ppy/osu,DrabWeb/osu,2yangk23/osu,DrabWeb/osu,EVAST9919/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,naoey/osu
osu.Game.Rulesets.Osu/Mods/OsuModGrow.cs
osu.Game.Rulesets.Osu/Mods/OsuModGrow.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModGrow : Mod, IApplicableToDrawableHitObjects { public override string Name => "Grow"; public override string Acronym => "GR"; public override FontAwesome Icon => FontAwesome.fa_arrows_v; public override ModType Type => ModType.Fun; public override string Description => "Hit them at the right size!"; public override double ScoreMultiplier => 1; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var drawable in drawables) { if (drawable is DrawableSpinner spinner) return; drawable.ApplyCustomUpdateState += applyCustomState; } } protected virtual void applyCustomState(DrawableHitObject drawable, ArmedState state) { var hitObject = (OsuHitObject) drawable.HitObject; double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1; double scaleDuration = hitObject.TimePreempt + 1; var originalScale = drawable.Scale; drawable.Scale /= 2; using (drawable.BeginAbsoluteSequence(appearTime, true)) drawable.ScaleTo(originalScale, scaleDuration, Easing.OutSine); if (drawable is DrawableHitCircle circle) using (circle.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimePreempt)) circle.ApproachCircle.Hide(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osuTK; namespace osu.Game.Rulesets.Osu.Mods { internal class OsuModGrow : Mod, IApplicableToDrawableHitObjects { public override string Name => "Grow"; public override string Acronym => "GR"; public override FontAwesome Icon => FontAwesome.fa_arrows_v; public override ModType Type => ModType.Fun; public override string Description => "Hit them at the right size!"; public override double ScoreMultiplier => 1; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var drawable in drawables) { if (drawable is DrawableSpinner spinner) return; drawable.ApplyCustomUpdateState += applyCustomState; } } protected virtual void applyCustomState(DrawableHitObject drawable, ArmedState state) { var hitObject = (OsuHitObject) drawable.HitObject; double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1; double scaleDuration = hitObject.TimePreempt + 1; var originalScale = drawable.Scale; drawable.Scale /= 2; using (drawable.BeginAbsoluteSequence(appearTime, true)) drawable.ScaleTo(originalScale, scaleDuration, Easing.OutSine); if (drawable is DrawableHitCircle circle) using (circle.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimePreempt)) circle.ApproachCircle.Hide(); } } }
mit
C#
4ee8224f8b624320b52743c2e68986b795002388
change naming to be less confusing
peppy/osu,peppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu
osu.Game.Tournament/Models/StableInfo.cs
osu.Game.Tournament/Models/StableInfo.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using Newtonsoft.Json; using osu.Framework.Platform; using osu.Game.Tournament.IO; namespace osu.Game.Tournament.Models { /// <summary> /// Holds the path to locate the osu! stable cutting-edge installation. /// </summary> [Serializable] public class StableInfo { /// <summary> /// Path to the IPC directory used by the stable (cutting-edge) install. /// </summary> public string StablePath { get; set; } /// <summary> /// Fired whenever stable info is successfully saved to file. /// </summary> public event Action OnStableInfoSaved; private const string config_path = "stable.json"; private readonly Storage configStorage; public StableInfo(Storage storage) { TournamentStorage tStorage = (TournamentStorage)storage; configStorage = tStorage.AllTournaments; if (!configStorage.Exists(config_path)) return; using (Stream stream = configStorage.GetStream(config_path, FileAccess.Read, FileMode.Open)) using (var sr = new StreamReader(stream)) { JsonConvert.PopulateObject(sr.ReadToEnd(), this); } } public void SaveChanges() { using (var stream = configStorage.GetStream(config_path, FileAccess.Write, FileMode.Create)) using (var sw = new StreamWriter(stream)) { sw.Write(JsonConvert.SerializeObject(this, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, })); } OnStableInfoSaved?.Invoke(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using Newtonsoft.Json; using osu.Framework.Platform; using osu.Game.Tournament.IO; namespace osu.Game.Tournament.Models { /// <summary> /// Holds the path to locate the osu! stable cutting-edge installation. /// </summary> [Serializable] public class StableInfo { /// <summary> /// Path to the IPC directory used by the stable (cutting-edge) install. /// </summary> public string StablePath { get; set; } /// <summary> /// Fired whenever stable info is successfully saved to file. /// </summary> public event Action OnStableInfoSaved; private const string config_path = "stable.json"; private readonly Storage storage; public StableInfo(Storage storage) { TournamentStorage tStorage = (TournamentStorage)storage; this.storage = tStorage.AllTournaments; if (!this.storage.Exists(config_path)) return; using (Stream stream = this.storage.GetStream(config_path, FileAccess.Read, FileMode.Open)) using (var sr = new StreamReader(stream)) { JsonConvert.PopulateObject(sr.ReadToEnd(), this); } } public void SaveChanges() { using (var stream = storage.GetStream(config_path, FileAccess.Write, FileMode.Create)) using (var sw = new StreamWriter(stream)) { sw.Write(JsonConvert.SerializeObject(this, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, })); } OnStableInfoSaved?.Invoke(); } } }
mit
C#
cad68bb82fce1bfdaed3ca85b092b39f484cb222
Add autoplay helper property
ZLima12/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,ppy/osu,ppy/osu,2yangk23/osu,2yangk23/osu,UselessToucan/osu,johnneijzen/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,johnneijzen/osu,peppy/osu-new,peppy/osu,EVAST9919/osu,ZLima12/osu
osu.Game/Tests/Visual/PlayerTestScene.cs
osu.Game/Tests/Visual/PlayerTestScene.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Testing; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { public abstract class PlayerTestScene : RateAdjustedBeatmapTestScene { private readonly Ruleset ruleset; protected Player Player; protected PlayerTestScene(Ruleset ruleset) { this.ruleset = ruleset; } protected OsuConfigManager LocalConfig; [BackgroundDependencyLoader] private void load() { Dependencies.Cache(LocalConfig = new OsuConfigManager(LocalStorage)); LocalConfig.GetBindable<double>(OsuSetting.DimLevel).Value = 1.0; } [SetUpSteps] public virtual void SetUpSteps() { AddStep(ruleset.RulesetInfo.Name, loadPlayer); AddUntilStep("player loaded", () => Player.IsLoaded && Player.Alpha == 1); } protected virtual bool AllowFail => false; protected virtual bool Autoplay => false; private void loadPlayer() { var beatmap = CreateBeatmap(ruleset.RulesetInfo); Beatmap.Value = CreateWorkingBeatmap(beatmap); if (!AllowFail) Mods.Value = new[] { ruleset.GetAllMods().First(m => m is ModNoFail) }; Player = CreatePlayer(ruleset); LoadScreen(Player); } protected virtual Player CreatePlayer(Ruleset ruleset) { if (Autoplay) { var mod = ruleset.GetAutoplayMod(); if (mod != null) Mods.Value = Mods.Value.Concat(mod.Yield()).ToArray(); } return new TestPlayer(false, false); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { public abstract class PlayerTestScene : RateAdjustedBeatmapTestScene { private readonly Ruleset ruleset; protected Player Player; protected PlayerTestScene(Ruleset ruleset) { this.ruleset = ruleset; } protected OsuConfigManager LocalConfig; [BackgroundDependencyLoader] private void load() { Dependencies.Cache(LocalConfig = new OsuConfigManager(LocalStorage)); LocalConfig.GetBindable<double>(OsuSetting.DimLevel).Value = 1.0; } [SetUpSteps] public virtual void SetUpSteps() { AddStep(ruleset.RulesetInfo.Name, loadPlayer); AddUntilStep("player loaded", () => Player.IsLoaded && Player.Alpha == 1); } protected virtual bool AllowFail => false; private void loadPlayer() { var beatmap = CreateBeatmap(ruleset.RulesetInfo); Beatmap.Value = CreateWorkingBeatmap(beatmap); if (!AllowFail) Mods.Value = new[] { ruleset.GetAllMods().First(m => m is ModNoFail) }; Player = CreatePlayer(ruleset); LoadScreen(Player); } protected virtual Player CreatePlayer(Ruleset ruleset) => new TestPlayer(false, false); } }
mit
C#
91aa9a79131b9040ea56b54af561bf38a30bf63e
fix warning
leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
JoinRpg.Data.Write.Interfaces/Properties/AssemblyInfo.cs
JoinRpg.Data.Write.Interfaces/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("JoinRpg.Data.Write.Interfaces")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JoinRpg.Data.Write.Interfaces")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1da9abca-67fe-4e37-b97d-7a5ccc5cdb46")] // 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("JoinRpg.Data.Write.Interfaces")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JoinRpg.Data.Write.Interfaces")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1da9abca-67fe-4e37-b97d-7a5ccc5cdb46")] // 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#
28168ab09798670d3c0d3445d8d7b91346778f77
update synapse factory
jobeland/NeuralNetwork
NeuralNetwork/NeuralNetwork/Factories/SynapseFactory.cs
NeuralNetwork/NeuralNetwork/Factories/SynapseFactory.cs
using ArtificialNeuralNetwork.WeightInitializer; namespace ArtificialNeuralNetwork.Factories { public class SynapseFactory : ISynapseFactory { private IWeightInitializer _weightInitializer; private SynapseFactory(IWeightInitializer weightInitializer) { _weightInitializer = weightInitializer; } public static ISynapseFactory GetInstance(IWeightInitializer weightInitializer) { return new SynapseFactory(weightInitializer); } public Synapse Create() { return new Synapse { Weight = _weightInitializer.InitializeWeight() }; } public Synapse Create(double weight) { return new Synapse { Weight = weight }; } } }
using ArtificialNeuralNetwork.WeightInitializer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork.Factories { public class SynapseFactory : ISynapseFactory { private IWeightInitializer _weightInitializer; private SynapseFactory(IWeightInitializer weightInitializer) { _weightInitializer = weightInitializer; } public static ISynapseFactory GetInstance(IWeightInitializer weightInitializer) { return new SynapseFactory(weightInitializer); } public Synapse Create() { return new Synapse { Value = 0.0, Weight = _weightInitializer.InitializeWeight() }; } public Synapse Create(double weight) { return new Synapse { Value = 0.0, Weight = weight }; } } }
mit
C#
c30d23c3065a277ef2c4c6b3640a712350cd98b1
add ToDateTime() invalid input exception tests
martinlindhe/Punku
PunkuTests/Validate/PersonalIdentityNumberSwedenTest.cs
PunkuTests/Validate/PersonalIdentityNumberSwedenTest.cs
using System; using NUnit.Framework; using Punku; [TestFixture] [Category ("Validate")] public class PersonalIdentityNumberSwedenTestTest { [Test] public void IsPersonnummer01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsValid ("8112189876"), true); } [Test] public void IsPersonnummer02 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsValid ("5566848635"), false); } [Test] public void IsMale01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsMale ("8112189876"), true); } [Test] public void IsFemale01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsFemale ("8112189876"), false); } [Test] public void ParseDateTime01 () { var x = PersonalIdentityNumberSweden.ToDateTime ("811218-9876"); Assert.AreEqual (x.Year, 1981); Assert.AreEqual (x.Month, 12); Assert.AreEqual (x.Day, 18); } [Test] [ExpectedException (typeof(FormatException))] public void ParseDateTime02 () { PersonalIdentityNumberSweden.ToDateTime ("801232-0000"); } [Test] [ExpectedException (typeof(FormatException))] public void ParseDateTime03 () { PersonalIdentityNumberSweden.ToDateTime ("abc123-0000"); } }
using System; using NUnit.Framework; using Punku; [TestFixture] [Category ("Validate")] public class PersonalIdentityNumberSwedenTestTest { [Test] public void IsPersonnummer01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsValid ("8112189876"), true); } [Test] public void IsPersonnummer02 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsValid ("5566848635"), false); } [Test] public void IsMale01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsMale ("8112189876"), true); } [Test] public void IsFemale01 () { Assert.AreEqual (PersonalIdentityNumberSweden.IsFemale ("8112189876"), false); } [Test] public void ParseDateTime01 () { var x = PersonalIdentityNumberSweden.ToDateTime ("811218-9876"); Assert.AreEqual (x.Year, 1981); Assert.AreEqual (x.Month, 12); Assert.AreEqual (x.Day, 18); } }
mit
C#
a446b627da0decbb477efefbb0e63be4c1aa686f
Make TooltipText virtual
EVAST9919/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,ZLima12/osu,johnneijzen/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,smoogipooo/osu,DrabWeb/osu,naoey/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,naoey/osu,naoey/osu,ppy/osu,DrabWeb/osu,DrabWeb/osu,ZLima12/osu,ppy/osu,UselessToucan/osu
osu.Game/Graphics/DrawableDate.cs
osu.Game/Graphics/DrawableDate.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using Humanizer; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Game.Graphics.Sprites; namespace osu.Game.Graphics { public class DrawableDate : OsuSpriteText, IHasTooltip { private readonly DateTimeOffset date; private readonly string dateFormat; /// <param name="dateFormat">The string to format the date text with. /// May be null if the humanized format should be used.</param> public DrawableDate(DateTimeOffset date) { AutoSizeAxes = Axes.Both; Font = "Exo2.0-RegularItalic"; this.date = date.ToLocalTime(); this.dateFormat = dateFormat; } [BackgroundDependencyLoader] private void load() { updateTime(); } protected override void LoadComplete() { base.LoadComplete(); Scheduler.Add(updateTimeWithReschedule); } private void updateTimeWithReschedule() { updateTime(); var diffToNow = DateTimeOffset.Now.Subtract(date); double timeUntilNextUpdate = 1000; if (diffToNow.TotalSeconds > 60) { timeUntilNextUpdate *= 60; if (diffToNow.TotalMinutes > 60) { timeUntilNextUpdate *= 60; if (diffToNow.TotalHours > 24) timeUntilNextUpdate *= 24; } } Scheduler.AddDelayed(updateTimeWithReschedule, timeUntilNextUpdate); } public override bool HandleMouseInput => true; private void updateTime() => Text = string.IsNullOrEmpty(dateFormat) ? date.Humanize() : string.Format(dateFormat, date); public virtual string TooltipText => string.Format("{0:d MMMM yyyy H:mm \"UTC\"z}", date); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using Humanizer; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Game.Graphics.Sprites; namespace osu.Game.Graphics { public class DrawableDate : OsuSpriteText, IHasTooltip { private readonly DateTimeOffset date; private readonly string dateFormat; /// <param name="dateFormat">The string to format the date text with. /// May be null if the humanized format should be used.</param> public DrawableDate(DateTimeOffset date) { AutoSizeAxes = Axes.Both; Font = "Exo2.0-RegularItalic"; this.date = date.ToLocalTime(); this.dateFormat = dateFormat; } [BackgroundDependencyLoader] private void load() { updateTime(); } protected override void LoadComplete() { base.LoadComplete(); Scheduler.Add(updateTimeWithReschedule); } private void updateTimeWithReschedule() { updateTime(); var diffToNow = DateTimeOffset.Now.Subtract(date); double timeUntilNextUpdate = 1000; if (diffToNow.TotalSeconds > 60) { timeUntilNextUpdate *= 60; if (diffToNow.TotalMinutes > 60) { timeUntilNextUpdate *= 60; if (diffToNow.TotalHours > 24) timeUntilNextUpdate *= 24; } } Scheduler.AddDelayed(updateTimeWithReschedule, timeUntilNextUpdate); } public override bool HandleMouseInput => true; private void updateTime() => Text = string.IsNullOrEmpty(dateFormat) ? date.Humanize() : string.Format(dateFormat, date); public string TooltipText => string.Format("{0:d MMMM yyyy H:mm \"UTC\"z}", date); } }
mit
C#
391cd24a9f1582ed3cca9b16bf0702183b3f6623
Test date/days is robuster
Mozketo/TFSbot
ChangesetsNotReviewed/run.csx
ChangesetsNotReviewed/run.csx
#load "..\extensions\TfsEx.csx" using System; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { DateTime dFrom = DateTime.Now.Subtract(TimeSpan.FromDays(1)); string from = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "from", true) == 0) .Value; DateTime tryDate; int tryDays = 0; if (DateTime.TryParse(from, out tryDate)) { dFrom = tryDate; } else if (int.TryParse(from, out tryDays)) { dFrom = dFrom.Subtract(TimeSpan.FromDays(Math.Abs(tryDays))); } string tfsPath = ConfigurationManager.AppSettings["Tfs.Path"] ?? "$/"; var tickets = TfsEx.GetHistory(log, tfsPath, dFrom); string message = tickets.Count().ToString(); return Message(req, message); } static HttpResponseMessage Message(HttpRequestMessage req, string message) { return req.CreateResponse(HttpStatusCode.OK, new { text = message }); }
#load "..\extensions\TfsEx.csx" using System; using System.Configuration; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { DateTime dFrom = DateTime.Now.Subtract(TimeSpan.FromDays(1)); string from = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "from", true) == 0) .Value; int days = 0; if (DateTime.TryParse(from, out dFrom)) { // i guess that worked } else if (int.TryParse(from, out days)) { dFrom = dFrom.Subtract(TimeSpan.FromDays(Math.Abs(days))); } string tfsPath = ConfigurationManager.AppSettings["Tfs.Path"] ?? "$/"; var tickets = TfsEx.GetHistory(log, tfsPath, dFrom); string message = tickets.Count().ToString(); return Message(req, message); } static HttpResponseMessage Message(HttpRequestMessage req, string message) { return req.CreateResponse(HttpStatusCode.OK, new { text = message }); }
mit
C#
e3460f9b1b2deb70101fd48e886bc7f803a20c0a
Change type of force added when throwing a weapon.
Warhead-Entertainment/OpenWorld
Assets/Scripts/Player/ObjectInteraction.cs
Assets/Scripts/Player/ObjectInteraction.cs
using UnityEngine; using System.Collections; public sealed class ObjectInteraction : MonoBehaviour { public GameObject ItemInHand; private int SelectedItem; private Transform FirstPersonCamera; private Inventory LocalInventory; void Start () { FirstPersonCamera = transform.Find("FirstPersonCamera"); LocalInventory = transform.GetComponent<Inventory>(); ItemInHand = new GameObject("Empty Inventory Slot"); } void Update () { // Select hotbar if (Input.GetKeyDown(KeyCode.Alpha1)) { SelectItem(0); } else if (Input.GetKeyDown(KeyCode.Alpha2)) { SelectItem(1); } else if (Input.GetKeyDown(KeyCode.Alpha3)) { SelectItem(2); } else if (Input.GetKeyDown(KeyCode.Alpha4)) { SelectItem(3); } else if (Input.GetKeyDown(KeyCode.Alpha5)) { SelectItem(4); } else if (Input.GetKeyDown(KeyCode.Alpha6)) { SelectItem(5); } else if (Input.GetKeyDown(KeyCode.Alpha7)) { SelectItem(6); } else if (Input.GetKeyDown(KeyCode.Alpha8)) { SelectItem(7); } else if (Input.GetKeyDown(KeyCode.Alpha9)) { SelectItem(8); } // Control pickup if (Input.GetKeyDown(KeyCode.E)) { InsertItem(); } // Control drop if (Input.GetKeyDown(KeyCode.Q)) { DropItem(); } } private void SelectItem (int keyDown) { Destroy(ItemInHand); SelectedItem = keyDown; if (LocalInventory.IfExists(keyDown)) { ItemInHand = (GameObject) GameObject.Instantiate(LocalInventory.GetItem(keyDown)); ItemInHand.GetComponent<Rigidbody>().detectCollisions = false; ItemInHand.GetComponent<Rigidbody>().useGravity = false; //Taylor's bullshit play idle animation when you select item ItemInHand.GetComponent<Animation>().Play("idle"); ItemInHand.layer = LayerMask.NameToLayer("Weapon"); } else { ItemInHand = new GameObject("Empty Inventory Slot"); } ItemInHand.transform.parent = FirstPersonCamera.transform.Find("Hand").transform; ItemInHand.transform.localPosition = Vector3.zero; ItemInHand.transform.localRotation = Quaternion.identity; } private void InsertItem () { RaycastHit hit; if (Physics.Raycast(FirstPersonCamera.position, FirstPersonCamera.forward, out hit, 2)) { GameObject item = hit.transform.gameObject; if (LocalInventory.Insert(item.name)) { DestroyObject(item); } } } private void DropItem () { LocalInventory.Remove(SelectedItem); GameObject DroppedItem = (GameObject) Instantiate(ItemInHand, transform.position, transform.rotation); DroppedItem.rigidbody.AddForce(FirstPersonCamera.forward * (Input.GetAxis("Vertical") + 1) * 30, ForceMode.Impulse); DroppedItem.GetComponent<Rigidbody>().detectCollisions = true; DroppedItem.GetComponent<Rigidbody>().useGravity = true; DroppedItem.layer = LayerMask.NameToLayer("Default"); Destroy(ItemInHand); } }
using UnityEngine; using System.Collections; public sealed class ObjectInteraction : MonoBehaviour { public GameObject ItemInHand; private int SelectedItem; private Transform FirstPersonCamera; private Inventory LocalInventory; void Start () { FirstPersonCamera = transform.Find("FirstPersonCamera"); LocalInventory = transform.GetComponent<Inventory>(); ItemInHand = new GameObject("Empty Inventory Slot"); } void Update () { // Select hotbar if (Input.GetKeyDown(KeyCode.Alpha1)) { SelectItem(0); } else if (Input.GetKeyDown(KeyCode.Alpha2)) { SelectItem(1); } else if (Input.GetKeyDown(KeyCode.Alpha3)) { SelectItem(2); } else if (Input.GetKeyDown(KeyCode.Alpha4)) { SelectItem(3); } else if (Input.GetKeyDown(KeyCode.Alpha5)) { SelectItem(4); } else if (Input.GetKeyDown(KeyCode.Alpha6)) { SelectItem(5); } else if (Input.GetKeyDown(KeyCode.Alpha7)) { SelectItem(6); } else if (Input.GetKeyDown(KeyCode.Alpha8)) { SelectItem(7); } else if (Input.GetKeyDown(KeyCode.Alpha9)) { SelectItem(8); } // Control pickup if (Input.GetKeyDown(KeyCode.E)) { InsertItem(); } // Control drop if (Input.GetKeyDown(KeyCode.Q)) { DropItem(); } } private void SelectItem (int keyDown) { Destroy(ItemInHand); SelectedItem = keyDown; if (LocalInventory.IfExists(keyDown)) { ItemInHand = (GameObject) GameObject.Instantiate(LocalInventory.GetItem(keyDown)); ItemInHand.GetComponent<Rigidbody>().detectCollisions = false; ItemInHand.GetComponent<Rigidbody>().useGravity = false; //Taylor's bullshit play idle animation when you select item ItemInHand.GetComponent<Animation>().Play("idle"); ItemInHand.layer = LayerMask.NameToLayer("Weapon"); } else { ItemInHand = new GameObject("Empty Inventory Slot"); } ItemInHand.transform.parent = FirstPersonCamera.transform.Find("Hand").transform; ItemInHand.transform.localPosition = Vector3.zero; ItemInHand.transform.localRotation = Quaternion.identity; } private void InsertItem () { RaycastHit hit; if (Physics.Raycast(FirstPersonCamera.position, FirstPersonCamera.forward, out hit, 2)) { GameObject item = hit.transform.gameObject; if (LocalInventory.Insert(item.name)) { DestroyObject(item); } } } private void DropItem () { LocalInventory.Remove(SelectedItem); GameObject DroppedItem = (GameObject) Instantiate(ItemInHand, transform.position, transform.rotation); //DroppedItem.rigidbody.AddForce(FirstPersonCamera.forward, ForceMode.Impulse); DroppedItem.rigidbody.velocity = transform.TransformDirection(FirstPersonCamera.forward * (Input.GetAxis("Vertical") + 1) * 30); DroppedItem.GetComponent<Rigidbody>().detectCollisions = true; DroppedItem.GetComponent<Rigidbody>().useGravity = true; DroppedItem.layer = LayerMask.NameToLayer("Default"); Destroy(ItemInHand); } }
mit
C#
53c5c74cb3ef1e11487539f28b006ba27f4a63dc
update samples.
dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP
samples/Sample.RabbitMQ.MySql/Startup.cs
samples/Sample.RabbitMQ.MySql/Startup.cs
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Sample.RabbitMQ.MySql { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(); services.AddCap(x => { x.UseEntityFramework<AppDbContext>(); x.UseRabbitMQ("localhost"); x.UseDashboard(); x.FailedRetryCount = 5; x.FailedThresholdCallback = (type, name, content) => { Console.WriteLine($@"A message of type {type} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {name}, message body: {content}"); }; }); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvc(); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Sample.RabbitMQ.MySql { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(); services.AddCap(x => { x.UseEntityFramework<AppDbContext>(); x.UseRabbitMQ("localhost"); x.UseDashboard(); x.FailedRetryCount = 5; x.FailedThresholdCallback = (type, name, content) => { Console.WriteLine($@"A message of type {type} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {name}, message body: {content}"); }; }); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvc(); app.UseCap(); } } }
mit
C#
2e2e229d2f2d62e09afbe9099ac8f97d59c710f7
Fix issue where ratio was always returning "1"
janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent
Components/TemplateHelpers/Images/Ratio.cs
Components/TemplateHelpers/Images/Ratio.cs
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height; } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height); } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
mit
C#
e049f7e0fa19661b964b7f9a3a2315ab034c50eb
bump to v0.1.17
abelsilva/swaggerwcf
src/SwaggerWcf/Properties/AssemblyInfo.cs
src/SwaggerWcf/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("SwaggerWcf")] [assembly: AssemblyDescription("Swagger for WCF")] [assembly: AssemblyCompany("abelsilva")] [assembly: AssemblyProduct("SwaggerWcf")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif // 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("d2eeaa63-60e5-4fda-8b62-e05dc8be8b5f")] // 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.17")] [assembly: AssemblyFileVersion("0.1.17")] [assembly: AssemblyInformationalVersion("0.1.17")]
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("SwaggerWcf")] [assembly: AssemblyDescription("Swagger for WCF")] [assembly: AssemblyCompany("abelsilva")] [assembly: AssemblyProduct("SwaggerWcf")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif // 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("d2eeaa63-60e5-4fda-8b62-e05dc8be8b5f")] // 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.16")] [assembly: AssemblyFileVersion("0.1.16")] [assembly: AssemblyInformationalVersion("0.1.16")]
apache-2.0
C#
152fb0aaa0aada84633b3951bb8a57997d370e28
Update docs
RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake
src/Snowflake.Framework.Primitives/Scraping/Extensibility/ICuller.cs
src/Snowflake.Framework.Primitives/Scraping/Extensibility/ICuller.cs
using System; using System.Collections.Generic; using System.Text; using Snowflake.Extensibility; namespace Snowflake.Scraping.Extensibility { /// <summary> /// A <see cref="ICuller"/> filters seeds that remain in consideration /// when the <see cref="ISeedRootContext"/> is traversed to produce a result. /// </summary> public interface ICuller : IPlugin { /// <summary> /// Gets the type of <see cref="ISeed"/> that this culler examines. /// </summary> string TargetType { get; } /// <summary> /// Determines the seeds that REMAIN for traversal. /// </summary> /// <param name="seedsToFilter">The seeds of the specified type in the current job.</param> /// <param name="context">The root context of the current job.</param> /// <returns>A list of seeds NOT to cull.</returns> IEnumerable<ISeed> Filter(IEnumerable<ISeed> seedsToFilter, ISeedRootContext context); } }
using System; using System.Collections.Generic; using System.Text; using Snowflake.Extensibility; namespace Snowflake.Scraping.Extensibility { /// <summary> /// A <see cref="ICuller"/> filters seeds that remain in consideration /// when the <see cref="ISeedRootContext"/> is traversed to produce a result. /// </summary> public interface ICuller : IPlugin { /// <summary> /// Gets the type of <see cref="ISeed"/> that this culler examines. /// </summary> string TargetType { get; } /// <summary> /// Determines the seeds that REMAIN for traversal. /// A culler should never call <see cref="ISeed.Cull"/>, and instead /// specifies the eeeds that should NOT be culled. /// </summary> /// <param name="seedsToFilter">The seeds of the specified type in the current job.</param> /// <param name="context">The root context of the current job.</param> /// <returns>A list of seeds NOT to cull.</returns> IEnumerable<ISeed> Filter(IEnumerable<ISeed> seedsToFilter, ISeedRootContext context); } }
mpl-2.0
C#
eb6d2bf3ce11f951db53fffc138525fdeac9f3e7
add notification
Rychard/Skylines-ModTools,earalov/Skylines-ModTools,joaofarias/Unity-ModTools,Skylines-ModTools/Skylines-ModTools
Debugger/UserNotifications.cs
Debugger/UserNotifications.cs
using System.Collections.Generic; namespace ModTools { public static class UserNotifications { private static Configuration config { get { return ModTools.Instance.config; } } private static List<KeyValuePair<int, string>> notifications = new List<KeyValuePair<int, string>>(); private static int notificationsCount = 0; static UserNotifications() { Add(LoggingChangeNotification); Add(UnityLoggingHookNotification); } private static void Add(string notification) { notifications.Add(new KeyValuePair<int, string>(notificationsCount++, notification)); } public static List<KeyValuePair<int, string>> GetNotifications() { List<KeyValuePair<int, string>> result = new List<KeyValuePair<int, string>>(); foreach (var item in notifications) { if ((config.hiddenNotifications & (1 << item.Key)) == 0) { result.Add(item); } } return result; } public static void HideNotification(int index) { config.hiddenNotifications |= 1 << index; ModTools.Instance.SaveConfig(); } private static string LoggingChangeNotification = @"You are using the new ModTools console. It offers an improved experience over the old one but requires a change to your logging code. You should no longer use DebugOutputPanel for logging as messages sent to it won't get displayed by ModTools. Instead you should use the built-in Unity Debug API (http://docs.unity3d.com/ScriptReference/Debug.html). Example: Debug.Log(""Hello world!"");"; private static string UnityLoggingHookNotification = @"Your version of ModTools has a new feature which allows it to hook Unity's Debug logging so you can safely log from the simulation thread (or any other thread). This feature is currently marked as experimental and is off by default. You can find it in the main menu (Ctrl+Q) as ""Hook Unity's logging (experimental)"". After enabling it you should see a warning in the console saying so. It is recommended that you enable this (as it will probably become the default mode in the future) and report any issues."; } }
using System.Collections.Generic; namespace ModTools { public static class UserNotifications { private static Configuration config { get { return ModTools.Instance.config; } } private static List<KeyValuePair<int, string>> notifications = new List<KeyValuePair<int, string>>(); private static int notificationsCount = 0; static UserNotifications() { Add(LoggingChangeNotification); } private static void Add(string notification) { notifications.Add(new KeyValuePair<int, string>(notificationsCount++, notification)); } public static List<KeyValuePair<int, string>> GetNotifications() { List<KeyValuePair<int, string>> result = new List<KeyValuePair<int, string>>(); foreach (var item in notifications) { if ((config.hiddenNotifications & (1 << item.Key)) == 0) { result.Add(item); } } return result; } public static void HideNotification(int index) { config.hiddenNotifications |= 1 << index; ModTools.Instance.SaveConfig(); } private static string LoggingChangeNotification = @"You are using the new ModTools console. It offers an improved experience over the old one but requires a change to your logging code. You should no longer use DebugOutputPanel for logging as messages sent to it won't get displayed by ModTools. Instead you should use the built-in Unity Debug API (http://docs.unity3d.com/ScriptReference/Debug.html). Example: Debug.Log(""Hello world!"");"; } }
mit
C#
1ade41e6442526fd57178d1411665d82b49a6c45
remove commented lines
messagebird/csharp-rest-api
Examples/VoiceMessage/ListVoiceMessages.cs
Examples/VoiceMessage/ListVoiceMessages.cs
using System; using MessageBird; using MessageBird.Exceptions; using MessageBird.Net.ProxyConfigurationInjector; using MessageBird.Objects; namespace Examples.VoiceMessage { class ListVoiceMessages { const string YourAccessKey = "YOUR_ACCESS_KEY"; // your access key here. static void Main(string[] args) { IProxyConfigurationInjector proxyConfigurationInjector = null; // for no web proxies, or web proxies not requiring authentication Client client = Client.CreateDefault(YourAccessKey, proxyConfigurationInjector); try { MessageBird.Objects.VoiceMessageList voiceMessageList = client.ListVoiceMessages(); Console.WriteLine("{0}", voiceMessageList); } catch (ErrorException e) { // Either the request fails with error descriptions from the endpoint. if (e.HasErrors) { foreach (Error error in e.Errors) { Console.WriteLine("code: {0} description: '{1}' parameter: '{2}'", error.Code, error.Description, error.Parameter); } } // or fails without error information from the endpoint, in which case the reason contains a 'best effort' description. if (e.HasReason) { Console.WriteLine(e.Reason); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
using System; using MessageBird; using MessageBird.Exceptions; using MessageBird.Net.ProxyConfigurationInjector; using MessageBird.Objects; namespace Examples.VoiceMessage { class ListVoiceMessages { const string YourAccessKey = "YOUR_ACCESS_KEY"; // your access key here. static void Main(string[] args) { IProxyConfigurationInjector proxyConfigurationInjector = null; // for no web proxies, or web proxies not requiring authentication //proxyConfigurationInjector = new InjectDefaultCredentialsForProxiedUris(); // for NTLM based web proxies //proxyConfigurationInjector = new InjectCredentialsForProxiedUris(new NetworkCredential("domain\\user", "password")); // for username/password based web proxies Client client = Client.CreateDefault(YourAccessKey, proxyConfigurationInjector); try { MessageBird.Objects.VoiceMessageList voiceMessageList = client.ListVoiceMessages(); Console.WriteLine("{0}", voiceMessageList); } catch (ErrorException e) { // Either the request fails with error descriptions from the endpoint. if (e.HasErrors) { foreach (Error error in e.Errors) { Console.WriteLine("code: {0} description: '{1}' parameter: '{2}'", error.Code, error.Description, error.Parameter); } } // or fails without error information from the endpoint, in which case the reason contains a 'best effort' description. if (e.HasReason) { Console.WriteLine(e.Reason); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
isc
C#
1408666eecc94e8b3488dfb4fcf143fae302b0e7
change update dbconnection pool size (#5797)
greenlaw110/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jamming/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jamming/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jamming/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jamming/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks
frameworks/CSharp/beetlex/PlatformBenchmarks/HttpServer.cs
frameworks/CSharp/beetlex/PlatformBenchmarks/HttpServer.cs
using BeetleX; using BeetleX.EventArgs; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PlatformBenchmarks { public class HttpServer : IHostedService { public static IServer ApiServer; public virtual Task StartAsync(CancellationToken cancellationToken) { ArraySegment<byte> date = GMTDate.Default.DATE; ServerOptions serverOptions = new ServerOptions(); serverOptions.LogLevel = LogType.Error; serverOptions.DefaultListen.Port = 8080; serverOptions.Statistical = false; serverOptions.BufferSize = 1024 * 8; serverOptions.BufferPoolMaxMemory = 1000; serverOptions.BufferPoolSize = 1024 * 8; ApiServer = SocketFactory.CreateTcpServer<HttpHandler>(serverOptions); ApiServer.Open(); if (!Program.UpDB) { RawDb._connectionString = "Server=tfb-database;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=256;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; // RawDb._connectionString = "Server=192.168.2.19;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=256;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; } else { // RawDb._connectionString = "Server=192.168.2.19;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=32;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; RawDb._connectionString = "Server=tfb-database;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=64;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; } ApiServer.Log(LogType.Info, null, $"Debug mode [{Program.Debug}]"); return Task.CompletedTask; } public virtual Task StopAsync(CancellationToken cancellationToken) { ApiServer.Dispose(); return Task.CompletedTask; } } }
using BeetleX; using BeetleX.EventArgs; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PlatformBenchmarks { public class HttpServer : IHostedService { public static IServer ApiServer; public virtual Task StartAsync(CancellationToken cancellationToken) { ArraySegment<byte> date = GMTDate.Default.DATE; ServerOptions serverOptions = new ServerOptions(); serverOptions.LogLevel = LogType.Error; serverOptions.DefaultListen.Port = 8080; serverOptions.Statistical = false; serverOptions.BufferSize = 1024 * 8; serverOptions.BufferPoolMaxMemory = 1000; serverOptions.BufferPoolSize = 1024 * 8; ApiServer = SocketFactory.CreateTcpServer<HttpHandler>(serverOptions); ApiServer.Open(); if (!Program.UpDB) { RawDb._connectionString = "Server=tfb-database;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=256;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; // RawDb._connectionString = "Server=192.168.2.19;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=256;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; } else { // RawDb._connectionString = "Server=192.168.2.19;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=32;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; RawDb._connectionString = "Server=tfb-database;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=32;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3"; } ApiServer.Log(LogType.Info, null, $"Debug mode [{Program.Debug}]"); return Task.CompletedTask; } public virtual Task StopAsync(CancellationToken cancellationToken) { ApiServer.Dispose(); return Task.CompletedTask; } } }
bsd-3-clause
C#
abf4cadab49e7baac51700029f29181550924e8c
Enable sliding expiration by default as that is what the Tea Commerce cache does
TeaCommerce/Tea-Commerce-for-Umbraco,TeaCommerce/Tea-Commerce-for-Umbraco,TeaCommerce/Tea-Commerce-for-Umbraco
Source/TeaCommerce.Umbraco.Application/Caching/UmbracoRuntimeCacheService.cs
Source/TeaCommerce.Umbraco.Application/Caching/UmbracoRuntimeCacheService.cs
using System; using TeaCommerce.Api.Dependency; using TeaCommerce.Api.Infrastructure.Caching; using Umbraco.Core; using Umbraco.Core.Cache; namespace TeaCommerce.Umbraco.Application.Caching { [SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")] public class UmbracoRuntimeCacheService : ICacheService { private IRuntimeCacheProvider _runtimeCache; public UmbracoRuntimeCacheService() : this(ApplicationContext.Current.ApplicationCache.RuntimeCache) { } public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache) { _runtimeCache = runtimeCache; } public T GetCacheValue<T>(string cacheKey) where T : class { return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}"); } public void Invalidate(string cacheKey) { _runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}"); } public void SetCacheValue(string cacheKey, object cacheValue) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue); } public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration, true); } } }
using System; using TeaCommerce.Api.Dependency; using TeaCommerce.Api.Infrastructure.Caching; using Umbraco.Core; using Umbraco.Core.Cache; namespace TeaCommerce.Umbraco.Application.Caching { [SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")] public class UmbracoRuntimeCacheService : ICacheService { private IRuntimeCacheProvider _runtimeCache; public UmbracoRuntimeCacheService() : this(ApplicationContext.Current.ApplicationCache.RuntimeCache) { } public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache) { _runtimeCache = runtimeCache; } public T GetCacheValue<T>(string cacheKey) where T : class { return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}"); } public void Invalidate(string cacheKey) { _runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}"); } public void SetCacheValue(string cacheKey, object cacheValue) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue); } public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration) { _runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration); } } }
mit
C#
3b47f8dd6815eb88c6f5ff4139b1ab5982c3c80c
increase images range
M1chaelTran/Fun-Match-Game,M1chaelTran/Fun-Match-Game,M1chaelTran/Fun-Match-Game
FunMatchGame/Repositories/SetRepository.cs
FunMatchGame/Repositories/SetRepository.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; using AutoMapper; using FunMatchGame.Models; using Newtonsoft.Json; namespace FunMatchGame.Repositories { public class SetRepository : ISetRepository { private readonly IMappingEngine _mappingEngine; public SetRepository(IMappingEngine mappingEngine) { _mappingEngine = mappingEngine; } public Task<IList<Card>> GetCardsBySetIdAsync(Sets setId) { switch (setId) { case Sets.AbcStories: return GetAbcLocalStories(); case Sets.AustralianWarMemorial: return GetAustralianWarMemorial(); } return Task.FromResult<IList<Card>>(new List<Card>()); } private async Task<IList<Card>> GetAustralianWarMemorial() { var apiUrl = "https://www.awm.gov.au/direct/data.php?key=ww1hack2015&q=type:%22Photograph%22&count=50"; var r = new Random(); apiUrl += "&start=" + r.Next(0, 200000); var client = new HttpClient(); var result = await client.GetAsync(apiUrl); result.EnsureSuccessStatusCode(); var data = await result.Content.ReadAsAsync<AustralianWarMemorialRootDataModel>(); return (from d in data.results let url = new UriBuilder("https", d.url.Remove(0, 4)) let imageUrl = "https://static.awm.gov.au/images/collection/items/ACCNUM_SCREEN/" + d.accession_number + ".JPG" select new Card(Guid.NewGuid(), d.title, imageUrl, url.ToString(), d.description)).ToList(); } private string GetDataFile(string dataFileName) { return Path.Combine(HttpRuntime.AppDomainAppPath, "Data", dataFileName); } private Task<IList<Card>> GetAbcLocalStories() { using (var r = new StreamReader(GetDataFile("Localphotostories2009-2014-JSON.json"))) { var json = r.ReadToEnd(); dynamic items = JsonConvert.DeserializeObject(json); var cards = new List<Card>(); foreach (var item in items) { if (string.IsNullOrWhiteSpace(item["Primary image"].ToString())) continue; cards.Add(new Card(Guid.NewGuid(), item["Title"].ToString(), item["Primary image"].ToString(), item["URL"].ToString(), item["Primary image caption"].ToString())); } return Task.FromResult<IList<Card>>(cards); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; using AutoMapper; using FunMatchGame.Models; using Newtonsoft.Json; namespace FunMatchGame.Repositories { public class SetRepository : ISetRepository { private readonly IMappingEngine _mappingEngine; public SetRepository(IMappingEngine mappingEngine) { _mappingEngine = mappingEngine; } public Task<IList<Card>> GetCardsBySetIdAsync(Sets setId) { switch (setId) { case Sets.AbcStories: return GetAbcLocalStories(); case Sets.AustralianWarMemorial: return GetAustralianWarMemorial(); } return Task.FromResult<IList<Card>>(new List<Card>()); } private async Task<IList<Card>> GetAustralianWarMemorial() { var apiUrl = "https://www.awm.gov.au/direct/data.php?key=ww1hack2015&q=type:%22Photograph%22&count=50"; var r = new Random(); apiUrl += "&start=" + r.Next(0, 2000); var client = new HttpClient(); var result = await client.GetAsync(apiUrl); result.EnsureSuccessStatusCode(); var data = await result.Content.ReadAsAsync<AustralianWarMemorialRootDataModel>(); return (from d in data.results let url = new UriBuilder("https", d.url.Remove(0, 4)) let imageUrl = "https://static.awm.gov.au/images/collection/items/ACCNUM_SCREEN/" + d.accession_number + ".JPG" select new Card(Guid.NewGuid(), d.title, imageUrl, url.ToString(), d.description)).ToList(); } private string GetDataFile(string dataFileName) { return Path.Combine(HttpRuntime.AppDomainAppPath, "Data", dataFileName); } private Task<IList<Card>> GetAbcLocalStories() { using (var r = new StreamReader(GetDataFile("Localphotostories2009-2014-JSON.json"))) { var json = r.ReadToEnd(); dynamic items = JsonConvert.DeserializeObject(json); var cards = new List<Card>(); foreach (var item in items) { if (string.IsNullOrWhiteSpace(item["Primary image"].ToString())) continue; cards.Add(new Card(Guid.NewGuid(), item["Title"].ToString(), item["Primary image"].ToString(), item["URL"].ToString(), item["Primary image caption"].ToString())); } return Task.FromResult<IList<Card>>(cards); } } } }
mit
C#
82ec97343a604e166d3667cfaca758027d8a344d
Fix a missing semicolon in an example
MRCollective/MicrotestingPresentation
code_examples/01-SubcutaneousTestsVsImplementationTests/subcutaneous-test.cs
code_examples/01-SubcutaneousTestsVsImplementationTests/subcutaneous-test.cs
public class StudentControllerTests { [SetUp] public void Setup() { _fixture = new DatabaseFixture(); _controller = new StudentController(new StudentRepository(_fixture.Context)); } [Test] public void IndexAction_ShowsAllStudentsOrderedByName() { var expectedStudents = new List<Student> { new Student("Joe", "Bloggs"), new Student("Jane", "Smith") }; expectedStudents.ForEach(_fixture.SeedContext.Students.Add) _fixture.SeedContext.SaveChanges(); List<StudentViewModel> viewModel; _controller.Index() .ShouldRenderDefaultView() .WithModel<List<StudentViewModel>>(vm => viewModel = vm); viewModel.Select(s => s.Name).ShouldBe( _existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName)); } private StudentController _controller; private DatabaseFixture _fixture; }
public class StudentControllerTests { [SetUp] public void Setup() { _fixture = new DatabaseFixture(); _controller = new StudentController(new StudentRepository(_fixture.Context)); } [Test] public void IndexAction_ShowsAllStudentsOrderedByName() { var expectedStudents = new List<Student> { new Student("Joe", "Bloggs"), new Student("Jane", "Smith") }; expectedStudents.ForEach(_fixture.SeedContext.Students.Add) _fixture.SeedContext.SaveChanges(); List<StudentViewModel> viewModel; _controller.Index() .ShouldRenderDefaultView() .WithModel<List<StudentViewModel>>(vm => viewModel = vm); viewModel.Select(s => s.Name).ShouldBe( _existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName)) } private StudentController _controller; private DatabaseFixture _fixture; }
mit
C#
d44662bce026e82990476fd9ccd7406e49f790b0
Remove unconventional "age_eq" filter.
Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module
GraphQL/Services/ContentItemTypeBuilder.cs
GraphQL/Services/ContentItemTypeBuilder.cs
using GraphQL.Types; using OrchardCore.ContentManagement.GraphQL.Queries.Types; using OrchardCore.ContentManagement.Metadata.Models; using System.Linq; namespace Lombiq.TrainingDemo.GraphQL.Services { // Services that implement IContentTypeBuilder extend the features of existing ContentItem type fields, including // the top level fields automatically created by Orchard Core for every content type. You can use this to add new // sub-fields or filter attributes to existing ContentItem type fields. public class ContentItemTypeBuilder : IContentTypeBuilder { // It's a good practice to make the argument name a const because you will reuse it in the IGraphQLFilter. public const string AgeFilterName = "age"; // Here you can add arguments to every Content Type (top level) field. public void Build( FieldType contentQuery, ContentTypeDefinition contentTypeDefinition, ContentItemType contentItemType) { // You can check the sub-fields if your argument relies on certain content parts or content fields. if (contentItemType.Fields.All(field => field.Name != "person")) return; // The resolved type can be anything that can be represented with JSON and has a known graph type, but we // stick with numbers for simplicity's sake. contentQuery.Arguments.Add(new QueryArgument<IntGraphType> { Name = AgeFilterName, ResolvedType = new IntGraphType(), }); // You can't use special characters in the argument names so by GraphQL convention these two letter suffixes // that represent the relational operators. AddFilter(contentQuery, "_lt"); AddFilter(contentQuery, "_le"); AddFilter(contentQuery, "_ge"); AddFilter(contentQuery, "_gt"); AddFilter(contentQuery, "_ne"); } private static void AddFilter(FieldType contentQuery, string suffix) => contentQuery.Arguments.Add(new QueryArgument<IntGraphType> { Name = AgeFilterName + suffix, ResolvedType = new IntGraphType(), }); } } // NEXT STATION: Services/PersonAgeGraphQLFilter.cs
using GraphQL.Types; using OrchardCore.ContentManagement.GraphQL.Queries.Types; using OrchardCore.ContentManagement.Metadata.Models; using System.Linq; namespace Lombiq.TrainingDemo.GraphQL.Services { // Services that implement IContentTypeBuilder extend the features of existing ContentItem type fields, including // the top level fields automatically created by Orchard Core for every content type. You can use this to add new // sub-fields or filter attributes to existing ContentItem type fields. public class ContentItemTypeBuilder : IContentTypeBuilder { // It's a good practice to make the argument name a const because you will reuse it in the IGraphQLFilter. public const string AgeFilterName = "age"; // Here you can add arguments to every Content Type (top level) field. public void Build( FieldType contentQuery, ContentTypeDefinition contentTypeDefinition, ContentItemType contentItemType) { // You can check the sub-fields if your argument relies on certain content parts or content fields. if (contentItemType.Fields.All(field => field.Name != "person")) return; // The resolved type can be anything that can be represented with JSON and has a known graph type, but we // stick with numbers for simplicity's sake. contentQuery.Arguments.Add(new QueryArgument<IntGraphType> { Name = AgeFilterName, ResolvedType = new IntGraphType(), }); // You can't use special characters in the argument names so by GraphQL convention these two letter suffixes // that represent the relational operators. AddFilter(contentQuery, "_lt"); AddFilter(contentQuery, "_le"); AddFilter(contentQuery, "_ge"); AddFilter(contentQuery, "_gt"); AddFilter(contentQuery, "_eq"); AddFilter(contentQuery, "_ne"); } private static void AddFilter(FieldType contentQuery, string suffix) => contentQuery.Arguments.Add(new QueryArgument<IntGraphType> { Name = AgeFilterName + suffix, ResolvedType = new IntGraphType(), }); } } // NEXT STATION: Services/PersonAgeGraphQLFilter.cs
bsd-3-clause
C#