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
a6a67cf03159bc1085b2f9c1887f09ccaf59bba0
Change "RSS Headlines" widget name
danielchalmers/DesktopWidgets
DesktopWidgets/Widgets/RSSFeed/Metadata.cs
DesktopWidgets/Widgets/RSSFeed/Metadata.cs
namespace DesktopWidgets.Widgets.RSSFeed { public static class Metadata { public const string FriendlyName = "RSS Feed"; } }
namespace DesktopWidgets.Widgets.RSSFeed { public static class Metadata { public const string FriendlyName = "RSS Headlines"; } }
apache-2.0
C#
52c0f29d83997452a74551cdfc19c148fad14796
Fix new class name in LoadTester.Demo
LukasBoersma/LoadTester
LoadTester.Demo/Program.cs
LoadTester.Demo/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using LoadTester; namespace LoadTester.Demo { public class Program { static void Main(string[] args) { // Create the test runner. Configure it to run lots of tests in parallel. var tester = new TestRunner { ParallelTests = 128 }; // Get a chunk of data var data = MakeData(); // Test how fast we can copy that data tester.AddTest(() => { var dataCopy = new byte[data.Length]; data.CopyTo(dataCopy, 0); // This test can not fail, so always report success. return true; }); // Run the test tester.Start(); // Print status information every second while(true) { Thread.Sleep(1000); Console.WriteLine(String.Format( "Requests: {0} ({1:0.00}/s), Errors: {2} ({3:0.00}%), ", tester.TotalTestsExecuted, tester.TotalTestsExecuted / tester.TotalSeconds, tester.TotalErrors, 100.0 * (double)tester.TotalErrors / tester.TotalTestsExecuted )); } } static byte[] MakeData() { // Return a 1 MB byte array const int dataSize = 1024 * 1024; byte[] data = new byte[dataSize]; for (int i = 0; i < dataSize; i++) { // Fill in some numbers data[i] = (byte)(i % 256); } return data; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using LoadTester; namespace LoadTester.Demo { public class Program { static void Main(string[] args) { // Create the load tester. Configure it to run lots of tests in parallel. var tester = new LoadTester { ParallelTests = 128 }; // Get a chunk of data var data = MakeData(); // Test how fast we can copy that data tester.AddTest(() => { var dataCopy = new byte[data.Length]; data.CopyTo(dataCopy, 0); // This test can not fail, so always report success. return true; }); // Run the test tester.Start(); // Print status information every second while(true) { Thread.Sleep(1000); Console.WriteLine(String.Format( "Requests: {0} ({1:0.00}/s), Errors: {2} ({3:0.00}%), ", tester.TotalTestsExecuted, tester.TotalTestsExecuted / tester.TotalSeconds, tester.TotalErrors, 100.0 * (double)tester.TotalErrors / tester.TotalTestsExecuted )); } } static byte[] MakeData() { // Return a 1 MB byte array const int dataSize = 1024 * 1024; byte[] data = new byte[dataSize]; for (int i = 0; i < dataSize; i++) { // Fill in some numbers data[i] = (byte)(i % 256); } return data; } } }
mit
C#
6c05c9530f13bade1a14611c130b0d14add732af
Correct the direction of the moon's travel.
JapaMala/armok-vision,JapaMala/armok-vision,JapaMala/armok-vision
Assets/Scripts/CelestialScripts/SunRotate.cs
Assets/Scripts/CelestialScripts/SunRotate.cs
using UnityEngine; public class SunRotate : MonoBehaviour { public float rotationSpeed = 1.0f; public float longitude; public float axialTilt; private int starMatrix; private int moonMatrix; public float GetLongitudeFromWorld(RemoteFortressReader.WorldMap world) { float tude = Mathf.InverseLerp(0, world.world_height, world.center_y); switch (world.world_poles) { case RemoteFortressReader.WorldPoles.NO_POLES: return 0; case RemoteFortressReader.WorldPoles.NORTH_POLE: tude = (1-tude) * 90; break; case RemoteFortressReader.WorldPoles.SOUTH_POLE: tude = tude * 90; break; case RemoteFortressReader.WorldPoles.BOTH_POLES: tude = ((tude * 2) - 1) * -180; break; default: return 0; } return tude; } private void Awake() { starMatrix = Shader.PropertyToID("_StarRotationMatrix"); moonMatrix = Shader.PropertyToID("_MoonRotationMatrix"); } // Update is called once per frame void Update() { var seasonRotation = Quaternion.Euler((Mathf.Cos(TimeHolder.DisplayedTime.SolsticeAngle * Mathf.Deg2Rad) * axialTilt), 0, 0); var planetRotation = Quaternion.AngleAxis(TimeHolder.DisplayedTime.SunAngle, Vector3.back); var yearRotation = Quaternion.AngleAxis(TimeHolder.DisplayedTime.SolsticeAngle, Vector3.back) * Quaternion.Euler(0, 90, 0); var moonRotation = Quaternion.AngleAxis(-((TimeHolder.DisplayedTime.SolsticeAngle * 13) + 111.923076923076f), Vector3.back) * Quaternion.Euler(0, 90, 0); transform.rotation = planetRotation * seasonRotation * Quaternion.Euler(0, 90, 0); RenderSettings.skybox.SetMatrix(starMatrix, Matrix4x4.Rotate(planetRotation * yearRotation * seasonRotation)); RenderSettings.skybox.SetMatrix(moonMatrix, Matrix4x4.Rotate(planetRotation * moonRotation * seasonRotation)); } }
using UnityEngine; public class SunRotate : MonoBehaviour { public float rotationSpeed = 1.0f; public float longitude; public float axialTilt; private int starMatrix; private int moonMatrix; public float GetLongitudeFromWorld(RemoteFortressReader.WorldMap world) { float tude = Mathf.InverseLerp(0, world.world_height, world.center_y); switch (world.world_poles) { case RemoteFortressReader.WorldPoles.NO_POLES: return 0; case RemoteFortressReader.WorldPoles.NORTH_POLE: tude = (1-tude) * 90; break; case RemoteFortressReader.WorldPoles.SOUTH_POLE: tude = tude * 90; break; case RemoteFortressReader.WorldPoles.BOTH_POLES: tude = ((tude * 2) - 1) * -180; break; default: return 0; } return tude; } private void Awake() { starMatrix = Shader.PropertyToID("_StarRotationMatrix"); moonMatrix = Shader.PropertyToID("_MoonRotationMatrix"); } // Update is called once per frame void Update() { var seasonRotation = Quaternion.Euler((Mathf.Cos(TimeHolder.DisplayedTime.SolsticeAngle * Mathf.Deg2Rad) * axialTilt), 0, 0); var planetRotation = Quaternion.AngleAxis(TimeHolder.DisplayedTime.SunAngle, Vector3.back); var yearRotation = Quaternion.AngleAxis(TimeHolder.DisplayedTime.SolsticeAngle, Vector3.back) * Quaternion.Euler(0, 90, 0); var moonRotation = Quaternion.AngleAxis((TimeHolder.DisplayedTime.SolsticeAngle * 13) + 111.923076923076f, Vector3.back) * Quaternion.Euler(0, 90, 0); transform.rotation = planetRotation * seasonRotation * Quaternion.Euler(0, 90, 0); RenderSettings.skybox.SetMatrix(starMatrix, Matrix4x4.Rotate(planetRotation * yearRotation * seasonRotation)); RenderSettings.skybox.SetMatrix(moonMatrix, Matrix4x4.Rotate(planetRotation * moonRotation * seasonRotation)); } }
mit
C#
93edc93c0cb26f3f6933b071b9f78b3614dcc58d
Add new Google Analytics tracking ID
aspnet/live.asp.net,reactiveui/website,reactiveui/website,sejka/live.asp.net,pakrym/kudutest,aspnet/live.asp.net,pakrym/kudutest,reactiveui/website,aspnet/live.asp.net,reactiveui/website,sejka/live.asp.net
src/live.asp.net/Views/Shared/_AnalyticsHead.cshtml
src/live.asp.net/Views/Shared/_AnalyticsHead.cshtml
@using Microsoft.ApplicationInsights.Extensibility @inject TelemetryConfiguration TelemetryConfiguration <environment names="Production"> <script type="text/javascript"> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' }); ga('create', 'UA-61337531-4', 'auto', { 'name': 'liveaspnetTracker' }); ga('mscTracker.send', 'pageview'); ga('liveaspnetTracker.send', 'pageview'); </script> @Html.ApplicationInsightsJavaScript(TelemetryConfiguration) </environment>
@using Microsoft.ApplicationInsights.Extensibility @inject TelemetryConfiguration TelemetryConfiguration <environment names="Production"> <script type="text/javascript"> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' }); ga('mscTracker.send', 'pageview'); </script> @Html.ApplicationInsightsJavaScript(TelemetryConfiguration) </environment>
mit
C#
b51a08c6cec288b7f7e1675a6db729c75e6a02d5
Bump version
Yuisbean/WebMConverter,nixxquality/WebMConverter,o11c/WebMConverter
Properties/AssemblyInfo.cs
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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.1")]
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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.0")]
mit
C#
2f9bc904353f34f930f93bad42202420f93ef1a9
Update Program.cs
tvert/GitTest1
ConsoleApp1/ConsoleApp1/Program.cs
ConsoleApp1/ConsoleApp1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // Code amended in GitHub } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { } } }
mit
C#
36922a518740d0a145efffbdaa3dee25871b131c
Add test
sakapon/Tools-2016
FileReplacer/UnitTest/DirectoryHelperTest.cs
FileReplacer/UnitTest/DirectoryHelperTest.cs
using System; using System.IO; using FileReplacer; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { [TestClass] public class DirectoryHelperTest { [TestMethod] public void ReplaceDirectoryName() { if (Directory.Exists("Root")) Directory.Delete("Root", true); Directory.CreateDirectory(@"Root\OldDir"); var dir = new DirectoryInfo(@"Root\OldDir"); DirectoryHelper.ReplaceDirectoryName(dir, "Old", "New"); Assert.AreEqual(false, Directory.Exists(@"Root\OldDir")); Assert.AreEqual(true, Directory.Exists(@"Root\NewDir")); } [TestMethod] public void ReplaceFileName() { if (Directory.Exists("Root")) Directory.Delete("Root", true); Directory.CreateDirectory("Root"); File.WriteAllText(@"Root\OldFile.txt", "Text"); var file = new FileInfo(@"Root\OldFile.txt"); DirectoryHelper.ReplaceFileName(file, "Old", "New"); Assert.AreEqual(false, File.Exists(@"Root\OldFile.txt")); Assert.AreEqual(true, File.Exists(@"Root\NewFile.txt")); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { [TestClass] public class DirectoryHelperTest { [TestMethod] public void TestMethod1() { } } }
mit
C#
e90e304fc6c956a384a83f42716e3f472ce32fd3
return list of excluded items
rauljmz/Sitecore-Courier,csteeg/Sitecore-Courier,cmgutmanis/Sitecore-Courier,adoprog/Sitecore-Courier
Sitecore.Courier.Runner/ExclusionReader.cs
Sitecore.Courier.Runner/ExclusionReader.cs
using System.Collections.Generic; using System.Xml; namespace Sitecore.Courier.Runner { // Reads the scproj file for excludedfiles and returns them for processing. public static class ExclusionReader { public static List<string> GetExcludedItems(string projectFilePath, string buildConfiguration) { var excludedItems = new List<string>(); var xmldocument = new XmlDocument(); xmldocument.Load(projectFilePath); var reader = XmlReader.Create(projectFilePath); reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "SitecoreItem") { var node = xmldocument.ReadNode(reader); foreach (XmlNode child in node.ChildNodes) { if (child.NodeType == XmlNodeType.Element && child.Name == "ExcludeItemFrom" && child.InnerText == buildConfiguration) { var path = node.Attributes[0].Value; excludedItems.Add(path); } } } } return excludedItems; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Sitecore.Courier.Runner { // Reads the scproj file for excludedfiles and returns them for processing. public static class ExclusionReader { public static List<string> GetExcludedItems(string projectFilePath, string buildConfiguration) { var excludedItems = new List<string>(); var reader = XmlReader.Create(projectFilePath); reader.MoveToContent(); while (reader.Read()) { // do stuff } return excludedItems; } } }
mit
C#
c6253c263e30ccd6eedd5825524b7190163ec54d
Fix bug by adding [DataContract].
EusthEnoptEron/Sketchball
Sketchball/GameComponents/HighscoreList.cs
Sketchball/GameComponents/HighscoreList.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Sketchball.GameComponents { /// <summary> /// /// </summary> [DataContract] public class HighscoreList : ICollection<HighscoreEntry> { [DataContract] private class DescendedComparer : IComparer<HighscoreEntry> { public int Compare(HighscoreEntry x, HighscoreEntry y) { // use the default comparer to do the original comparison for datetimes return x.CompareTo(y) * -1; } } private const int MAX_ENTRIES = 30; [DataMember] private SortedSet<HighscoreEntry> innerList = new SortedSet<HighscoreEntry>(new DescendedComparer()); public HighscoreList() { } public void Add(HighscoreEntry item) { innerList.Add(item); while (Count > MAX_ENTRIES) { innerList.Remove(innerList.Last()); } } public void Clear() { innerList.Clear(); } public bool Contains(HighscoreEntry item) { return innerList.Contains(item); } public void CopyTo(HighscoreEntry[] array, int arrayIndex) { innerList.CopyTo(array, arrayIndex); } public int Count { get { return innerList.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(HighscoreEntry item) { return innerList.Remove(item); } public IEnumerator<HighscoreEntry> GetEnumerator() { return innerList.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return innerList.GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Sketchball.GameComponents { /// <summary> /// /// </summary> [DataContract] public class HighscoreList : ICollection<HighscoreEntry> { private class DescendedComparer : IComparer<HighscoreEntry> { public int Compare(HighscoreEntry x, HighscoreEntry y) { // use the default comparer to do the original comparison for datetimes return x.CompareTo(y) * -1; } } private const int MAX_ENTRIES = 30; [DataMember] private SortedSet<HighscoreEntry> innerList = new SortedSet<HighscoreEntry>(new DescendedComparer()); public HighscoreList() { } public void Add(HighscoreEntry item) { innerList.Add(item); while (Count > MAX_ENTRIES) { innerList.Remove(innerList.Last()); } } public void Clear() { innerList.Clear(); } public bool Contains(HighscoreEntry item) { return innerList.Contains(item); } public void CopyTo(HighscoreEntry[] array, int arrayIndex) { innerList.CopyTo(array, arrayIndex); } public int Count { get { return innerList.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(HighscoreEntry item) { return innerList.Remove(item); } public IEnumerator<HighscoreEntry> GetEnumerator() { return innerList.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return innerList.GetEnumerator(); } } }
mit
C#
cfa4f027d01e8ddc4a0117cf60793fa15b7240d2
Remove redundant ctor call
anjdreas/UnitsNet,anjdreas/UnitsNet
UnitsNet.Tests/CustomQuantities/HowMuch.cs
UnitsNet.Tests/CustomQuantities/HowMuch.cs
using System; namespace UnitsNet.Tests.CustomQuantities { /// <inheritdoc cref="IQuantity"/> /// <summary> /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. /// </summary> public struct HowMuch : IQuantity { public HowMuch(double value, HowMuchUnit unit) { Unit = unit; Value = value; } Enum IQuantity.Unit => Unit; public HowMuchUnit Unit { get; } public double Value { get; } #region IQuantity private static readonly HowMuch Zero = new HowMuch(0, HowMuchUnit.Some); public QuantityType Type => QuantityType.Undefined; public BaseDimensions Dimensions => BaseDimensions.Dimensionless; public QuantityInfo QuantityInfo => new QuantityInfo(Type, new UnitInfo[] { new UnitInfo<HowMuchUnit>(HowMuchUnit.Some, BaseUnits.Undefined), new UnitInfo<HowMuchUnit>(HowMuchUnit.ATon, BaseUnits.Undefined), new UnitInfo<HowMuchUnit>(HowMuchUnit.AShitTon, BaseUnits.Undefined), }, HowMuchUnit.Some, Zero, BaseDimensions.Dimensionless); public double As(Enum unit) => Convert.ToDouble(unit); public double As(UnitSystem unitSystem) => throw new NotImplementedException(); public IQuantity ToUnit(Enum unit) { if (unit is HowMuchUnit howMuchUnit) return new HowMuch(As(unit), howMuchUnit); throw new ArgumentException("Must be of type HowMuchUnit.", nameof(unit)); } public IQuantity ToUnit(UnitSystem unitSystem) => throw new NotImplementedException(); public string ToString(string format, IFormatProvider formatProvider) => $"HowMuch ({format}, {formatProvider})"; public string ToString(IFormatProvider provider) => $"HowMuch ({provider})"; public string ToString(IFormatProvider provider, int significantDigitsAfterRadix) => $"HowMuch ({provider}, {significantDigitsAfterRadix})"; public string ToString(IFormatProvider provider, string format, params object[] args) => $"HowMuch ({provider}, {string.Join(", ", args)})"; #endregion } }
using System; namespace UnitsNet.Tests.CustomQuantities { /// <inheritdoc cref="IQuantity"/> /// <summary> /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. /// </summary> public struct HowMuch : IQuantity { public HowMuch(double value, HowMuchUnit unit) : this() { Unit = unit; Value = value; } Enum IQuantity.Unit => Unit; public HowMuchUnit Unit { get; } public double Value { get; } #region IQuantity private static readonly HowMuch Zero = new HowMuch(0, HowMuchUnit.Some); public QuantityType Type => QuantityType.Undefined; public BaseDimensions Dimensions => BaseDimensions.Dimensionless; public QuantityInfo QuantityInfo => new QuantityInfo(Type, new UnitInfo[] { new UnitInfo<HowMuchUnit>(HowMuchUnit.Some, BaseUnits.Undefined), new UnitInfo<HowMuchUnit>(HowMuchUnit.ATon, BaseUnits.Undefined), new UnitInfo<HowMuchUnit>(HowMuchUnit.AShitTon, BaseUnits.Undefined), }, HowMuchUnit.Some, Zero, BaseDimensions.Dimensionless); public double As(Enum unit) => Convert.ToDouble(unit); public double As(UnitSystem unitSystem) => throw new NotImplementedException(); public IQuantity ToUnit(Enum unit) { if (unit is HowMuchUnit howMuchUnit) return new HowMuch(As(unit), howMuchUnit); throw new ArgumentException("Must be of type HowMuchUnit.", nameof(unit)); } public IQuantity ToUnit(UnitSystem unitSystem) => throw new NotImplementedException(); public string ToString(string format, IFormatProvider formatProvider) => $"HowMuch ({format}, {formatProvider})"; public string ToString(IFormatProvider provider) => $"HowMuch ({provider})"; public string ToString(IFormatProvider provider, int significantDigitsAfterRadix) => $"HowMuch ({provider}, {significantDigitsAfterRadix})"; public string ToString(IFormatProvider provider, string format, params object[] args) => $"HowMuch ({provider}, {string.Join(", ", args)})"; #endregion } }
mit
C#
6e507d952f11287a2ab379475ab0b900872b05f9
Use ICollection.Any(), instead of Count() for validation
mysticfall/Alensia
Assets/Alensia/Core/Camera/CameraManager.cs
Assets/Alensia/Core/Camera/CameraManager.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Alensia.Core.Actor; using Alensia.Core.Common; using UnityEngine.Assertions; namespace Alensia.Core.Camera { public class CameraManager : ICameraManager { private ICameraMode _mode; public ICameraMode Mode { get { return _mode; } private set { if (value == null || value == _mode) return; if (_mode != null) _mode.Deactivate(); _mode = value; if (_mode == null) return; _mode.Activate(); CameraChanged.Fire(_mode); } } public ReadOnlyCollection<ICameraMode> AvailableModes { get; private set; } public CameraChangeEvent CameraChanged { get; private set; } public CameraManager(List<ICameraMode> modes, CameraChangeEvent cameraChanged) { Assert.IsNotNull(modes, "modes != null"); Assert.IsTrue(modes.Any(), "modes.Any()"); Assert.IsNotNull(cameraChanged, "cameraChanged != null"); AvailableModes = modes.AsReadOnly(); CameraChanged = cameraChanged; } public T Switch<T>() where T : class, ICameraMode { return AvailableModes.FirstOrDefault(m => m is T) as T; } public IFirstPersonCamera ToFirstPerson(IActor target) { var camera = Switch<IFirstPersonCamera>(); if (camera == null) return null; camera.Initialize(target); Mode = camera; return camera; } public IThirdPersonCamera ToThirdPerson(IActor target) { var camera = Switch<IThirdPersonCamera>(); if (camera == null) return null; camera.Initialize(target); Mode = camera; return camera; } public void Follow(ITransformable target) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Alensia.Core.Actor; using Alensia.Core.Common; using UnityEngine.Assertions; namespace Alensia.Core.Camera { public class CameraManager : ICameraManager { private ICameraMode _mode; public ICameraMode Mode { get { return _mode; } private set { if (value == null || value == _mode) return; if (_mode != null) _mode.Deactivate(); _mode = value; if (_mode == null) return; _mode.Activate(); CameraChanged.Fire(_mode); } } public ReadOnlyCollection<ICameraMode> AvailableModes { get; private set; } public CameraChangeEvent CameraChanged { get; private set; } public CameraManager(List<ICameraMode> modes, CameraChangeEvent cameraChanged) { Assert.IsNotNull(modes, "modes != null"); Assert.IsTrue(modes.Count > 0, "modes.Count > 0"); Assert.IsNotNull(cameraChanged, "cameraChanged != null"); AvailableModes = modes.AsReadOnly(); CameraChanged = cameraChanged; } public T Switch<T>() where T : class, ICameraMode { return AvailableModes.FirstOrDefault(m => m is T) as T; } public IFirstPersonCamera ToFirstPerson(IActor target) { var camera = Switch<IFirstPersonCamera>(); if (camera == null) return null; camera.Initialize(target); Mode = camera; return camera; } public IThirdPersonCamera ToThirdPerson(IActor target) { var camera = Switch<IThirdPersonCamera>(); if (camera == null) return null; camera.Initialize(target); Mode = camera; return camera; } public void Follow(ITransformable target) { throw new NotImplementedException(); } } }
apache-2.0
C#
0c2252863801a61d52afc3da47e46e961637bbfe
Bump número de versión a 0.8.4.0
TheXDS/MCART
CoreComponents/AssemblyInfo/AssemblyInfo.cs
CoreComponents/AssemblyInfo/AssemblyInfo.cs
/* AssemblyInfo.cs This file is part of Morgan's CLR Advanced Runtime (MCART) Author(s): César Andrés Morgan <xds_xps_ivx@hotmail.com> Copyright (c) 2011 - 2018 César Andrés Morgan Morgan's CLR Advanced Runtime (MCART) is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System.Reflection; [assembly: AssemblyCompany("TheXDS! non-Corp.")] [assembly: AssemblyProduct("Morgan's CLR Advanced Runtime")] [assembly: AssemblyCopyright("Copyright © 2011-2018 César Andrés Morgan")] [assembly: AssemblyVersion("0.8.4.0")] #if CLSCompliance [assembly: System.CLSCompliant(true)] #endif
/* AssemblyInfo.cs This file is part of Morgan's CLR Advanced Runtime (MCART) Author(s): César Andrés Morgan <xds_xps_ivx@hotmail.com> Copyright (c) 2011 - 2018 César Andrés Morgan Morgan's CLR Advanced Runtime (MCART) is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System.Reflection; [assembly: AssemblyCompany("TheXDS! non-Corp.")] [assembly: AssemblyProduct("Morgan's CLR Advanced Runtime")] [assembly: AssemblyCopyright("Copyright © 2011-2018 César Andrés Morgan")] [assembly: AssemblyVersion("0.8.3.4")] #if CLSCompliance [assembly: System.CLSCompliant(true)] #endif
mit
C#
2cea1291c5f3ce8452e9092eea436f46793dc373
Add Logger Name as a prefix on Log (optional)
eugeniusfox/vgprompter
VGPrompter/Logger.cs
VGPrompter/Logger.cs
using System; namespace VGPrompter { [Serializable] public class Logger { const string DEFAULT_NAME = "Logger", NULL = "Null"; public bool Enabled { get; set; } public string Name { get; private set; } Action<object> _logger; public Logger(bool enabled = true) : this(DEFAULT_NAME, enabled: enabled) { } public Logger(string name, Action<object> f = null, bool enabled = true) { Enabled = enabled; Name = name; _logger = f ?? Console.WriteLine; } public void Log(object s, bool logger_prefix = true) { if (Enabled) _logger(logger_prefix ? string.Format("[{0}] {1}", Name, s ?? NULL) : s); } } }
using System; namespace VGPrompter { [Serializable] public class Logger { public bool Enabled { get; set; } public string Name { get; private set; } Action<object> _logger; public Logger(bool enabled = true) : this("Default", enabled: enabled) { } public Logger(string name, Action<object> f = null, bool enabled = true) { Enabled = enabled; Name = name; _logger = f ?? Console.WriteLine; } public void Log(object s) { if (Enabled) _logger(s); } } }
mit
C#
89db866601c1cf5566bae0478249d5520a7afbb0
introduce _abc
miraimann/Knuth-Morris-Pratt
KnuthMorrisPratt/KnuthMorrisPratt/Finder.cs
KnuthMorrisPratt/KnuthMorrisPratt/Finder.cs
using System; using System.Collections.Generic; using System.Linq; namespace KnuthMorrisPratt { internal class Finder<T> : IFinder<T> { private readonly T[] _pattern; private readonly int[,] _dfa; private readonly Dictionary<T, int> _abc; public Finder(IEnumerable<T> word) { _pattern = word as T[] ?? word.ToArray(); _abc = _pattern.Distinct() .Select((v, i) => new { v, i }) .ToDictionary(o => o.v, o => o.i); _dfa = new int[_abc.Count, _pattern.Length]; _dfa[0, 0] = 1; for (int i = 0, j = 1; j < _pattern.Length; i = _dfa[_abc[_pattern[j++]], i]) { for (int c = 0; c < _abc.Count; c++) _dfa[c, j] = _dfa[c, i]; _dfa[_abc[_pattern[j]], j] = j + 1; } } public int FindIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public int FindLastIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public IEnumerable<int> FindAllIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public bool ExistsIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace KnuthMorrisPratt { internal class Finder<T> : IFinder<T> { private readonly T[] _pattern; private readonly int[,] _dfa; public Finder(IEnumerable<T> word) { _pattern = word as T[] ?? word.ToArray(); var abc = _pattern.Distinct().ToList(); _dfa = new int[abc.Count, _pattern.Length]; _dfa[0, 0] = 1; for (int x = 0, j = 1; j < _pattern.Length; x = _dfa[abc.IndexOf(_pattern[j++]), x]) { for (int c = 0; c < abc.Count; c++) _dfa[c, j] = _dfa[c, x]; _dfa[abc.IndexOf(_pattern[j]), j] = j + 1; } } public int FindIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public int FindLastIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public IEnumerable<int> FindAllIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public bool ExistsIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } } }
mit
C#
ccc55dc800afe83051a087595145781cccbf9d3e
Add DisposeChildren to IConductor, since it's really part of that...
cH40z-Lord/Stylet,canton7/Stylet,cH40z-Lord/Stylet,canton7/Stylet
Stylet/IConductor.cs
Stylet/IConductor.cs
using System; using System.Collections.Generic; namespace Stylet { /// <summary> /// Generalised parent, with many children /// </summary> /// <typeparam name="T">Type of children</typeparam> public interface IParent<out T> { /// <summary> /// Fetch all children of this parent /// </summary> /// <returns>All children owned by this parent</returns> IEnumerable<T> GetChildren(); } /// <summary> /// Thing which has a single active item /// </summary> /// <typeparam name="T">Type of the active item</typeparam> public interface IHaveActiveItem<T> { /// <summary> /// Gets or sets the only item which is currently active. /// This normally corresponds to the item being displayed /// </summary> T ActiveItem { get; set; } } /// <summary> /// Thing which has one or more children, and from which a child can request that it be closed /// </summary> public interface IChildDelegate { /// <summary> /// Called by the child to request that is be closed /// </summary> /// <param name="item">Child object, which is passed by the child itself</param> /// <param name="dialogResult">DialogResult to use to close, if any</param> void CloseItem(object item, bool? dialogResult = null); } /// <summary> /// Thing which owns one or more children, and can manage their lifecycles accordingly /// </summary> /// <typeparam name="T">Type of child being conducted</typeparam> // ReSharper disable once TypeParameterCanBeVariant // Not sure whether this might change in future... public interface IConductor<T> { /// <summary> /// Gets or sets a value indicating whether to dispose a child when it's closed. True by default /// </summary> bool DisposeChildren { get; set; } /// <summary> /// Activate the given item /// </summary> /// <param name="item">Item to activate</param> void ActivateItem(T item); /// <summary> /// Deactivate the given item /// </summary> /// <param name="item">Item to deactivate</param> void DeactivateItem(T item); /// <summary> /// Close the given item /// </summary> /// <param name="item">Item to close</param> void CloseItem(T item); } }
using System; using System.Collections.Generic; namespace Stylet { /// <summary> /// Generalised parent, with many children /// </summary> /// <typeparam name="T">Type of children</typeparam> public interface IParent<out T> { /// <summary> /// Fetch all children of this parent /// </summary> /// <returns>All children owned by this parent</returns> IEnumerable<T> GetChildren(); } /// <summary> /// Thing which has a single active item /// </summary> /// <typeparam name="T">Type of the active item</typeparam> public interface IHaveActiveItem<T> { /// <summary> /// Gets or sets the only item which is currently active. /// This normally corresponds to the item being displayed /// </summary> T ActiveItem { get; set; } } /// <summary> /// Thing which has one or more children, and from which a child can request that it be closed /// </summary> public interface IChildDelegate { /// <summary> /// Called by the child to request that is be closed /// </summary> /// <param name="item">Child object, which is passed by the child itself</param> /// <param name="dialogResult">DialogResult to use to close, if any</param> void CloseItem(object item, bool? dialogResult = null); } /// <summary> /// Thing which owns one or more children, and can manage their lifecycles accordingly /// </summary> /// <typeparam name="T">Type of child being conducted</typeparam> // ReSharper disable once TypeParameterCanBeVariant // Not sure whether this might change in future... public interface IConductor<T> { /// <summary> /// Activate the given item /// </summary> /// <param name="item">Item to activate</param> void ActivateItem(T item); /// <summary> /// Deactivate the given item /// </summary> /// <param name="item">Item to deactivate</param> void DeactivateItem(T item); /// <summary> /// Close the given item /// </summary> /// <param name="item">Item to close</param> void CloseItem(T item); } }
mit
C#
69e41efb95d564daf484e31fabd3b24f3d93ae1a
Throw Locked in Collection
signumsoftware/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework,avifatal/framework,AlejandroCano/framework
Signum.Entities/Patterns/LockeableEntity.cs
Signum.Entities/Patterns/LockeableEntity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.ComponentModel; using Signum.Utilities; using Signum.Utilities.Reflection; namespace Signum.Entities.Patterns { [Serializable] public abstract class LockableEntity : Entity { bool locked; public bool Locked { get { return locked; } set { if (UnsafeSet(ref locked, value, () => Locked)) ItemLockedChanged(Locked); } } protected bool UnsafeSet<T>(ref T field, T value, Expression<Func<T>> property) { return base.Set<T>(ref field, value, property); } protected virtual void ItemLockedChanged(bool locked) { } protected override bool Set<T>(ref T field, T value, Expression<Func<T>> property) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; if (this.locked) throw new ApplicationException(EntityMessage.AttemptToSet0InLockedEntity1.NiceToString().Formato(ReflectionTools.BasePropertyInfo(property).NiceName(), this.ToString())); return base.Set<T>(ref field, value, property); } protected override void ChildCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args) { if (this.locked) throw new ApplicationException(EntityMessage.AttemptToAddRemove0InLockedEntity1.NiceToString().Formato(sender.GetType().ElementType().NicePluralName(), this.ToString())); base.ChildCollectionChanged(sender, args); } public IDisposable AllowTemporalUnlock() { bool old = this.locked; this.locked = false; return new Disposable(() => this.locked = old); } } public enum EntityMessage { [Description("Attempt to set {0} in locked entity {1}")] AttemptToSet0InLockedEntity1, [Description("Attempt to add/remove {0} in locked entity {1}")] AttemptToAddRemove0InLockedEntity1 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.ComponentModel; using Signum.Utilities; namespace Signum.Entities.Patterns { [Serializable] public abstract class LockableEntity : Entity { bool locked; public bool Locked { get { return locked; } set { if (UnsafeSet(ref locked, value, () => Locked)) ItemLockedChanged(Locked); } } protected bool UnsafeSet<T>(ref T field, T value, Expression<Func<T>> property) { return base.Set<T>(ref field, value, property); } protected virtual void ItemLockedChanged(bool locked) { } protected override bool Set<T>(ref T field, T value, Expression<Func<T>> property) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; if (this.locked) throw new ApplicationException(EntityMessage.AttemptToModifyLockedEntity0.NiceToString().Formato(this.ToString())); return base.Set<T>(ref field, value, property); } public IDisposable AllowTemporalUnlock() { bool old = this.locked; this.locked = false; return new Disposable(() => this.locked = old); } } public enum EntityMessage { [Description("Attempt to modify locked entity {0}")] AttemptToModifyLockedEntity0 } }
mit
C#
bb13db8697ef574d6624f8784a320e4d14c47e6b
Update version number
awslabs/elasticache-cluster-config-net
Amazon.ElastiCacheCluster/Properties/AssemblyInfo.cs
Amazon.ElastiCacheCluster/Properties/AssemblyInfo.cs
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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("AmazonElastiCacheClusterConfig")] [assembly: AssemblyDescription("A configuration object to enable auto discovery in Enyim for ElastiCache")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("AmazonElastiCacheClusterConfig")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2014-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("526dcd43-9e27-40fe-aed6-5d72ad69b7cd")] // 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.4")] [assembly: AssemblyFileVersion("1.0.0.4")]
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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("AmazonElastiCacheClusterConfig")] [assembly: AssemblyDescription("A configuration object to enable auto discovery in Enyim for ElastiCache")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("AmazonElastiCacheClusterConfig")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("526dcd43-9e27-40fe-aed6-5d72ad69b7cd")] // 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.3")] [assembly: AssemblyFileVersion("1.0.0.3")]
apache-2.0
C#
1764f36659a39824321e02d23cbe1a82407b0c01
Fix FER+ and add debug lines
tobyclh/UnityCNTK,tobyclh/UnityCNTK
Assets/UnityCNTK/Scripts/Models/FERPlusModel.cs
Assets/UnityCNTK/Scripts/Models/FERPlusModel.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityCNTK; using CNTK; using System; using UnityEngine.Assertions; using System.Linq; namespace UnityCNTK { public class FERPlusModel : Model<Texture2D, int>, IStreamModel { [Tooltip("Evaluation carry out in every specificed second")] public float evaluationPeriod = 10; private bool shouldStop = false; private bool isStreaming = false; public new Texture2DSource dataSource; public void StartStreaming() { Assert.IsFalse(isStreaming, " is already streaming"); Debug.Log("Start Streaming"); InvokeRepeating("MyStream", 0, evaluationPeriod); } private async void MyStream() { //Debug.Log("Grabbing data"); var data = dataSource.GetData(); Evaluate(data); } public void StopStreaming() { Assert.IsTrue(isStreaming, name + " is not streaming"); CancelInvoke("MyStream"); } public override int OnPostProcess(Value output) { //Debug.Log("OnPostprocess FER+"); var expression = output.GetDenseData<float>(function.Output); var e = expression[0]; //Debug.Log("EXP Count :" + expression.Count); //Debug.Log("E Count :" + e.Count); Debug.Log(e[0].ToString() + " " + e[1].ToString() + " " + e[2].ToString() + " " + e[3].ToString() + " " + e[4].ToString() + " " + e[5].ToString() + " " + e[6].ToString() + " " + e[7].ToString()); return e.IndexOf(e.Max()); } public override Value OnPreprocess(Texture2D input) { //Debug.Log("OnPreprocess FER+"); return input.ToValue(CNTKManager.device, true); } public override void OnEvaluted(int output) { Debug.Log("OUTPUT : " + output); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityCNTK; using CNTK; using System; using UnityEngine.Assertions; namespace UnityCNTK { public class FERPlusModel : Model<Texture2D, int>, IStreamModel { [Tooltip("Evaluation carry out in every specificed second")] public float evaluationPeriod = 10; private bool shouldStop = false; private bool isStreaming = false; public new Texture2DSource dataSource; public void StartStreaming() { Assert.IsFalse(isStreaming, " is already streaming"); Debug.Log("Start Streaming"); InvokeRepeating("MyStream", 0, evaluationPeriod); } private void MyStream() { Debug.Log("Grabbing data"); var data =dataSource.GetData(); var s = Evaluate(data); } public void StopStreaming() { Assert.IsTrue(isStreaming, name + " is not streaming"); CancelInvoke("MyStream"); } public override int OnPostProcess(Value output) { Debug.Log("OnPostprocess FER+"); throw new NotImplementedException(); } public override Value OnPreprocess(Texture2D input) { Debug.Log("OnPreprocess FER+"); return input.ToValue(CNTKManager.device); } } }
mit
C#
4ee99a3fe2802f7263bc787c212ecf2b89d3002b
Package rename and add support for Media
wbsimms/WordPressRestApi
WordPressRestApi/Properties/AssemblyInfo.cs
WordPressRestApi/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WordPressRestApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DevFoundries")] [assembly: AssemblyProduct("WordPressRestApi")] [assembly: AssemblyCopyright("Copyright © 2017 Wm. Barrett Simms")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WordPressRestApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DevFoundries")] [assembly: AssemblyProduct("WordPressRestApi")] [assembly: AssemblyCopyright("Copyright © 2017 Wm. Barrett Simms")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
apache-2.0
C#
c3a002ae38651af69b7df76c47d5d81947b6a919
Edit details page for the news
Kidoo96/MediaNews,Kidoo96/MediaNews,Kidoo96/MediaNews
MediaNews/MediaNews.Index/Views/Posts/Details.cshtml
MediaNews/MediaNews.Index/Views/Posts/Details.cshtml
@model MediaNews.Entities.Models.Posts @{ ViewBag.Title = Model.Title; } <section class="post-content-section"> <div class="container"> <div class="row"> <div class="header"> @*@{ var base64 = Convert.ToBase64String(Model.imagePath); var imgSrc = String.Format("data:image/gif;base64,{0}", base64); }*@ <img src="@Model.ImgUrl" style="width:100%" /> <div class="triangulo"></div> <h5 class="sub-title-details"> Публикувано на: @Html.DisplayFor(model => model.DatePublished) в категория: @Html.DisplayFor(model => model.Category.Name) от: @Html.DisplayFor(model => model.Author.UserName)</h5> <h2 class="title-details">@Html.DisplayFor(model => model.Title)</h2> </div> <div class="col-lg-9 col-md-9 col-sm-12 mt-5"> @Html.DisplayFor(model => model.Content) </div> @if (Request.IsAuthenticated && User.IsInRole("Администратор")) { <div class="col-lg-3 col-md-3 col-sm-12"> <div class="well"> <h2>Управление</h2> @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Delete", "Delete", new { id = Model.Id }) </div> </div> } @{ Html.RenderPartial("_Comments"); } </div> </div> </section>
@model MediaNews.Entities.Models.Posts @{ ViewBag.Title = Model.Title; } <section class="post-content-section"> <div class="container"> <div class="row"> <div class="header"> @*@{ var base64 = Convert.ToBase64String(Model.imagePath); var imgSrc = String.Format("data:image/gif;base64,{0}", base64); }*@ <img src="@Model.ImgUrl" style="width:100%" /> <div class="triangulo"></div> <h5 class="sub-title-details"> Публикувано на: @Html.DisplayFor(model => model.DatePublished) в категория: @Html.DisplayFor(model => model.Category.Name) от: @Html.DisplayFor(model => model.Author.UserName)</h5> <h2 class="title-details">@Html.DisplayFor(model => model.Title)</h2> </div> <div class="col-lg-9 col-md-9 col-sm-12 mt-5"> @Html.DisplayFor(model => model.Content) </div> @{ Html.RenderPartial("_Comments"); } @if (Request.IsAuthenticated && User.IsInRole("Администратор")) { <div class="col-lg-3 col-md-3 col-sm-12"> <div class="well"> <h2>Управление</h2> @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Delete", "Delete", new { id = Model.Id }) </div> </div> } </div> </div> </section>
mit
C#
148b74d67f74b591f12c3bd9a064f8b6d37a4e4e
Make Flickr whoami method async
libertyernie/WeasylSync
ArtSourceWrapper/Flickr.cs
ArtSourceWrapper/Flickr.cs
using FlickrNet; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtSourceWrapper { public class FlickrWrapper : SiteWrapper<FlickrSubmissionWrapper, uint> { private Flickr _flickr; public FlickrWrapper(string apiKey, string sharedSecret, string oAuthAccessToken, string oAuthAccessTokenSecret) { _flickr = new Flickr(apiKey, sharedSecret) { OAuthAccessToken = oAuthAccessToken, OAuthAccessTokenSecret = oAuthAccessTokenSecret }; } public override string SiteName => "Flickr"; public override string WrapperName => "Flickr"; public override int BatchSize { get; set; } = 0; public override int MinBatchSize => 0; public override int MaxBatchSize => 0; private Task<Auth> AuthOAuthCheckTokenAsync() { var t = new TaskCompletionSource<Auth>(); _flickr.AuthOAuthCheckTokenAsync(a => { if (a.HasError) { t.SetException(a.Error); } else { t.SetResult(a.Result); } }); return t.Task; } public async override Task<string> WhoamiAsync() { var oauth = await AuthOAuthCheckTokenAsync(); return oauth.User.UserName; } protected async override Task<InternalFetchResult> InternalFetchAsync(uint? startPosition, int count) { return new InternalFetchResult(0, true); } } public class FlickrSubmissionWrapper : ISubmissionWrapper { public string Title => throw new NotImplementedException(); public string HTMLDescription => throw new NotImplementedException(); public bool PotentiallySensitive => throw new NotImplementedException(); public IEnumerable<string> Tags => throw new NotImplementedException(); public DateTime Timestamp => throw new NotImplementedException(); public string ViewURL => throw new NotImplementedException(); public string ImageURL => throw new NotImplementedException(); public string ThumbnailURL => throw new NotImplementedException(); public Color? BorderColor => throw new NotImplementedException(); public bool OwnWork => throw new NotImplementedException(); } }
using FlickrNet; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtSourceWrapper { public class FlickrWrapper : SiteWrapper<FlickrSubmissionWrapper, uint> { private Flickr _flickr; public FlickrWrapper(string apiKey, string sharedSecret, string oAuthAccessToken, string oAuthAccessTokenSecret) { _flickr = new Flickr(apiKey, sharedSecret) { OAuthAccessToken = oAuthAccessToken, OAuthAccessTokenSecret = oAuthAccessTokenSecret }; } public override string SiteName => "Flickr"; public override string WrapperName => "Flickr"; public override int BatchSize { get; set; } = 0; public override int MinBatchSize => 0; public override int MaxBatchSize => 0; public async override Task<string> WhoamiAsync() { var oauth = _flickr.AuthOAuthCheckToken(); return oauth.User.UserName; } protected async override Task<InternalFetchResult> InternalFetchAsync(uint? startPosition, int count) { return new InternalFetchResult(0, true); } } public class FlickrSubmissionWrapper : ISubmissionWrapper { public string Title => throw new NotImplementedException(); public string HTMLDescription => throw new NotImplementedException(); public bool PotentiallySensitive => throw new NotImplementedException(); public IEnumerable<string> Tags => throw new NotImplementedException(); public DateTime Timestamp => throw new NotImplementedException(); public string ViewURL => throw new NotImplementedException(); public string ImageURL => throw new NotImplementedException(); public string ThumbnailURL => throw new NotImplementedException(); public Color? BorderColor => throw new NotImplementedException(); public bool OwnWork => throw new NotImplementedException(); } }
mit
C#
1b27c2c6309420c6343eebe89dd17dabb70ea283
update comment (empty `recurrence-rule-expr` doesn't work yet)
IlyaKhD/DevExtreme.AspNet.TagHelpers,DevExpress/DevExtreme.AspNet.TagHelpers
Samples/Controllers/GoogleCalendarController.cs
Samples/Controllers/GoogleCalendarController.cs
using DevExtreme.AspNet.Data; using Microsoft.AspNet.Mvc; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace Samples.Controllers { public class GoogleCalendarController { public async Task<IActionResult> Appointments(DataSourceLoadOptions loadOptions) { var url = "https://www.googleapis.com/calendar/v3/calendars/" + "f7jnetm22dsjc3npc2lu3buvu4@group.calendar.google.com" + "/events?key=" + "AIzaSyBnNAISIUKe6xdhq1_rjor2rxoI3UlMY7k"; using(var client = new HttpClient()) { var json = await client.GetStringAsync(url); var appointments = from i in JObject.Parse(json)["items"] select new { text = (string)i["summary"], startDate = (DateTime?)i["start"]["dateTime"], endDate = (DateTime?)i["end"]["dateTime"], recurrenceRule = "" // TODO consider replacing with '-expr' attribute in 15.2.8 }; return DataSourceLoadResult.Create(appointments, loadOptions); } } } }
using DevExtreme.AspNet.Data; using Microsoft.AspNet.Mvc; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace Samples.Controllers { public class GoogleCalendarController { public async Task<IActionResult> Appointments(DataSourceLoadOptions loadOptions) { var url = "https://www.googleapis.com/calendar/v3/calendars/" + "f7jnetm22dsjc3npc2lu3buvu4@group.calendar.google.com" + "/events?key=" + "AIzaSyBnNAISIUKe6xdhq1_rjor2rxoI3UlMY7k"; using(var client = new HttpClient()) { var json = await client.GetStringAsync(url); var appointments = from i in JObject.Parse(json)["items"] select new { text = (string)i["summary"], startDate = (DateTime?)i["start"]["dateTime"], endDate = (DateTime?)i["end"]["dateTime"], recurrenceRule = "" // TODO consider replacing with '-expr' attribute in 15.2.6 }; return DataSourceLoadResult.Create(appointments, loadOptions); } } } }
mit
C#
230c7e1f1099ead2023275de6401312e5123a512
Fix tabs
WojcikMike/docs.particular.net
Snippets/Snippets_4/Persistence/Custom/Usage.cs
Snippets/Snippets_4/Persistence/Custom/Usage.cs
namespace Snippets4.Persistence.Custom { using NServiceBus; class Usage { public Usage() { #region PersistTimeoutsInterfaces public interface IPersistTimeouts { /// <summary> /// Retrieves the next range of timeouts that are due. /// </summary> /// <param name="startSlice">The time where to start retrieving the next slice, the slice should exclude this date.</param> /// <param name="nextTimeToRunQuery">Returns the next time we should query again.</param> /// <returns>Returns the next range of timeouts that are due.</returns> IEnumerable<Tuple<string, DateTime>> GetNextChunk(DateTime startSlice, out DateTime nextTimeToRunQuery); /// <summary> /// Adds a new timeout. /// </summary> /// <param name="timeout">Timeout data.</param> void Add(TimeoutData timeout); /// <summary> /// Removes the timeout if it hasn't been previously removed. /// </summary> /// <param name="timeoutId">The timeout id to remove.</param> /// <param name="timeoutData">The timeout data of the removed timeout.</param> /// <returns><c>true</c> it the timeout was successfully removed.</returns> bool TryRemove(string timeoutId, out TimeoutData timeoutData); /// <summary> /// Removes the time by saga id. /// </summary> /// <param name="sagaId">The saga id of the timeouts to remove.</param> void RemoveTimeoutBy(Guid sagaId); } public interface IPersistTimeoutsV2 { /// <summary> /// Reads timeout data. /// </summary> /// <param name="timeoutId">The timeout id to read.</param> /// <returns><see cref="TimeoutData"/> of the timeout if it was found. <c>null</c> otherwise.</returns> TimeoutData Peek(string timeoutId); /// <summary> /// Removes the timeout if it hasn't been previously removed. /// </summary> /// <param name="timeoutId">The timeout id to remove.</param> /// <returns><c>true</c> if the timeout has been successfully removed or <c>false</c> if there was no timeout to remove.</returns> bool TryRemove(string timeoutId); } #endregion } } }
namespace Snippets4.Persistence.Custom { using NServiceBus; class Usage { public Usage() { #region PersistTimeoutsInterfaces public interface IPersistTimeouts { /// <summary> /// Retrieves the next range of timeouts that are due. /// </summary> /// <param name="startSlice">The time where to start retrieving the next slice, the slice should exclude this date.</param> /// <param name="nextTimeToRunQuery">Returns the next time we should query again.</param> /// <returns>Returns the next range of timeouts that are due.</returns> IEnumerable<Tuple<string, DateTime>> GetNextChunk(DateTime startSlice, out DateTime nextTimeToRunQuery); /// <summary> /// Adds a new timeout. /// </summary> /// <param name="timeout">Timeout data.</param> void Add(TimeoutData timeout); /// <summary> /// Removes the timeout if it hasn't been previously removed. /// </summary> /// <param name="timeoutId">The timeout id to remove.</param> /// <param name="timeoutData">The timeout data of the removed timeout.</param> /// <returns><c>true</c> it the timeout was successfully removed.</returns> bool TryRemove(string timeoutId, out TimeoutData timeoutData); /// <summary> /// Removes the time by saga id. /// </summary> /// <param name="sagaId">The saga id of the timeouts to remove.</param> void RemoveTimeoutBy(Guid sagaId); } public interface IPersistTimeoutsV2 { /// <summary> /// Reads timeout data. /// </summary> /// <param name="timeoutId">The timeout id to read.</param> /// <returns><see cref="TimeoutData"/> of the timeout if it was found. <c>null</c> otherwise.</returns> TimeoutData Peek(string timeoutId); /// <summary> /// Removes the timeout if it hasn't been previously removed. /// </summary> /// <param name="timeoutId">The timeout id to remove.</param> /// <returns><c>true</c> if the timeout has been successfully removed or <c>false</c> if there was no timeout to remove.</returns> bool TryRemove(string timeoutId); } #endregion } } }
apache-2.0
C#
8cb2b512376e63c21e352b7326c98b8c1af37c66
Increment Intrinio time between calls to 1 minute
StefanoRaggi/Lean,JKarathiya/Lean,AlexCatarino/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,kaffeebrauer/Lean,StefanoRaggi/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,kaffeebrauer/Lean,jameschch/Lean,jameschch/Lean,JKarathiya/Lean,QuantConnect/Lean,kaffeebrauer/Lean,jameschch/Lean,JKarathiya/Lean,Jay-Jay-D/LeanSTP,kaffeebrauer/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,JKarathiya/Lean,QuantConnect/Lean,AlexCatarino/Lean,Jay-Jay-D/LeanSTP,AlexCatarino/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,StefanoRaggi/Lean,kaffeebrauer/Lean,QuantConnect/Lean,QuantConnect/Lean
Common/Data/Custom/Intrinio/IntrinioConfig.cs
Common/Data/Custom/Intrinio/IntrinioConfig.cs
using System; using QuantConnect.Parameters; using QuantConnect.Util; namespace QuantConnect.Data.Custom.Intrinio { /// <summary> /// Auxiliary class to access all Intrinio API data. /// </summary> public static class IntrinioConfig { /// <summary> /// </summary> public static RateGate RateGate = new RateGate(1, TimeSpan.FromMinutes(1)); /// <summary> /// Check if Intrinio API user and password are not empty or null. /// </summary> public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password); /// <summary> /// Intrinio API password /// </summary> public static string Password = string.Empty; /// <summary> /// Intrinio API user /// </summary> public static string User = string.Empty; /// <summary> /// Set the Intrinio API user and password. /// </summary> public static void SetUserAndPassword(string user, string password) { User = user; Password = password; if (!IsInitialized) { throw new InvalidOperationException("Please set a valid Intrinio user and password."); } } } }
using System; using QuantConnect.Parameters; using QuantConnect.Util; namespace QuantConnect.Data.Custom.Intrinio { /// <summary> /// Auxiliary class to access all Intrinio API data. /// </summary> public static class IntrinioConfig { /// <summary> /// </summary> public static RateGate RateGate = new RateGate(1, TimeSpan.FromMilliseconds(5000)); /// <summary> /// Check if Intrinio API user and password are not empty or null. /// </summary> public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password); /// <summary> /// Intrinio API password /// </summary> public static string Password = string.Empty; /// <summary> /// Intrinio API user /// </summary> public static string User = string.Empty; /// <summary> /// Set the Intrinio API user and password. /// </summary> public static void SetUserAndPassword(string user, string password) { User = user; Password = password; if (!IsInitialized) { throw new InvalidOperationException("Please set a valid Intrinio user and password."); } } } }
apache-2.0
C#
cc3fafe174ea4344e83e31b6403276830192a4f6
Update UserViewModel.cs
xcjs/ASP.NET-WebForm-MVVM-Demo
MVVMDemo/ViewModels/Account/UserViewModel.cs
MVVMDemo/ViewModels/Account/UserViewModel.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Web; using MVVMDemo.Entities; using MVVMDemo.ViewModels; namespace MVVMDemo.ViewModels.Account { public class UserViewModel : ViewModelBase<UserViewModel> { private User _user; public User User { get { return _user; } set { _user = value; NotifyPropertyChanged("User"); } } public UserViewModel() { } public bool SaveUser(User updatedUser) { bool saved = false; User = new User(); User.ID = updatedUser.ID; User.FirstName = updatedUser.FirstName.Trim(); User.LastName = updatedUser.LastName.Trim(); User.Address = updatedUser.Address.Trim(); User.Address2 = updatedUser.Address2.Trim(); User.City = updatedUser.City.Trim(); User.State = updatedUser.State.Trim(); User.Zip = updatedUser.Zip.Trim(); try { using (var db = new UsersEntities()) { User existingUser = db.Users.FirstOrDefault(u => u.ID == User.ID); if (existingUser != null) { existingUser.FirstName = User.FirstName; existingUser.LastName = User.LastName; existingUser.Address = User.Address; existingUser.Address2 = User.Address2; existingUser.City = User.City; existingUser.State = User.State; existingUser.Zip = User.Zip; } else { db.Users.AddObject(User); } if (db.SaveChanges() > 0) { saved = true; } } } catch (Exception ex) { Debug.WriteLine("An exception occurred while saving User changes: " + ex.Message); } return saved; } public static UserViewModel CreateInstance() { UserViewModel m = new UserViewModel(); m.User = User.CreateInstance(); return m; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Web; using MVVMDemo.Entities; using MVVMDemo.ViewModels; namespace MVVMDemo.ViewModels.Account { public class UserViewModel : ViewModelBase<UserViewModel> { private User _user; public User User { get { return _user; } set { _user = value; NotifyPropertyChanged("User"); } } public UserViewModel() { } public bool SaveUser(User updatedUser) { bool saved = false; User = new User(); User.ID = updatedUser.ID; User.FirstName = updatedUser.FirstName.Trim(); User.LastName = updatedUser.LastName.Trim(); User.Address = updatedUser.Address.Trim(); User.Address2 = updatedUser.Address2.Trim(); User.City = updatedUser.City.Trim(); User.State = updatedUser.State.Trim(); User.Zip = updatedUser.Zip.Trim(); try { using (var db = new UsersEntities()) { User existingUser = db.Users.FirstOrDefault(u => u.ID == User.ID); if (existingUser != null) { existingUser.FirstName = User.FirstName; existingUser.LastName = User.LastName; existingUser.Address = User.Address; existingUser.Address2 = User.Address2; existingUser.City = User.City; existingUser.State = User.State; existingUser.Zip = User.Zip; } else { db.Users.AddObject(User); } if (db.SaveChanges() > 0) { saved = true; } } } catch (Exception ex) { Debug.WriteLine("AN exception occurred while saving User changes: " + ex.Message); } return saved; } public static UserViewModel CreateInstance() { UserViewModel m = new UserViewModel(); m.User = User.CreateInstance(); return m; } } }
mit
C#
482aca7da07e7c00281d1a507fbdaa861436371f
Check pattern validity
Diego999/Game-Of-Life
Game-Of-Life/Patterns.cs
Game-Of-Life/Patterns.cs
using System; using System.Collections.Generic; using System.IO; namespace Game_Of_Life { /// <summary> /// Static class which holds all the patterns find in the folder "patterns" /// </summary> class Patterns { public static readonly Dictionary<string, PatternRepresentation> PATTERNS; // Dictionary where the key is the name of the pattern and the value the pattern private static readonly string DIRECTORY_PATTERNS = "patterns"; private static readonly string PATTERN_EXT = "txt"; static Patterns() { PATTERNS = new Dictionary<string, PatternRepresentation>(); string path = System.Environment.CurrentDirectory; path = path.Substring(0, path.LastIndexOf("bin")) + DIRECTORY_PATTERNS; string[] filePaths = Directory.GetFiles(path, "*." + PATTERN_EXT); string[] nl = new string[] { Environment.NewLine}; foreach(string filePath in filePaths) { String[] text = System.IO.File.ReadAllText(filePath).Split(nl, StringSplitOptions.None); if (text.Length > 0) { string key = Path.GetFileNameWithoutExtension(filePath); PatternRepresentation value = new PatternRepresentation(text.Length, text[0].Length); bool isPatternValid = true; for (int i = 0; i < text.Length && isPatternValid; ++i) { isPatternValid = text[i].Length == text[0].Length; for (int j = 0; j < text[i].Length && isPatternValid; ++j) isPatternValid = text[i][j].ToString() == PatternRepresentation.ALIVE || text[i][j].ToString() == PatternRepresentation.EMPTY; } if(isPatternValid) { for (int i = 0; i < text.Length; ++i) for (int j = 0; j < text[i].Length; ++j) if (text[i][j].ToString() == PatternRepresentation.ALIVE) value[i, j] = PatternRepresentation.ALIVE; PATTERNS.Add(key, value); } } } } } }
using System; using System.Collections.Generic; using System.IO; namespace Game_Of_Life { /// <summary> /// Static class which holds all the patterns find in the folder "patterns" /// </summary> class Patterns { public static readonly Dictionary<string, PatternRepresentation> PATTERNS; // Dictionary where the key is the name of the pattern and the value the pattern private static readonly string DIRECTORY_PATTERNS = "patterns"; private static readonly string PATTERN_EXT = "txt"; static Patterns() { PATTERNS = new Dictionary<string, PatternRepresentation>(); string path = System.Environment.CurrentDirectory; path = path.Substring(0, path.LastIndexOf("bin")) + DIRECTORY_PATTERNS; string[] filePaths = Directory.GetFiles(path, "*." + PATTERN_EXT); string[] nl = new string[] { Environment.NewLine}; foreach(string filePath in filePaths) { string key = Path.GetFileNameWithoutExtension(filePath); String[] text = System.IO.File.ReadAllText(filePath).Split(nl, StringSplitOptions.None); PatternRepresentation value = new PatternRepresentation(text.Length, text[0].Length); for (int i = 0; i < text.Length; ++i) for (int j = 0; j < text[i].Length; ++j) if (text[i][j].ToString() == PatternRepresentation.ALIVE) value[i, j] = PatternRepresentation.ALIVE; PATTERNS.Add(key, value); } } } }
mit
C#
23e942b6323998791bf158393984a97761b59173
Bump Android nuget version
SotoiGhost/FacebookComponents,SotoiGhost/FacebookComponents
Facebook.Android/build.cake
Facebook.Android/build.cake
#load "../common.cake" var NUGET_VERSION = "4.11.0.1"; var FB_VERSION = "4.11.0"; var FB_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}.aar", FB_VERSION); var FB_DOCS_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}-javadoc.jar", FB_VERSION); var AN_VERSION = "4.11.0"; var AN_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/audience-network-sdk/{0}/audience-network-sdk-{0}.aar", AN_VERSION); var TARGET = Argument ("t", Argument ("target", "Default")); var buildSpec = new BuildSpec () { Libs = new [] { new DefaultSolutionBuilder { SolutionPath = "./Xamarin.Facebook.sln", BuildsOn = BuildPlatforms.Mac, OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/Xamarin.Facebook/bin/Release/Xamarin.Facebook.dll", }, new OutputFileCopy { FromFile = "./source/Xamarin.Facebook.AudienceNetwork/bin/Release/Xamarin.Facebook.AudienceNetwork.dll", } } } }, Samples = new [] { new DefaultSolutionBuilder { SolutionPath = "./samples/HelloFacebookSample.sln" }, new DefaultSolutionBuilder { SolutionPath = "./samples/MessengerSendSample.sln" }, new DefaultSolutionBuilder { SolutionPath = "./samples/AudienceNetworkSample.sln" }, }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.Android.nuspec", Version = NUGET_VERSION }, new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.AudienceNetwork.Android.nuspec", Version = NUGET_VERSION }, }, Components = new [] { new Component {ManifestDirectory = "./component"}, }, }; Task ("externals") .WithCriteria (!FileExists ("./externals/facebook.aar")) .Does (() => { if (!DirectoryExists ("./externals/")) CreateDirectory ("./externals"); // Download the FB aar DownloadFile (FB_URL, "./externals/facebook.aar"); // Download, and unzip the docs .jar DownloadFile (FB_DOCS_URL, "./externals/facebook-docs.jar"); if (!DirectoryExists ("./externals/fb-docs")) CreateDirectory ("./externals/fb-docs"); Unzip ("./externals/facebook-docs.jar", "./externals/fb-docs"); // Download the FB aar DownloadFile (AN_URL, "./externals/audiencenetwork.aar"); }); Task ("clean").IsDependentOn ("clean-base").Does (() => { if (DirectoryExists ("./externals/")) DeleteDirectory ("./externals", true); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
#load "../common.cake" var NUGET_VERSION = "4.11.0"; var FB_VERSION = "4.11.0"; var FB_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}.aar", FB_VERSION); var FB_DOCS_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/facebook-android-sdk/{0}/facebook-android-sdk-{0}-javadoc.jar", FB_VERSION); var AN_VERSION = "4.11.0"; var AN_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/facebook/android/audience-network-sdk/{0}/audience-network-sdk-{0}.aar", AN_VERSION); var TARGET = Argument ("t", Argument ("target", "Default")); var buildSpec = new BuildSpec () { Libs = new [] { new DefaultSolutionBuilder { SolutionPath = "./Xamarin.Facebook.sln", BuildsOn = BuildPlatforms.Mac, OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/Xamarin.Facebook/bin/Release/Xamarin.Facebook.dll", }, new OutputFileCopy { FromFile = "./source/Xamarin.Facebook.AudienceNetwork/bin/Release/Xamarin.Facebook.AudienceNetwork.dll", } } } }, Samples = new [] { new DefaultSolutionBuilder { SolutionPath = "./samples/HelloFacebookSample.sln" }, new DefaultSolutionBuilder { SolutionPath = "./samples/MessengerSendSample.sln" }, new DefaultSolutionBuilder { SolutionPath = "./samples/AudienceNetworkSample.sln" }, }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.Android.nuspec", Version = NUGET_VERSION }, new NuGetInfo { NuSpec = "./nuget/Xamarin.Facebook.AudienceNetwork.Android.nuspec", Version = NUGET_VERSION }, }, Components = new [] { new Component {ManifestDirectory = "./component"}, }, }; Task ("externals") .WithCriteria (!FileExists ("./externals/facebook.aar")) .Does (() => { if (!DirectoryExists ("./externals/")) CreateDirectory ("./externals"); // Download the FB aar DownloadFile (FB_URL, "./externals/facebook.aar"); // Download, and unzip the docs .jar DownloadFile (FB_DOCS_URL, "./externals/facebook-docs.jar"); if (!DirectoryExists ("./externals/fb-docs")) CreateDirectory ("./externals/fb-docs"); Unzip ("./externals/facebook-docs.jar", "./externals/fb-docs"); // Download the FB aar DownloadFile (AN_URL, "./externals/audiencenetwork.aar"); }); Task ("clean").IsDependentOn ("clean-base").Does (() => { if (DirectoryExists ("./externals/")) DeleteDirectory ("./externals", true); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
mit
C#
2756269bd849141124900c6d016d5cf20d76b22c
Fix already existing title.
m5219/POGOLib,AeonLucid/POGOLib
POGOLib/Properties/AssemblyInfo.cs
POGOLib/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("POGOLib.Official")] [assembly: AssemblyDescription("A community driven PokémonGo API Library written in C#.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AeonLucid")] [assembly: AssemblyProduct("POGOLib.Official")] [assembly: AssemblyCopyright("Copyright © AeonLucid 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("3ba89dfb-a162-420a-9ded-daa211e52ad2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.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("POGOLib")] [assembly: AssemblyDescription("A community driven PokémonGo API Library written in C#.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AeonLucid")] [assembly: AssemblyProduct("POGOLib")] [assembly: AssemblyCopyright("Copyright © AeonLucid 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("3ba89dfb-a162-420a-9ded-daa211e52ad2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
0cf6defb0589c000158600f949f263fa67fc8e16
enhance cacheme with invoker
oelite/RESTme
OElite.Restme/Cacheme.cs
OElite.Restme/Cacheme.cs
using System; using System.Threading.Tasks; namespace OElite; /// <summary> /// Caching Utils for Restme /// </summary> public static class RestmeCacheExtensions { /// <summary> /// default expiry in seconds for cached item /// </summary> public const int defaultCacheExpiryInSeconds = 60; /// <summary> /// default expiry in seconds as cache grace period /// </summary> public const int defaultCacheGraceInSeconds = 3600; /// <summary> /// default refresh in seconds based on a cache's cachedOnUtc /// </summary> public const int defaultCacheRefreshInSeconds = 60; public static async Task<ResponseMessage> CachemeAsync(this Rest rest, string uid, object data, int expiryInSeconds = -1, int graceInSeconds = -1) { var result = default(ResponseMessage); if (rest == null || !uid.IsNotNullOrEmpty()) return result; var expiry = expiryInSeconds > 0 ? DateTime.UtcNow.AddSeconds(expiryInSeconds) : DateTime.UtcNow.AddSeconds(defaultCacheExpiryInSeconds); var grace = graceInSeconds > 0 ? expiry.AddSeconds(graceInSeconds) : expiry; var responseMessage = new ResponseMessage(data) { ExpiryOnUtc = expiry, GraceTillUtc = grace }; result = await rest?.PostAsync<ResponseMessage>(uid, responseMessage); return result; } public static async Task<T> FindmeAsync<T>(this Rest rest, string uid, bool returnExpired = false, bool returnInGrace = true, Func<Task<T>> refreshAction = null) where T : class { var obj = rest?.Get<ResponseMessage>(uid); if (obj is { Data: { } }) { var result = obj.GetOriginalData<T>(); if (returnExpired) return result; if (returnInGrace && obj.GraceTillUtc >= DateTime.UtcNow) { if (obj.ExpiryOnUtc <= DateTime.UtcNow) { refreshAction.Invoke().RunInBackgroundAndForget(); } return result; } if (obj.ExpiryOnUtc >= DateTime.UtcNow) return result; return await refreshAction.Invoke(); } return default; } }
using System; using System.Threading.Tasks; namespace OElite; /// <summary> /// Caching Utils for Restme /// </summary> public static class RestmeCacheExtensions { /// <summary> /// default expiry in seconds for cached item /// </summary> public const int defaultCacheExpiryInSeconds = 60; /// <summary> /// default expiry in seconds as cache grace period /// </summary> public const int defaultCacheGraceInSeconds = 3600; /// <summary> /// default refresh in seconds based on a cache's cachedOnUtc /// </summary> public const int defaultCacheRefreshInSeconds = 60; public static async Task<ResponseMessage> CachemeAsync(this Rest rest, string uid, object data, int expiryInSeconds = -1, int graceInSeconds = -1) { var result = default(ResponseMessage); if (rest == null || !uid.IsNotNullOrEmpty()) return result; var expiry = expiryInSeconds > 0 ? DateTime.UtcNow.AddSeconds(expiryInSeconds) : DateTime.UtcNow.AddSeconds(defaultCacheExpiryInSeconds); var grace = graceInSeconds > 0 ? expiry.AddSeconds(graceInSeconds) : expiry; var responseMessage = new ResponseMessage(data) { ExpiryOnUtc = expiry, GraceTillUtc = grace }; result = await rest?.PostAsync<ResponseMessage>(uid, responseMessage); return result; } public static async Task<T> FindmeAsync<T>(this Rest rest, string uid, bool returnExpired = false, bool returnInGrace = true) where T : class { var obj = rest?.Get<ResponseMessage>(uid); if (obj is { Data: { } }) { var result = obj.Data as T; if (returnExpired) return result; if (returnInGrace && obj.GraceTillUtc >= DateTime.UtcNow) return result; if (obj.ExpiryOnUtc >= DateTime.UtcNow) return result; } return default; } }
mit
C#
6fcd5b195bd07c05ddb19cfd5689f7cdba5525eb
Add missing attributes to paymentSource
conekta/conekta-.net
src/conekta/conekta/Models/PaymentSource.cs
src/conekta/conekta/Models/PaymentSource.cs
using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class PaymentSource : Resource { public string id { get; set; } public string type { get; set; } /* In case card token */ public string token_id { get; set; } /* In case card object*/ public string name { get; set; } public string number { get; set; } public string exp_month { get; set; } public string exp_year { get; set; } public string cvc { get; set; } public string last4 { get; set; } public string bin { get; set; } public string brand { get; set; } public Address address { get; set; } public string parent_id { get; set; } public PaymentSource update(string data) { PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString()); return payment_source; } public PaymentSource destroy() { this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id); return this; } public PaymentSource toClass(string json) { PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return payment_source; } } }
using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class PaymentSource : Resource { public string id { get; set; } public string type { get; set; } /* In case card token */ public string token_id { get; set; } /* In case card object*/ public string name { get; set; } public string number { get; set; } public string exp_month { get; set; } public string exp_year { get; set; } public string cvc { get; set; } public Address address { get; set; } public string parent_id { get; set; } public PaymentSource update(string data) { PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString()); return payment_source; } public PaymentSource destroy() { this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id); return this; } public PaymentSource toClass(string json) { PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return payment_source; } } }
mit
C#
f769f9ea1c43cd4545b81e9d1079b359de289f4b
Update LibraryExporterExtensions.cs
naamunds/cli,Faizan2304/cli,blackdwarf/cli,MichaelSimons/cli,mlorbetske/cli,Faizan2304/cli,weshaggard/cli,mlorbetske/cli,weshaggard/cli,livarcocc/cli-1,johnbeisner/cli,nguerrera/cli,AbhitejJohn/cli,svick/cli,EdwardBlair/cli,harshjain2/cli,dasMulli/cli,johnbeisner/cli,AbhitejJohn/cli,jonsequitur/cli,weshaggard/cli,blackdwarf/cli,naamunds/cli,nguerrera/cli,MichaelSimons/cli,livarcocc/cli-1,weshaggard/cli,nguerrera/cli,ravimeda/cli,naamunds/cli,johnbeisner/cli,naamunds/cli,MichaelSimons/cli,dasMulli/cli,dasMulli/cli,jonsequitur/cli,svick/cli,nguerrera/cli,MichaelSimons/cli,Faizan2304/cli,mlorbetske/cli,jonsequitur/cli,naamunds/cli,ravimeda/cli,AbhitejJohn/cli,harshjain2/cli,EdwardBlair/cli,ravimeda/cli,svick/cli,harshjain2/cli,weshaggard/cli,mlorbetske/cli,blackdwarf/cli,livarcocc/cli-1,EdwardBlair/cli,blackdwarf/cli,MichaelSimons/cli,AbhitejJohn/cli,jonsequitur/cli
src/Microsoft.DotNet.Compiler.Common/LibraryExporterExtensions.cs
src/Microsoft.DotNet.Compiler.Common/LibraryExporterExtensions.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation; using Microsoft.DotNet.ProjectModel.Graph; namespace Microsoft.DotNet.Cli.Compiler.Common { public static class LibraryExporterExtensions { public static IEnumerable<LibraryExport> GetAllProjectTypeDependencies(this LibraryExporter exporter) { return exporter.GetDependencies(LibraryType.Project) .Concat(exporter.GetDependencies(LibraryType.MSBuildProject)); } public static void CopyTo(this IEnumerable<LibraryAsset> assets, string destinationPath) { if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } foreach (var asset in assets) { var file = Path.Combine(destinationPath, Path.GetFileName(asset.ResolvedPath)); File.Copy(asset.ResolvedPath, file, overwrite: true); RemoveFileAttribute(file, FileAttributes.ReadOnly); } } private static void RemoveFileAttribute(String file, FileAttributes attribute) { if (File.Exists(file)) { var fileAttributes = File.GetAttributes(file); if ((fileAttributes & attribute) == attribute) { File.SetAttributes(file, fileAttributes & ~attribute); } } } public static void StructuredCopyTo(this IEnumerable<LibraryAsset> assets, string destinationPath, string tempLocation) { if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } foreach (var asset in assets) { var targetName = ResolveTargetName(destinationPath, asset); var transformedFile = asset.GetTransformedFile(tempLocation); File.Copy(transformedFile, targetName, overwrite: true); RemoveFileAttribute(targetName, FileAttributes.ReadOnly); } } private static string ResolveTargetName(string destinationPath, LibraryAsset asset) { string targetName; if (!string.IsNullOrEmpty(asset.RelativePath)) { targetName = Path.Combine(destinationPath, asset.RelativePath); var destinationAssetPath = Path.GetDirectoryName(targetName); if (!Directory.Exists(destinationAssetPath)) { Directory.CreateDirectory(destinationAssetPath); } } else { targetName = Path.Combine(destinationPath, Path.GetFileName(asset.ResolvedPath)); } return targetName; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation; using Microsoft.DotNet.ProjectModel.Graph; namespace Microsoft.DotNet.Cli.Compiler.Common { public static class LibraryExporterExtensions { public static IEnumerable<LibraryExport> GetAllProjectTypeDependencies(this LibraryExporter exporter) { return exporter.GetDependencies(LibraryType.Project) .Concat(exporter.GetDependencies(LibraryType.MSBuildProject)); } public static void CopyTo(this IEnumerable<LibraryAsset> assets, string destinationPath) { if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } foreach (var asset in assets) { File.Copy(asset.ResolvedPath, Path.Combine(destinationPath, Path.GetFileName(asset.ResolvedPath)), overwrite: true); } } public static void StructuredCopyTo(this IEnumerable<LibraryAsset> assets, string destinationPath, string tempLocation) { if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } foreach (var asset in assets) { var targetName = ResolveTargetName(destinationPath, asset); var transformedFile = asset.GetTransformedFile(tempLocation); File.Copy(transformedFile, targetName, overwrite: true); } } private static string ResolveTargetName(string destinationPath, LibraryAsset asset) { string targetName; if (!string.IsNullOrEmpty(asset.RelativePath)) { targetName = Path.Combine(destinationPath, asset.RelativePath); var destinationAssetPath = Path.GetDirectoryName(targetName); if (!Directory.Exists(destinationAssetPath)) { Directory.CreateDirectory(destinationAssetPath); } } else { targetName = Path.Combine(destinationPath, Path.GetFileName(asset.ResolvedPath)); } return targetName; } } }
mit
C#
cde4a38dadc9c31c079b9e807e84f3f76dc4c450
Fix null reference exception in MediaField.cshtml (#3228)
stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.Media/Views/MediaField.cshtml
src/OrchardCore.Modules/OrchardCore.Media/Views/MediaField.cshtml
@model OrchardCore.Media.ViewModels.DisplayMediaFieldViewModel @using OrchardCore.ContentManagement.Metadata.Models <div> @Model.PartFieldDefinition.DisplayName(): @String.Join(", ", Model.Field.Paths ?? Array.Empty<string>()) </div>
@model OrchardCore.Media.ViewModels.DisplayMediaFieldViewModel @using OrchardCore.ContentManagement.Metadata.Models <div> @Model.PartFieldDefinition.DisplayName(): @String.Join(", ", Model.Field.Paths) </div>
bsd-3-clause
C#
49862aaad1bc84f45cf5efc29ee13b84ed5560a2
Remove dead code.
ProjectExtensions/ProjectExtensions.Azure.ServiceBus
src/Tests/ProjectExtensions.Azure.ServiceBus.Tests.Unit/Config.cs
src/Tests/ProjectExtensions.Azure.ServiceBus.Tests.Unit/Config.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; using Autofac; using ProjectExtensions.Azure.ServiceBus.Interfaces; using ProjectExtensions.Azure.ServiceBus.Tests.Unit.Mocks; using ProjectExtensions.Azure.ServiceBus.Tests.Unit.Messages; using ProjectExtensions.Azure.ServiceBus.Tests.Unit.Interfaces; using System.Diagnostics; namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit { [SetUpFixture] public class Config { [SetUp] public void SetUp() { var builder = new ContainerBuilder(); builder.RegisterType(typeof(MockSubscriptionClient)).As(typeof(ISubscriptionClient)).SingleInstance(); builder.RegisterType(typeof(MockTopicClient)).As(typeof(ITopicClient)).SingleInstance(); builder.RegisterType(typeof(MockNamespaceManager)).As(typeof(INamespaceManager)).SingleInstance(); builder.RegisterType(typeof(MockMessagingFactory)).As(typeof(IMessagingFactory)).SingleInstance(); builder.RegisterType(typeof(MockServiceBus)).As(typeof(IBus)).SingleInstance(); BusConfiguration.WithSettings() .UseAutofacContainer(builder.Build()) .ServiceBusApplicationId("AppName") .TopicName("test") .RegisterAssembly(typeof(Config).Assembly) .Configure(); //test send a message for (int i = 0; i < 10; i++) { BusConfiguration.Instance.Bus.PublishAsync(new TestMessageForTesting(), (callback) => { Console.WriteLine("Time Spent:" + callback.TimeSpent); }); } } [TearDown] public void TearDown() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; using Autofac; using ProjectExtensions.Azure.ServiceBus.Interfaces; using ProjectExtensions.Azure.ServiceBus.Tests.Unit.Mocks; using ProjectExtensions.Azure.ServiceBus.Tests.Unit.Messages; using ProjectExtensions.Azure.ServiceBus.Tests.Unit.Interfaces; using System.Diagnostics; namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit { [SetUpFixture] public class Config { [SetUp] public void SetUp() { var builder = new ContainerBuilder(); builder.RegisterType(typeof(MockSubscriptionClient)).As(typeof(ISubscriptionClient)).SingleInstance(); builder.RegisterType(typeof(MockTopicClient)).As(typeof(ITopicClient)).SingleInstance(); builder.RegisterType(typeof(MockNamespaceManager)).As(typeof(INamespaceManager)).SingleInstance(); builder.RegisterType(typeof(MockMessagingFactory)).As(typeof(IMessagingFactory)).SingleInstance(); builder.RegisterType(typeof(MockServiceBus)).As(typeof(IBus)).SingleInstance(); BusConfiguration.WithSettings() .UseAutofacContainer(builder.Build()) .ServiceBusApplicationId("AppName") .TopicName("test") .RegisterAssembly(typeof(Config).Assembly) .Configure(); //test send a message for (int i = 0; i < 10; i++) { BusConfiguration.Instance.Bus.PublishAsync(new TestMessageForTesting(), (callback) => { Console.WriteLine("Time Spent:" + callback.TimeSpent); }); } Console.ReadLine(); } [TearDown] public void TearDown() { } } }
bsd-3-clause
C#
7f189080b91a0d8d7a082b28b023eb939c86b023
Move fail override back to abstract implementation
ppy/osu,UselessToucan/osu,EVAST9919/osu,naoey/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu,naoey/osu,ZLima12/osu,smoogipooo/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,Nabile-Rahmani/osu,peppy/osu-new,peppy/osu,DrabWeb/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,DrabWeb/osu,2yangk23/osu,ppy/osu,ZLima12/osu,smoogipoo/osu,peppy/osu,Frontear/osuKyzer,UselessToucan/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu
osu.Game/Rulesets/Mods/ModAutoplay.cs
osu.Game/Rulesets/Mods/ModAutoplay.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mods { public class ModAutoplay<T> : ModAutoplay, IApplicableToRulesetContainer<T> where T : HitObject { protected virtual Score CreateReplayScore(Beatmap<T> beatmap) => new Score { Replay = new Replay() }; public override bool HasImplementation => GetType().GenericTypeArguments.Length == 0; public virtual void ApplyToRulesetContainer(RulesetContainer<T> rulesetContainer) => rulesetContainer.SetReplay(CreateReplayScore(rulesetContainer.Beatmap)?.Replay); } public abstract class ModAutoplay : Mod, IApplicableFailOverride { public override string Name => "Autoplay"; public override string ShortenedName => "AT"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_auto; public override string Description => "Watch a perfect automated play through the song"; public override double ScoreMultiplier => 0; public bool AllowFail => false; public override Type[] IncompatibleMods => new[] { typeof(ModRelax), typeof(ModSuddenDeath), typeof(ModNoFail) }; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mods { public class ModAutoplay<T> : ModAutoplay, IApplicableToRulesetContainer<T>, IApplicableFailOverride where T : HitObject { protected virtual Score CreateReplayScore(Beatmap<T> beatmap) => new Score { Replay = new Replay() }; public override bool HasImplementation => GetType().GenericTypeArguments.Length == 0; public bool AllowFail => false; public virtual void ApplyToRulesetContainer(RulesetContainer<T> rulesetContainer) => rulesetContainer.SetReplay(CreateReplayScore(rulesetContainer.Beatmap)?.Replay); } public abstract class ModAutoplay : Mod { public override string Name => "Autoplay"; public override string ShortenedName => "AT"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_auto; public override string Description => "Watch a perfect automated play through the song"; public override double ScoreMultiplier => 0; public override Type[] IncompatibleMods => new[] { typeof(ModRelax), typeof(ModSuddenDeath), typeof(ModNoFail) }; } }
mit
C#
14b189ae67e5898bafeb7aada362592c31f68f49
Refactor a code
kawatan/Milk
Megalopolis/Extensions.cs
Megalopolis/Extensions.cs
using System; using System.Collections.Generic; using System.Linq; namespace Megalopolis { public static class Extensions { public static int Binomial(this Random random, int n, double p) { int count = 0; for (int i = 0; i < n; i++) { if (random.NextDouble() < p) { count++; } } return count; } public static double Uniform(this Random random, double min, double max) { return (max - min) * random.NextDouble() + min; } public static IEnumerable<T> Sample<T>(this IEnumerable<T> collection, Random random, int size) { // Generates a random sample from a given 1-D collection T[] array1 = collection.ToArray(); T[] array2 = new T[array1.Length < size ? array1.Length : size]; int max = collection.Count(); int i = 0; while (i < array2.Length) { int j = random.Next(i, max); T temp = array1[i]; array1[i] = array2[i] = array1[j]; array1[j] = temp; i++; } return array2; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Megalopolis { public static class Extensions { public static int Binomial(this Random random, int n, double p) { int count = 0; for (int i = 0; i < n; i++) { if (random.NextDouble() < p) { count++; } } return count; } public static double Uniform(this Random random, double min, double max) { return (max - min) * random.NextDouble() + min; } public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection, Random random) { // Fisher-Yates algorithm T[] array = collection.ToArray(); int n = array.Length; // The number of items left to shuffle (loop invariant). while (n > 1) { int k = random.Next(n); // 0 <= k < n. n--; // n is now the last pertinent index; T temp = array[n]; // swap list[n] with list[k] (does nothing if k == n). array[n] = array[k]; array[k] = temp; } return array; } public static IEnumerable<T> Sample<T>(this IEnumerable<T> collection, Random random, int size) { // Generates a random sample from a given 1-D collection T[] array1 = collection.ToArray(); T[] array2 = new T[array1.Length < size ? array1.Length : size]; int max = collection.Count(); int i = 0; while (i < array2.Length) { int j = random.Next(i, max); T temp = array1[i]; array1[i] = array2[i] = array1[j]; array1[j] = temp; i++; } return array2; } } }
apache-2.0
C#
135df8c9cdb8287a2ca408492ca7306a9db1e1a2
Handle MapVidyanoWeb2Route for HttpRouteCollection as well
2sky/Vidyano,jmptrader/Vidyano,jmptrader/Vidyano,2sky/Vidyano,2sky/Vidyano,2sky/Vidyano,2sky/Vidyano,jmptrader/Vidyano
dist/Vidyano.Web2/Web2ControllerFactory.cs
dist/Vidyano.Web2/Web2ControllerFactory.cs
using System.Web.Http; using System.Web.Routing; namespace Vidyano.Web2 { public static class Web2ControllerFactory { public static void MapVidyanoWeb2Route(this RouteCollection routes, string routeTemplate = "web2/") { routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional }); routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional }); } public static void MapVidyanoWeb2Route(this HttpRouteCollection routes, string routeTemplate = "web2/") { routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional }); routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional }); } } }
using System.Web.Http; using System.Web.Routing; namespace Vidyano.Web2 { public static class Web2ControllerFactory { public static void MapVidyanoWeb2Route(this RouteCollection routes, string routeTemplate = "web2/") { routes.MapHttpRoute("VidyanoWeb2 Vulcanize", routeTemplate + "vulcanize/{*id}", new { controller = "Web2", action = "Vulcanize", id = RouteParameter.Optional }); routes.MapHttpRoute("VidyanoWeb2", routeTemplate + "{*id}", new { controller = "Web2", action = "Get", id = RouteParameter.Optional }); } } }
mit
C#
ac1511d79c56c410c905303cf7f13b94faaa6718
Remove "Last" LINQ method call in Load decimal method.
eXavera/NDbfReader
NDbfReader/DecimalColumn.cs
NDbfReader/DecimalColumn.cs
using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; namespace NDbfReader { /// <summary> /// Represents a <see cref="decimal"/> column. /// </summary> [DebuggerDisplay("Decimal {Name}")] public class DecimalColumn : Column<decimal?> { private static readonly NumberFormatInfo DecimalNumberFormat = new NumberFormatInfo { NumberDecimalSeparator = "." }; /// <summary> /// Initializes a new instance with the specified name and offset. /// </summary> /// <param name="name">The column name.</param> /// <param name="offset">The column offset in a row in bytes.</param> /// <param name="size">The column size in bytes.</param> /// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c> or empty.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> is &lt; 0 or <paramref name="size"/> is &lt; 0.</exception> public DecimalColumn(string name, int offset, int size) : base(name, offset, size) { } /// <summary> /// Loads a value from the specified buffer. /// </summary> /// <param name="buffer">The byte array from which a value should be loaded. The buffer length is always at least equal to the column size.</paramm> /// <param name="offset">The byte offset in <paramref name="buffer"/> at which loading begins. </param> /// <param name="encoding">The encoding that should be used when loading a value. The encoding is never <c>null</c>.</param> /// <returns>A column value.</returns> protected override decimal? DoLoad(byte[] buffer, int offset, Encoding encoding) { string stringValue = encoding.GetString(buffer, offset, Size); if (stringValue.Length == 0) { return null; } char lastChar = stringValue[stringValue.Length - 1]; if (lastChar == ' ' || lastChar == '?') { return null; } return decimal.Parse(stringValue, NumberStyles.Float | NumberStyles.AllowLeadingWhite, DecimalNumberFormat); } } }
using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; namespace NDbfReader { /// <summary> /// Represents a <see cref="decimal"/> column. /// </summary> [DebuggerDisplay("Decimal {Name}")] public class DecimalColumn : Column<decimal?> { private static readonly NumberFormatInfo DecimalNumberFormat = new NumberFormatInfo { NumberDecimalSeparator = "." }; /// <summary> /// Initializes a new instance with the specified name and offset. /// </summary> /// <param name="name">The column name.</param> /// <param name="offset">The column offset in a row in bytes.</param> /// <param name="size">The column size in bytes.</param> /// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c> or empty.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> is &lt; 0 or <paramref name="size"/> is &lt; 0.</exception> public DecimalColumn(string name, int offset, int size) : base(name, offset, size) { } /// <summary> /// Loads a value from the specified buffer. /// </summary> /// <param name="buffer">The byte array from which a value should be loaded. The buffer length is always at least equal to the column size.</param> /// <param name="offset">The byte offset in <paramref name="buffer"/> at which loading begins. </param> /// <param name="encoding">The encoding that should be used when loading a value. The encoding is never <c>null</c>.</param> /// <returns>A column value.</returns> protected override decimal? DoLoad(byte[] buffer, int offset, Encoding encoding) { string stringValue = encoding.GetString(buffer, offset, Size); if (stringValue.Length == 0) { return null; } char lastChar = stringValue.Last(); if (lastChar == ' ' || lastChar == '?') { return null; } return decimal.Parse(stringValue, NumberStyles.Float | NumberStyles.AllowLeadingWhite, DecimalNumberFormat); } } }
mit
C#
594771c3e00e362c10b43ac9b118260e78142cda
remove use of USE_GENERICS in PatriciaTree.cs
kjk/volante-obsolete,ingted/volante,kjk/volante-obsolete,ingted/volante,kjk/volante-obsolete,kjk/volante-obsolete,ingted/volante,ingted/volante
csharp/src/PatriciaTrie.cs
csharp/src/PatriciaTrie.cs
using System; using System.Collections; using System.Collections.Generic; namespace NachoDB { /// <summary> /// PATRICIA trie (Practical Algorithm To Retrieve Information Coded In Alphanumeric). /// Tries are a kind of tree where each node holds a common part of one or more keys. /// PATRICIA trie is one of the many existing variants of the trie, which adds path compression /// by grouping common sequences of nodes together. /// This structure provides a very efficient way of storing values while maintaining the lookup time /// for a key in O(N) in the worst case, where N is the length of the longest key. /// This structure has it's main use in IP routing software, but can provide an interesting alternative /// to other structures such as hashtables when memory space is of concern. /// </summary> public interface PatriciaTrie<T> : IPersistent, IResource, ICollection<T> where T:class,IPersistent { /// <summary> /// Add new key to the trie /// </summary> /// <param name="key">bit vector</param> /// <param name="obj">persistent object associated with this key</param> /// <returns>previous object associtated with this key or <code>null</code> if there /// was no such object</returns> T Add(PatriciaTrieKey key, T obj); /// <summary> /// Find best match with specified key /// </summary> /// <param name="key">bit vector</param> /// <returns>object associated with this deepest possible match with specified key</returns> T FindBestMatch(PatriciaTrieKey key); /// <summary> /// Find exact match with specified key /// </summary> /// <param name="key">bit vector</param> /// <returns>object associated with this key or NULL if match is not found</returns> T FindExactMatch(PatriciaTrieKey key); /// <summary> /// Removes key from the triesKFind exact match with specified key /// </summary> /// <param name="key">bit vector</param> /// <returns>object associated with removed key or <code>null</code> if such key is not found</returns> T Remove(PatriciaTrieKey key); } }
using System; #if USE_GENERICS using System.Collections.Generic; #else using System.Collections; #endif namespace NachoDB { /// <summary> /// PATRICIA trie (Practical Algorithm To Retrieve Information Coded In Alphanumeric). /// Tries are a kind of tree where each node holds a common part of one or more keys. /// PATRICIA trie is one of the many existing variants of the trie, which adds path compression /// by grouping common sequences of nodes together. /// This structure provides a very efficient way of storing values while maintaining the lookup time /// for a key in O(N) in the worst case, where N is the length of the longest key. /// This structure has it's main use in IP routing software, but can provide an interesting alternative /// to other structures such as hashtables when memory space is of concern. /// </summary> #if USE_GENERICS public interface PatriciaTrie<T> : IPersistent, IResource, ICollection<T> where T:class,IPersistent #else public interface PatriciaTrie : IPersistent, IResource, ICollection #endif { /// <summary> /// Add new key to the trie /// </summary> /// <param name="key">bit vector</param> /// <param name="obj">persistent object associated with this key</param> /// <returns>previous object associtated with this key or <code>null</code> if there /// was no such object</returns> #if USE_GENERICS T Add(PatriciaTrieKey key, T obj); #else IPersistent Add(PatriciaTrieKey key, IPersistent obj); #endif /// <summary> /// Find best match with specified key /// </summary> /// <param name="key">bit vector</param> /// <returns>object associated with this deepest possible match with specified key</returns> #if USE_GENERICS T FindBestMatch(PatriciaTrieKey key); #else IPersistent FindBestMatch(PatriciaTrieKey key); #endif /// <summary> /// Find exact match with specified key /// </summary> /// <param name="key">bit vector</param> /// <returns>object associated with this key or NULL if match is not found</returns> #if USE_GENERICS T FindExactMatch(PatriciaTrieKey key); #else IPersistent FindExactMatch(PatriciaTrieKey key); #endif /// <summary> /// Removes key from the triesKFind exact match with specified key /// </summary> /// <param name="key">bit vector</param> /// <returns>object associated with removed key or <code>null</code> if such key is not found</returns> #if USE_GENERICS T Remove(PatriciaTrieKey key); #else IPersistent Remove(PatriciaTrieKey key); #endif #if !USE_GENERICS /// <summary> /// Clear the trie: remove all elements from trie /// </summary> void Clear(); #endif } }
mit
C#
3358ab9f8abde79becfd4bca2a56361170aef2e1
Adjust diffcalc test expected value
2yangk23/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,2yangk23/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.9311451172608853d, "diffcalc-test")] [TestCase(1.0736587013228804d, "zero-length-sliders")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.931145117263422, "diffcalc-test")] [TestCase(1.0736587013228804d, "zero-length-sliders")] public void Test(double expected, string name) => base.Test(expected, name); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
mit
C#
c96d4ef845f878a6ac1514f935197fd0552e41ce
Change to Bootstrap buttons for Room.Index view
johanhelsing/vaskelista,johanhelsing/vaskelista
Vaskelista/Views/Room/Index.cshtml
Vaskelista/Views/Room/Index.cshtml
@model IEnumerable<Vaskelista.Models.Room> @{ ViewBag.Title = "Index"; } <h2>Romoversikt</h2> <p> <a href="@Url.Action("Index", "Task")" class="btn btn-default"><i class="fa fa-list"></i> Planlagte oppgaver</a> <a href="@Url.Action("Create")" class="btn btn-default"><i class="fa fa-plus"></i> Nytt rom</a> </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td class="vert-align"> @Html.DisplayFor(modelItem => item.Name) </td> <td class="vert-align"> <a href="@Url.Action("Edit")" class="btn btn-default btn-sm"><i class="fa fa-edit"></i> Endre</a> <a href="@Url.Action("Details")" class="btn btn-default btn-sm"><i class="fa fa-info"></i> Detaljer</a> </td> </tr> } </table>
@model IEnumerable<Vaskelista.Models.Room> @{ ViewBag.Title = "Index"; } <h2>Romoversikt</h2> <p> @Html.ActionLink("Legg til nytt rom", "Create") @Html.ActionLink("Planlagte oppgaver", "Index", "Task") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.ActionLink("Rediger", "Edit", new { id=item.RoomId }) | @Html.ActionLink("Detaljer", "Details", new { id=item.RoomId }) </td> </tr> } </table>
mit
C#
9b6da9705ffe001a0905a611ceb02a3a2531d09d
Add ISerializable implementation for NoWatchFindException
mplessis/kUtils
Kopigi.Utils/Class/NoWatchFindException.cs
Kopigi.Utils/Class/NoWatchFindException.cs
using System; using System.Runtime.Serialization; namespace Kopigi.Utils.Class { [Serializable] public class NoWatchFindException : Exception { /// <summary> /// Constructeur de l'exception /// </summary> /// <param name="label">Label de surveillance demandé</param> public NoWatchFindException(string label) : base($"No watch found for label {label}", null) { } protected NoWatchFindException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; namespace Kopigi.Utils.Class { public class NoWatchFindException : Exception { /// <summary> /// Constructeur de l'exception /// </summary> /// <param name="label">Label de surveillance demandé</param> public NoWatchFindException(string label) : base($"No watch found for label {label}", null) { } } }
mit
C#
e45df1918d1f92ff0b6bcaceac97c1d517d7b6b6
implement IExchangeRatesProvider.GetExchangeRatesHistory in cache
180254/KursyWalut
KursyWalut/Provider/ExchangeRatesCacher.cs
KursyWalut/Provider/ExchangeRatesCacher.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace KursyWalut.Provider { internal class ExchangeRatesCacher : IExchangeRatesProvider { private readonly Semaphore _lock = new Semaphore(1, 1); private readonly IExchangeRatesProvider _exchangeRatesProvider; private IList<DateTime> _availableDates; private readonly IDictionary<DateTime, IList<ExchangeRate>> _dailyExchangeRates = new Dictionary<DateTime, IList<ExchangeRate>>(); private readonly IDictionary<Tuple<Currency, DateTime, DateTime>, IList<ExchangeRate>> _exchangeRatesHistory = new Dictionary<Tuple<Currency, DateTime, DateTime>, IList<ExchangeRate>>(); public ExchangeRatesCacher(IExchangeRatesProvider exchangeRatesProvider) { _exchangeRatesProvider = exchangeRatesProvider; } public async Task<IList<DateTime>> GetAvailableDates() { _lock.WaitOne(); try { return _availableDates ?? (_availableDates = await _exchangeRatesProvider.GetAvailableDates()); } finally { _lock.Release(); } } public async Task<IList<ExchangeRate>> GetExchangeRates(DateTime day) { _lock.WaitOne(); try { if (_dailyExchangeRates.ContainsKey(day)) return _dailyExchangeRates[day]; var exchangeRates = await _exchangeRatesProvider.GetExchangeRates(day); _dailyExchangeRates.Add(day, exchangeRates); return exchangeRates; } finally { _lock.Release(); } } public async Task<IList<ExchangeRate>> GetExchangeRatesHistory( Currency currency, DateTime startDay, DateTime stopDay) { _lock.WaitOne(); try { var tuple = Tuple.Create(currency, startDay, stopDay); if (_exchangeRatesHistory.ContainsKey(tuple)) return _exchangeRatesHistory[tuple]; var exchangeRates = await _exchangeRatesProvider.GetExchangeRatesHistory(currency, startDay, stopDay); _exchangeRatesHistory.Add(tuple, exchangeRates); return exchangeRates; } finally { _lock.Release(); } } public IDisposable Subscribe(IObserver<int> observer) { return _exchangeRatesProvider.Subscribe(observer); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace KursyWalut.Provider { internal class ExchangeRatesCacher : IExchangeRatesProvider { private readonly Semaphore _lock = new Semaphore(1, 1); private readonly IExchangeRatesProvider _exchangeRatesProvider; private IList<DateTime> _availableDates; private readonly IDictionary<DateTime, IList<ExchangeRate>> _dailyExchangeRates = new Dictionary<DateTime, IList<ExchangeRate>>(); public ExchangeRatesCacher(IExchangeRatesProvider exchangeRatesProvider) { _exchangeRatesProvider = exchangeRatesProvider; } public async Task<IList<DateTime>> GetAvailableDates() { _lock.WaitOne(); if (_availableDates == null) _availableDates = await _exchangeRatesProvider.GetAvailableDates(); _lock.Release(); return _availableDates; } public async Task<IList<ExchangeRate>> GetExchangeRates(DateTime day) { _lock.WaitOne(); if (_dailyExchangeRates.ContainsKey(day)) return _dailyExchangeRates[day]; var exchangeRates = await _exchangeRatesProvider.GetExchangeRates(day); _dailyExchangeRates.Add(day, exchangeRates); _lock.Release(); return exchangeRates; } public IDisposable Subscribe(IObserver<int> observer) { return _exchangeRatesProvider.Subscribe(observer); } } }
mit
C#
84a3d9ca1f609d50b53f7878fbe327399ee21d92
Use theme default CornerRadius.
SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia
samples/ControlCatalog/ViewModels/ExpanderPageViewModel.cs
samples/ControlCatalog/ViewModels/ExpanderPageViewModel.cs
using Avalonia; using MiniMvvm; namespace ControlCatalog.ViewModels { public class ExpanderPageViewModel : ViewModelBase { private object _cornerRadius = AvaloniaProperty.UnsetValue; private bool _rounded; public object CornerRadius { get => _cornerRadius; private set => RaiseAndSetIfChanged(ref _cornerRadius, value); } public bool Rounded { get => _rounded; set { if (RaiseAndSetIfChanged(ref _rounded, value)) CornerRadius = _rounded ? new CornerRadius(25) : AvaloniaProperty.UnsetValue; } } } }
using Avalonia; using MiniMvvm; namespace ControlCatalog.ViewModels { public class ExpanderPageViewModel : ViewModelBase { private CornerRadius _cornerRadius; private bool _rounded; public CornerRadius CornerRadius { get => _cornerRadius; private set => RaiseAndSetIfChanged(ref _cornerRadius, value); } public bool Rounded { get => _rounded; set { if (RaiseAndSetIfChanged(ref _rounded, value)) CornerRadius = _rounded ? new CornerRadius(25) : default; } } } }
mit
C#
fed48eec9324cd5b542f3f21e580b719eff147be
fix review finding
os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos
Core.ApplicationServices/ItInterfaceService.cs
Core.ApplicationServices/ItInterfaceService.cs
using Core.DomainModel.ItSystem; using Core.DomainServices; using System.Linq; namespace Core.ApplicationServices { public class ItInterfaceService : IItInterfaceService { private readonly IGenericRepository<DataRow> _dataRowRepository; private readonly IGenericRepository<ItInterface> _repository; public ItInterfaceService(IGenericRepository<ItInterface> repository, IGenericRepository<DataRow> dataRowRepository) { _repository = repository; _dataRowRepository = dataRowRepository; } public void Delete(int id) { var dataRows = _dataRowRepository.Get(x => x.ItInterfaceId == id); foreach (var dataRow in dataRows) { _dataRowRepository.DeleteByKey(dataRow.Id); } _dataRowRepository.Save(); var itInterface = _repository.Get(x => x.Id == id).FirstOrDefault(); // delete it interface _repository.DeleteWithReferencePreload(itInterface); _repository.Save(); } } }
using Core.DomainModel.ItSystem; using Core.DomainServices; using System.Linq; namespace Core.ApplicationServices { public class ItInterfaceService : IItInterfaceService { private readonly IGenericRepository<DataRow> _dataRowRepository; private readonly IGenericRepository<ItInterface> _repository; public ItInterfaceService(IGenericRepository<ItInterface> repository, IGenericRepository<DataRow> dataRowRepository) { _repository = repository; _dataRowRepository = dataRowRepository; } public void Delete(int id) { var dataRows = _dataRowRepository.Get(x => x.ItInterfaceId == id); foreach (var dataRow in dataRows) { _dataRowRepository.DeleteByKey(dataRow.Id); } _dataRowRepository.Save(); var itInterface = _repository.Get(x => x.Id == id).FirstOrDefault(); // delete it interface _repository.Delete(itInterface); _repository.Save(); } } }
mpl-2.0
C#
3fee889036a322d67dec019e533e893cbf06d752
Remove redundant getters and setters
goshippo/shippo-csharp-client
Shippo/Track.cs
Shippo/Track.cs
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Track : ShippoId { [JsonProperty (PropertyName = "carrier")] private string Carrier; [JsonProperty (PropertyName = "tracking_number")] public string TrackingNumber; [JsonProperty (PropertyName = "address_from")] public ShortAddress AddressFrom; [JsonProperty (PropertyName = "address_to")] public ShortAddress AddressTo; [JsonProperty (PropertyName = "eta")] public DateTime? Eta; [JsonProperty (PropertyName = "servicelevel")] public Servicelevel Servicelevel; [JsonProperty (PropertyName = "tracking_status")] public TrackingStatus TrackingStatus; [JsonProperty (PropertyName = "tracking_history")] public List<TrackingHistory> TrackingHistory; [JsonProperty (PropertyName = "metadata")] public string Metadata; public override string ToString () { return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," + "Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier, TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus, TrackingHistory, Metadata); } } }
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Track : ShippoId { [JsonProperty (PropertyName = "carrier")] public string Carrier { get; set; } [JsonProperty (PropertyName = "tracking_number")] public string TrackingNumber { get; set; } [JsonProperty (PropertyName = "address_from")] public ShortAddress AddressFrom { get; set; } [JsonProperty (PropertyName = "address_to")] public ShortAddress AddressTo { get; set; } [JsonProperty (PropertyName = "eta")] public DateTime? Eta { get; set; } [JsonProperty (PropertyName = "servicelevel")] public Servicelevel Servicelevel { get; set; } [JsonProperty (PropertyName = "tracking_status")] public TrackingStatus TrackingStatus { get; set; } [JsonProperty (PropertyName = "tracking_history")] public List<TrackingHistory> TrackingHistory { get; set; } [JsonProperty (PropertyName = "metadata")] public string Metadata { get; set; } public override string ToString () { return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," + "Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier, TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus, TrackingHistory, Metadata); } } }
apache-2.0
C#
dd6eb541ca37c65a8be16ba01adf3ab7e2cdcbe4
Remove -beta from the InformationalVersion
GibraltarSoftware/Gibraltar.Agent.Web.Mvc
Src/Agent.Web.Mvc/Properties/AssemblyInfo.cs
Src/Agent.Web.Mvc/Properties/AssemblyInfo.cs
#region File Header and License // /* // AssemblyInfo.cs // Copyright 2013 Gibraltar Software, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // */ #endregion using System.Reflection; using System.Runtime.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("Loupe Agent for ASP.NET MVC 4")] [assembly: AssemblyDescription("Records performance, error, and tracing information for ASP.NET MVC and Web API using Loupe")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Gibraltar Software Inc.")] [assembly: AssemblyProduct("Loupe")] [assembly: AssemblyCopyright("Copyright © 2013-2014 Gibraltar Software Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("23d80f30-f21a-4ac9-8d8a-1b195ec80ed9")] // 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.8.0.0")] [assembly: AssemblyFileVersion("3.7.2.2199")] //this is synchronized with the Loupe agent version number [assembly: AssemblyInformationalVersion("3.8.0")]
#region File Header and License // /* // AssemblyInfo.cs // Copyright 2013 Gibraltar Software, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // */ #endregion using System.Reflection; using System.Runtime.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("Loupe Agent for ASP.NET MVC 4")] [assembly: AssemblyDescription("Records performance, error, and tracing information for ASP.NET MVC and Web API using Loupe")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Gibraltar Software Inc.")] [assembly: AssemblyProduct("Loupe")] [assembly: AssemblyCopyright("Copyright © 2013-2014 Gibraltar Software Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("23d80f30-f21a-4ac9-8d8a-1b195ec80ed9")] // 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.8.0.0")] [assembly: AssemblyFileVersion("3.7.2.2199")] //this is synchronized with the Loupe agent version number [assembly: AssemblyInformationalVersion("3.8.0-beta")]
apache-2.0
C#
d71b25589e6e404036a4522762b98847dac17c81
Add comments to physical props
OctoAwesome/octoawesome,OctoAwesome/octoawesome
OctoAwesome/OctoAwesome/PhysicalProperties.cs
OctoAwesome/OctoAwesome/PhysicalProperties.cs
namespace OctoAwesome { /// <summary> /// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/... /// </summary> public class PhysicalProperties { /// <summary> /// Härte, welche Materialien können abgebaut werden /// </summary> public float Hardness { get; set; } /// <summary> /// Dichte in kg/dm^3, Wie viel benötigt (Volumen berechnung) für Crafting bzw. hit result etc.... /// </summary> public float Density { get; set; } /// <summary> /// Granularität, Effiktivität von "Materialien" Schaufel für hohe Werte, Pickaxe für niedrige /// </summary> public float Granularity { get; set; } /// <summary> /// Bruchzähigkeit, Wie schnell geht etwas zu bruch? Haltbarkeit. /// </summary> public float FractureToughness { get; set; } } }
namespace OctoAwesome { /// <summary> /// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/... /// </summary> public class PhysicalProperties { /// <summary> /// Härte /// </summary> public float Hardness { get; set; } /// <summary> /// Dichte in kg/dm^3 /// </summary> public float Density { get; set; } /// <summary> /// Granularität /// </summary> public float Granularity { get; set; } /// <summary> /// Bruchzähigkeit /// </summary> public float FractureToughness { get; set; } } }
mit
C#
9b2c0eb6d00115db850b81c3bf8dfbe58eb3c15e
add property for configurable smtp timeout
brockallen/BrockAllen.MembershipReboot,DosGuru/MembershipReboot,vankooch/BrockAllen.MembershipReboot,rajendra1809/BrockAllen.MembershipReboot,rvdkooy/BrockAllen.MembershipReboot,vinneyk/BrockAllen.MembershipReboot,eric-swann-q2/BrockAllen.MembershipReboot,tomascassidy/BrockAllen.MembershipReboot
src/BrockAllen.MembershipReboot/Notification/Email/SmtpMessageDelivery.cs
src/BrockAllen.MembershipReboot/Notification/Email/SmtpMessageDelivery.cs
/* * Copyright (c) Brock Allen. All rights reserved. * see license.txt */ using System; using System.Configuration; using System.Net.Configuration; using System.Net.Mail; namespace BrockAllen.MembershipReboot { public class SmtpMessageDelivery : IMessageDelivery { public bool SendAsHtml { get; set; } public int SmtpTimeout { get; set; } public SmtpMessageDelivery(bool sendAsHtml = false, int smtpTimeout = 5000) { this.SendAsHtml = sendAsHtml; this.SmtpTimeout = smtpTimeout; } public void Send(Message msg) { Tracing.Information("[SmtpMessageDelivery.Send] sending mail to " + msg.To); if (String.IsNullOrWhiteSpace(msg.From)) { SmtpSection smtp = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; msg.From = smtp.From; } using (SmtpClient smtp = new SmtpClient()) { smtp.Timeout = SmtpTimeout; try { MailMessage mailMessage = new MailMessage(msg.From, msg.To, msg.Subject, msg.Body) { IsBodyHtml = SendAsHtml }; smtp.Send(mailMessage); } catch (SmtpException e) { Tracing.Error("[SmtpMessageDelivery.Send] SmtpException: " + e.Message); } catch (Exception e) { Tracing.Error("[SmtpMessageDelivery.Send] Exception: " + e.Message); } } } } }
/* * Copyright (c) Brock Allen. All rights reserved. * see license.txt */ using System; using System.Configuration; using System.Net.Configuration; using System.Net.Mail; namespace BrockAllen.MembershipReboot { public class SmtpMessageDelivery : IMessageDelivery { private readonly bool sendAsHtml; public SmtpMessageDelivery(bool sendAsHtml = false) { this.sendAsHtml = sendAsHtml; } public void Send(Message msg) { Tracing.Information("[SmtpMessageDelivery.Send] sending mail to " + msg.To); if (String.IsNullOrWhiteSpace(msg.From)) { SmtpSection smtp = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; msg.From = smtp.From; } using (SmtpClient smtp = new SmtpClient()) { smtp.Timeout = 5000; try { MailMessage mailMessage = new MailMessage(msg.From, msg.To, msg.Subject, msg.Body) { IsBodyHtml = sendAsHtml }; smtp.Send(mailMessage); } catch (SmtpException e) { Tracing.Error("[SmtpMessageDelivery.Send] SmtpException: " + e.Message); } catch (Exception e) { Tracing.Error("[SmtpMessageDelivery.Send] Exception: " + e.Message); } } } } }
bsd-3-clause
C#
e5863da40fe1da74d97399e68be56dadc2f6a667
Make CsvBackend google compatible
joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net
JoinRpg.Services.Export/BackEnds/CsvBackend.cs
JoinRpg.Services.Export/BackEnds/CsvBackend.cs
using System.Collections.Generic; using System.Linq; using System.Text; using JoinRpg.Services.Export.Internal; namespace JoinRpg.Services.Export.BackEnds { internal class CsvBackend : IGeneratorBackend { private StringBuilder Builder { get; }= new StringBuilder(); public string ContentType => "text/csv"; public string FileExtension => "csv"; public void WriteRow(IEnumerable<Cell> cells) => Builder.AppendLine(string.Join(",", cells.Select(GetContentForCsv))); private static string GetContentForCsv(Cell c) => "\"" + c.Content.Replace("\"", "\"\"") + "\""; public byte[] Generate() => Encoding.UTF8.GetBytes(Builder.ToString()); } }
using System.Collections.Generic; using System.Linq; using System.Text; using JoinRpg.Services.Export.Internal; namespace JoinRpg.Services.Export.BackEnds { internal class CsvBackend : IGeneratorBackend { private StringBuilder Builder { get; }= new StringBuilder(); public string ContentType => "text/csv"; public string FileExtension => "csv"; public void WriteRow(IEnumerable<Cell> cells) => Builder.AppendLine(string.Join(";", cells.Select(GetContentForCsv))); private static string GetContentForCsv(Cell c) => "\"" + c.Content.Replace("\"", "\"\"") + "\""; public byte[] Generate() => Encoding.UTF8.GetBytes(Builder.ToString()); } }
mit
C#
582ff0d10c65c4855695e2cbe4af7cba7fcef269
Remove JsonProperty's on RepositoryInfo to avoid breaking change
projectkudu/kudu,kali786516/kudu,sitereactor/kudu,duncansmart/kudu,mauricionr/kudu,uQr/kudu,mauricionr/kudu,uQr/kudu,EricSten-MSFT/kudu,YOTOV-LIMITED/kudu,juoni/kudu,shibayan/kudu,bbauya/kudu,puneet-gupta/kudu,projectkudu/kudu,kenegozi/kudu,dev-enthusiast/kudu,juvchan/kudu,shrimpy/kudu,shrimpy/kudu,puneet-gupta/kudu,MavenRain/kudu,puneet-gupta/kudu,YOTOV-LIMITED/kudu,barnyp/kudu,kenegozi/kudu,puneet-gupta/kudu,mauricionr/kudu,shibayan/kudu,YOTOV-LIMITED/kudu,juvchan/kudu,oliver-feng/kudu,uQr/kudu,shrimpy/kudu,chrisrpatterson/kudu,sitereactor/kudu,duncansmart/kudu,sitereactor/kudu,bbauya/kudu,juvchan/kudu,barnyp/kudu,MavenRain/kudu,juvchan/kudu,sitereactor/kudu,EricSten-MSFT/kudu,shrimpy/kudu,kali786516/kudu,shibayan/kudu,badescuga/kudu,shibayan/kudu,dev-enthusiast/kudu,EricSten-MSFT/kudu,oliver-feng/kudu,projectkudu/kudu,juvchan/kudu,oliver-feng/kudu,kenegozi/kudu,juoni/kudu,MavenRain/kudu,dev-enthusiast/kudu,chrisrpatterson/kudu,chrisrpatterson/kudu,kali786516/kudu,badescuga/kudu,kali786516/kudu,oliver-feng/kudu,badescuga/kudu,duncansmart/kudu,YOTOV-LIMITED/kudu,dev-enthusiast/kudu,sitereactor/kudu,kenegozi/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,juoni/kudu,uQr/kudu,chrisrpatterson/kudu,badescuga/kudu,badescuga/kudu,bbauya/kudu,barnyp/kudu,puneet-gupta/kudu,shibayan/kudu,barnyp/kudu,projectkudu/kudu,juoni/kudu,mauricionr/kudu,MavenRain/kudu,duncansmart/kudu,projectkudu/kudu,bbauya/kudu
Kudu.Contracts/SourceControl/RepositoryInfo.cs
Kudu.Contracts/SourceControl/RepositoryInfo.cs
using System; using Newtonsoft.Json; namespace Kudu.Core.SourceControl { public class RepositoryInfo { // Omitting the JsonProperty's to avoid a breaking change. We previously had [DataMember] attribs // but they were not working because there was no [DataContract] on the class //[JsonProperty(PropertyName = "repository_type")] public RepositoryType Type { get; set; } //[JsonProperty(PropertyName = "git_url")] public Uri GitUrl { get; set; } } }
using System; using Newtonsoft.Json; namespace Kudu.Core.SourceControl { public class RepositoryInfo { [JsonProperty(PropertyName = "repository_type")] public RepositoryType Type { get; set; } [JsonProperty(PropertyName = "git_url")] public Uri GitUrl { get; set; } } }
apache-2.0
C#
b69ee8c0db123d00f351a13572987b76228b1edc
add logging
farihan/NorthwindAngular4,farihan/NorthwindAngular4,farihan/NorthwindAngular4,farihan/NorthwindAngular4
NorthwindAngular4/NorthwindAngular4/Startup.cs
NorthwindAngular4/NorthwindAngular4/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.Webpack; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NorthwindAngular4.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace NorthwindAngular4 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DatabaseConnection"])); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.Webpack; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NorthwindAngular4.Data; using Microsoft.EntityFrameworkCore; namespace NorthwindAngular4 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DatabaseConnection"])); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); } } }
mit
C#
577d80ffc4b52919e4062690efe78e4cd1f346b6
Fix control property visibility
roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon
R7.Epsilon/Skins/Controls/JsVariables.ascx.cs
R7.Epsilon/Skins/Controls/JsVariables.ascx.cs
// // JsVariables.ascx.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using DotNetNuke.Entities.Tabs; namespace R7.Epsilon { public class JsVariables: EpsilonSkinObjectBase { #region Control properties private bool breadCrumbsRemoveLastLink = true; public bool BreadCrumbsRemoveLastLink { get { return breadCrumbsRemoveLastLink; } set { breadCrumbsRemoveLastLink = value; } } #endregion #region Bindable properties protected string JsBreadCrumbsRemoveLastLink { get { return breadCrumbsRemoveLastLink.ToString ().ToLowerInvariant (); } } protected string JsBreadCrumbsList { get { return "[" + Utils.FormatList (",", PortalSettings.ActiveTab.BreadCrumbs .ToArray ().Select (b => ((TabInfo) b).TabID)) + "]"; } } #endregion } }
// // JsVariables.ascx.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using DotNetNuke.Entities.Tabs; namespace R7.Epsilon { public class JsVariables: EpsilonSkinObjectBase { #region Control properties private bool breadCrumbsRemoveLastLink = true; protected bool BreadCrumbsRemoveLastLink { get { return breadCrumbsRemoveLastLink; } set { breadCrumbsRemoveLastLink = value; } } #endregion #region Bindable properties protected string JsBreadCrumbsRemoveLastLink { get { return breadCrumbsRemoveLastLink.ToString ().ToLowerInvariant (); } } protected string JsBreadCrumbsList { get { return "[" + Utils.FormatList (",", PortalSettings.ActiveTab.BreadCrumbs .ToArray ().Select (b => ((TabInfo) b).TabID)) + "]"; } } #endregion } }
agpl-3.0
C#
f85f792874ab43f9b82261896c48d488c914b777
Update docs
JudahGabriel/RavenDB.Identity
RavenDB.Identity/IdentityBuilderExtensions.cs
RavenDB.Identity/IdentityBuilderExtensions.cs
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Raven.Client; using Raven.Client.Documents; using Raven.Client.Documents.Session; using System; namespace Raven.Identity { /// <summary> /// Extends <see cref="IdentityBuilder"/> so that RavenDB services can be registered through it. /// </summary> public static class IdentityBuilderExtensions { /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser>(this IdentityBuilder builder) where TUser : IdentityUser { return builder.AddRavenDbIdentityStores<TUser, IdentityRole>(c => { }); } /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <param name="builder">The builder.</param> /// <param name="configure">Configure options for Raven Identity</param> /// <returns></returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser>(this IdentityBuilder builder, Action<RavenIdentityOptions> configure) where TUser : IdentityUser { return builder.AddRavenDbIdentityStores<TUser, IdentityRole>(configure); } /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <typeparam name="TRole">The type of the role.</typeparam> /// <param name="builder">The builder.</param> /// <returns>The builder.</returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser, TRole>(this IdentityBuilder builder) where TUser : IdentityUser where TRole : IdentityRole, new() { return builder.AddRavenDbIdentityStores<TUser, TRole>(c => { }); } /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <typeparam name="TRole">The type of the role.</typeparam> /// <param name="builder">The builder.</param> /// <param name="configure">Configure options for Raven Identity</param> /// <returns>The builder.</returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser, TRole>(this IdentityBuilder builder, Action<RavenIdentityOptions> configure) where TUser : IdentityUser where TRole : IdentityRole, new() { builder.Services.Configure(configure); builder.Services.AddScoped<IUserStore<TUser>, UserStore<TUser, TRole>>(); builder.Services.AddScoped<IRoleStore<TRole>, RoleStore<TRole>>(); return builder; } } }
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Raven.Client; using Raven.Client.Documents; using Raven.Client.Documents.Session; using System; namespace Raven.Identity { /// <summary> /// Extends <see cref="IdentityBuilder"/> so that RavenDB services can be registered through it. /// </summary> public static class IdentityBuilderExtensions { /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser>(this IdentityBuilder builder) where TUser : IdentityUser { return builder.AddRavenDbIdentityStores<TUser, IdentityRole>(c => { }); } /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <param name="builder">The builder.</param> /// <param name="configure">Configure options for Raven Identity</param> /// <returns></returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser>(this IdentityBuilder builder, Action<RavenIdentityOptions> configure) where TUser : IdentityUser { return builder.AddRavenDbIdentityStores<TUser, IdentityRole>(configure); } /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <typeparam name="TRole">The type of the role.</typeparam> /// <param name="builder">The builder.</param> /// <param name="configure">Configure options for Raven Identity</param> /// <returns>The builder.</returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser, TRole>(this IdentityBuilder builder) where TUser : IdentityUser where TRole : IdentityRole, new() { return builder.AddRavenDbIdentityStores<TUser, TRole>(c => { }); } /// <summary> /// Registers a RavenDB as the user store. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <typeparam name="TRole">The type of the role.</typeparam> /// <param name="builder">The builder.</param> /// <param name="configure">Configure options for Raven Identity</param> /// <returns>The builder.</returns> public static IdentityBuilder AddRavenDbIdentityStores<TUser, TRole>(this IdentityBuilder builder, Action<RavenIdentityOptions> configure) where TUser : IdentityUser where TRole : IdentityRole, new() { builder.Services.Configure(configure); builder.Services.AddScoped<IUserStore<TUser>, UserStore<TUser, TRole>>(); builder.Services.AddScoped<IRoleStore<TRole>, RoleStore<TRole>>(); return builder; } } }
mit
C#
650ad9414a5a9f5bcfc3cc2f456fedef69115926
Fix beer
RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast
RightpointLabs.Pourcast.Domain/Models/Beer.cs
RightpointLabs.Pourcast.Domain/Models/Beer.cs
namespace RightpointLabs.Pourcast.Domain.Models { using RightpointLabs.Pourcast.Domain.Events; public class Beer : Entity { private Beer() { } public Beer(string id, string name) : base(id) { Name = name; DomainEvents.Raise(new BeerCreated(id)); } public string Name { get; set; } public string BreweryId { get; set; } public double ABV { get; set; } public double BAScore { get; set; } public double RPScore { get; set; } public string StyleId { get; set; } public string Color { get; set; } public string Glass { get; set; } public string Style { get; set; } } }
namespace RightpointLabs.Pourcast.Domain.Models { using RightpointLabs.Pourcast.Domain.Events; public class Beer : Entity { private Beer() { } public Beer(string id, string name) : base(id) { Name = name; DomainEvents.Raise(new BeerCreated(id)); } public string Name { get; set; } public string BreweryId { get; set; } public double ABV { get; set; } public double BAScore { get; set; } public double RPScore { get; set; } public string StyleId { get; set; } } }
mit
C#
44611b8f3bfbdadc08a25616811bd7032c9d168d
Fix Instructions
redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team,redcanaryco/atomic-red-team
Windows/Payloads/AppCompatShims/AtomicTest.cs
Windows/Payloads/AppCompatShims/AtomicTest.cs
using System; /* mkdir C:\Tools copy AtomicTest.Dll C:\Tools\AtomicTest.dll C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /platform:x86 AtomicTest.cs From Elevated Prompt sdbinst.exe AtomicShimx86.sdb AtomicTest.exe sdbinst -u AtomicShimx86.sdb */ public class AtomicTest { public static void Main() { Console.WriteLine("Boom!"); } public static bool Thing() { Console.WriteLine("Things!"); return true; } }
using System; // C:\Users\subTee\Downloads\Shims>c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /platform:x86 AtomicTest.cs // From Elevated Prompt // sdbinst.exe AtomicShim.sdb public class AtomicTest { public static void Main() { Console.WriteLine("Boom!"); } public static bool Thing() { Console.WriteLine("Things!"); return true; } }
mit
C#
1a165eff27e33295750f1d365dcfc1189c5e03d9
Update "Shelf"
DRFP/Personal-Library
_Build/PersonalLibrary/Library/Model/Shelf.cs
_Build/PersonalLibrary/Library/Model/Shelf.cs
using SQLite; namespace Library.Model { [Table("Shelves")] public class Shelf { [PrimaryKey, AutoIncrement] public int slfID { get; set; } public string slfName { get; set; } } }
using SQLite; namespace Library.Model { [Table("Shelves")] public class Shelf { [PrimaryKey, AutoIncrement] public int slfID { get; set; } public string slfName { get; set; } public string slfDescription { get; set; } } }
mit
C#
06650dea0cc679b748989b0e3d30bac2b733fee3
Support other company main currencies than euro #23
aukolov/Spinvoice
src/QuickBooks/Spinvoice.QuickBooks/ExchangeRate/ExternalExchangeRatesRepository.cs
src/QuickBooks/Spinvoice.QuickBooks/ExchangeRate/ExternalExchangeRatesRepository.cs
using System; using NLog; using Spinvoice.Domain.Exchange; using Spinvoice.QuickBooks.Connection; namespace Spinvoice.QuickBooks.ExchangeRate { public class ExternalExchangeRatesRepository : IExchangeRatesRepository { private readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly ExternalConnection _externalConnection; public ExternalExchangeRatesRepository(ExternalConnection externalConnection) { _externalConnection = externalConnection; } public decimal? GetRate(string currency, DateTime date) { if (!_externalConnection.IsConnected) { return null; } Intuit.Ipp.Data.ExchangeRate exchangeRate; try { exchangeRate = _externalConnection.GetExchangeRate(date, currency); } catch (Exception e) { _logger.Error(e, "Error while loading exchange rates"); return null; } if (exchangeRate == null) { return null; } if (!exchangeRate.RateSpecified) { return null; } return exchangeRate.Rate; } } }
using System; using NLog; using Spinvoice.Domain.Exchange; using Spinvoice.QuickBooks.Connection; namespace Spinvoice.QuickBooks.ExchangeRate { public class ExternalExchangeRatesRepository : IExchangeRatesRepository { private readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly ExternalConnection _externalConnection; public ExternalExchangeRatesRepository(ExternalConnection externalConnection) { _externalConnection = externalConnection; } public decimal? GetRate(string currency, DateTime date) { if (currency == "EUR") { return 1; } if (!_externalConnection.IsConnected) { return null; } Intuit.Ipp.Data.ExchangeRate exchangeRate; try { exchangeRate = _externalConnection.GetExchangeRate(date, currency); } catch (Exception e) { _logger.Error(e, "Error while loading exchange rates"); return null; } if (exchangeRate == null) { return null; } if (!exchangeRate.RateSpecified) { return null; } return exchangeRate.Rate; } } }
unlicense
C#
b965a31c6395646ac80cb34db3da49464a28c7de
Update version
gahcep/App.Refoveo
App.Refoveo/Properties/GlobalAssemblyInfo.cs
App.Refoveo/Properties/GlobalAssemblyInfo.cs
using System.Reflection; /* General Product Information */ [assembly: AssemblyProduct("App.Refoveo")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] /* Configuration Type */ #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif /* Assembly Versioning: mixture of MSDN and SemVer approaches * MSDN Versioning: http://msdn.microsoft.com/en-us/library/51ket42z%28v=vs.110%29.aspx * SemVer: http://semver.org/spec/v2.0.0.html * * Format: Major.Minor.Patch-ReleaseType.BuildNum * - Major - for incompatible API changes (big changes) * - Minor - for adding functionality in a backwards-compatible manner (small changes) * - Patch - for bugfixes (increments only for "bugfix/" branch) * - ReleaseType - additional information: either * -- "pre-alpha" - active phase on docs creation and specifications ("dev" branch) * -- "alpha" - active development and adding new features ("dev" branch) * -- "beta" - feature-freeze (feature-complete), active bugfixes ("staging-qa" branch) * -- "rc" - stabilizing code: only very critical issues are to be resolved ("staging-qa" branch) * -- "release" - release in production ("release" branch) * -- "release.hotfix" - rapid bugfix for release ("hotfix" branch) * * AssemblyVersion - defines a version for the product itself * -- format: Major.Minor.0 * AssemblyFileVersion - defines a version for particular assembly * -- format: Major.Minor.Patch * AssemblyInformationalVersion - defines detailed version for the product and assemblies * -- format: Major.Minor.Patch-ReleaseType.BuildNumber * * {develop} branch contains ONLY alpha version */ [assembly: AssemblyVersion("0.6.0")] [assembly: AssemblyFileVersion("0.6.0")] [assembly: AssemblyInformationalVersion("0.6.0-alpha.7")]
using System.Reflection; /* General Product Information */ [assembly: AssemblyProduct("App.Refoveo")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] /* Configuration Type */ #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif /* Assembly Versioning: mixture of MSDN and SemVer approaches * MSDN Versioning: http://msdn.microsoft.com/en-us/library/51ket42z%28v=vs.110%29.aspx * SemVer: http://semver.org/spec/v2.0.0.html * * Format: Major.Minor.Patch-ReleaseType.BuildNum * - Major - for incompatible API changes (big changes) * - Minor - for adding functionality in a backwards-compatible manner (small changes) * - Patch - for bugfixes (increments only for "bugfix/" branch) * - ReleaseType - additional information: either * -- "pre-alpha" - active phase on docs creation and specifications ("dev" branch) * -- "alpha" - active development and adding new features ("dev" branch) * -- "beta" - feature-freeze (feature-complete), active bugfixes ("staging-qa" branch) * -- "rc" - stabilizing code: only very critical issues are to be resolved ("staging-qa" branch) * -- "release" - release in production ("release" branch) * -- "release.hotfix" - rapid bugfix for release ("hotfix" branch) * * AssemblyVersion - defines a version for the product itself * -- format: Major.Minor.0 * AssemblyFileVersion - defines a version for particular assembly * -- format: Major.Minor.Patch * AssemblyInformationalVersion - defines detailed version for the product and assemblies * -- format: Major.Minor.Patch-ReleaseType.BuildNumber * * {develop} branch contains ONLY alpha version */ [assembly: AssemblyVersion("0.5.0")] [assembly: AssemblyFileVersion("0.5.0")] [assembly: AssemblyInformationalVersion("0.5.0-alpha.6")]
mit
C#
ea46ca84f22498b54fd8486f957cf8a1a1b9f0e0
Remove spaces
DaveSenn/Extend
PortableExtensions/Properties/AssemblyInfo.cs
PortableExtensions/Properties/AssemblyInfo.cs
#region Usings using System.Reflection; using System.Resources; #endregion [assembly: AssemblyTitle("PortableExtensions")] [assembly: AssemblyDescription( "PortableExtensions is a set of .Net extension methods build as portable class library. " + "PortableExtensions enhance the .Net framework by adding a bunch of methods to increase developer’s productivity.")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("Dave Senn")] [assembly: AssemblyProduct("PortableExtensions")] [assembly: AssemblyCopyright("Copyright © Dave Senn 2015")] [assembly: AssemblyTrademark("PortableExtensions")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("1.1.4.0")] [assembly: AssemblyFileVersion("1.1.4.0")]
#region Usings using System.Reflection; using System.Resources; #endregion [assembly: AssemblyTitle( "PortableExtensions" )] [assembly: AssemblyDescription( "PortableExtensions is a set of .Net extension methods build as portable class library. " + "PortableExtensions enhance the .Net framework by adding a bunch of methods to increase developer’s productivity." )] #if DEBUG [assembly: AssemblyConfiguration( "Debug" )] #else [assembly: AssemblyConfiguration( "Release" )] #endif [assembly: AssemblyCompany( "Dave Senn" )] [assembly: AssemblyProduct( "PortableExtensions" )] [assembly: AssemblyCopyright( "Copyright © Dave Senn 2015" )] [assembly: AssemblyTrademark( "PortableExtensions" )] [assembly: AssemblyCulture( "" )] [assembly: NeutralResourcesLanguage( "en" )] [assembly: AssemblyVersion( "1.1.4.0" )] [assembly: AssemblyFileVersion( "1.1.4.0" )]
mit
C#
9e44d936b56d9f13a5aa65595d0e7cb46f10b287
Update AssemblyInfo.cs
remember664/Sitecore.RestSharp,remember664/Sitecore.RestSharp
Sitecore.RestSharp/Properties/AssemblyInfo.cs
Sitecore.RestSharp/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("Sitecore.RestSharp")] [assembly: AssemblyDescription("Sitecore mapper for RestSharp. GitHub: https://github.com/remember664/Sitecore.RestSharp")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sitecore.RestSharp")] [assembly: AssemblyCopyright("Copyright © Sergey Oleynik 2013")] [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("aae20721-04af-475d-8207-8f9efb4b7f2c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("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("Sitecore.RestSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sitecore.RestSharp")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("aae20721-04af-475d-8207-8f9efb4b7f2c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
6f5ec1ddda490c8ad80c2c8b1e9f93271d0c306a
fix QueryController
AlejandroCano/framework,avifatal/framework,signumsoftware/framework,AlejandroCano/framework,avifatal/framework,signumsoftware/framework
Signum.React/ApiControllers/QueryController.cs
Signum.React/ApiControllers/QueryController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Entities.DynamicQuery; namespace Signum.React.ApiControllers { public class QueryController : ApiController { [Route("api/query/description/{queryName}")] public QueryDescription GetQuery(string queryName) { var qn = QueryLogic.ToQueryName(queryName); return DynamicQueryManager.Current.QueryDescription(qn); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Entities.DynamicQuery; namespace Signum.React.ApiControllers { public class QueryController : ApiController { [Route("api/query/description/{queryName}")] public QueryDescription GetQuery(string queryName) { var qn = QueryLogic.TryToQueryName(queryName); return DynamicQueryManager.Current.QueryDescription(qn); } } }
mit
C#
23bba00d9a710d3891153bb8a8baff700a29fae0
Add `EdgeList`
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/OpenGl/IRenderable.cs
SolidworksAddinFramework/OpenGl/IRenderable.cs
using System; using System.Collections.Generic; using System.DoubleNumerics; using System.Drawing; using System.Linq; using LanguageExt; using SolidWorks.Interop.sldworks; using OpenTK.Graphics.OpenGL; using SolidworksAddinFramework.Geometry; namespace SolidworksAddinFramework.OpenGl { public interface IRenderable { void Render(DateTime time); void ApplyTransform(Matrix4x4 transform); Tuple<Vector3, double> BoundingSphere { get; } } public class EdgeList : IRenderable { private readonly Color _Color; private readonly IReadOnlyList<Edge3> _Edges; public EdgeList(IEnumerable<Edge3> edges, Color color) { _Color = color; _Edges = edges.ToList(); } public void Render(DateTime time) { using (ModernOpenGl.SetColor(_Color, ShadingModel.Smooth, solidBody: false)) using (ModernOpenGl.SetLineWidth(2.0)) using (ModernOpenGl.Begin(PrimitiveType.Lines)) foreach (var v in _Edges) { v.A.GLVertex3(); v.B.GLVertex3(); } } public void ApplyTransform(Matrix4x4 transform) { throw new NotImplementedException(); } public Tuple<Vector3, double> BoundingSphere { get { throw new NotImplementedException(); } } } public static class Renderable { public static Tuple<Vector3,double> BoundingSphere(IReadOnlyList<Vector3> points) { var range = Range3Single.FromVertices(points); return range.BoundingSphere(); } } }
using System; using System.Collections.Generic; using System.DoubleNumerics; using LanguageExt; using SolidWorks.Interop.sldworks; using OpenTK.Graphics.OpenGL; using SolidworksAddinFramework.Geometry; namespace SolidworksAddinFramework.OpenGl { public interface IRenderable { void Render(DateTime time); void ApplyTransform(Matrix4x4 transform); Tuple<Vector3, double> BoundingSphere { get; } } public static class Renderable { public static Tuple<Vector3,double> BoundingSphere(IReadOnlyList<Vector3> points) { var range = Range3Single.FromVertices(points); return range.BoundingSphere(); } } }
mit
C#
0133e07ff3b25ad48d411e78a38e23439bf38084
Add unit test for Quaternion.Chain
virtuallynaked/virtually-naked,virtuallynaked/virtually-naked
UnitTests/src/math/QuaternionExtensionsTest.cs
UnitTests/src/math/QuaternionExtensionsTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpDX; [TestClass] public class QuaternionExtensionsTest { [TestMethod] public void TestDecomposeIntoSwingThenTwistAlongX() { Quaternion q = Quaternion.RotationYawPitchRoll(0.1f, 0.2f, 0.3f); q.DecomposeIntoTwistThenSwing(Vector3.UnitX, out Quaternion twist, out Quaternion swing); //check that twist only has X component Assert.AreEqual(0, twist.Y); Assert.AreEqual(0, twist.Z); //check that swing has no X component Assert.AreEqual(0, swing.X); //check that swing-then-twist is equivalent to original rotation Quaternion swingThenTwist = twist.Chain(swing); Assert.AreEqual(swingThenTwist, q); } [TestMethod] public void TestDecomposeIntoSwingThenTwistAlongY() { Quaternion q = Quaternion.RotationYawPitchRoll(0.1f, 0.2f, 0.3f); q.DecomposeIntoTwistThenSwing(Vector3.UnitY, out Quaternion twist, out Quaternion swing); //check that twist only has Y component Assert.AreEqual(0, twist.X); Assert.AreEqual(0, twist.Z); //check that swing has no Y component Assert.AreEqual(0, swing.Y); //check that swing-then-twist is equivalent to original rotation Quaternion swingThenTwist = twist.Chain(swing); Assert.AreEqual(swingThenTwist, q); } [TestMethod] public void TestRotateBetween() { Vector3 v1 = new Vector3(2, 3, 4); Vector3 v2 = new Vector3(7, 6, 5); Quaternion q = QuaternionExtensions.RotateBetween(v1, v2); Assert.AreEqual( 0, Vector3.Distance( Vector3.Normalize(Vector3.Transform(v1, q)), Vector3.Normalize(v2)), 1e-6); } [TestMethod] public void TestHlslRotate() { Vector3 p = new Vector3(2, 3, 4); Quaternion q = Quaternion.RotationYawPitchRoll(0.1f, 0.2f, 0.3f); Vector3 expectedResult = Vector3.Transform(p, q); Vector3 qXYZ = new Vector3(q.X, q.Y, q.Z); Vector3 actualResult = p + 2 * Vector3.Cross(Vector3.Cross(p, qXYZ) - q.W * p, qXYZ); Assert.AreEqual( 0, Vector3.Distance( expectedResult, actualResult), 1e-6); } [TestMethod] public void TestChain() { Quaternion q1 = Quaternion.RotationYawPitchRoll(0.1f, 0.2f, 0.3f); Quaternion q2 = Quaternion.RotationYawPitchRoll(0.2f, -0.3f, 0.4f); Quaternion q12 = q1.Chain(q2); Assert.AreEqual(1, q12.Length(), 1e-4, "chained result is normalized"); Vector3 v = new Vector3(3, 4, 5); var expected = Vector3.Transform(Vector3.Transform(v, q1), q2); var actual = Vector3.Transform(v, q1.Chain(q2)); Assert.AreEqual(0, Vector3.Distance(expected, actual), 1e-4); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpDX; [TestClass] public class QuaternionExtensionsTest { [TestMethod] public void TestDecomposeIntoSwingThenTwistAlongX() { Quaternion q = Quaternion.RotationYawPitchRoll(0.1f, 0.2f, 0.3f); q.DecomposeIntoTwistThenSwing(Vector3.UnitX, out Quaternion twist, out Quaternion swing); //check that twist only has X component Assert.AreEqual(0, twist.Y); Assert.AreEqual(0, twist.Z); //check that swing has no X component Assert.AreEqual(0, swing.X); //check that swing-then-twist is equivalent to original rotation Quaternion swingThenTwist = twist.Chain(swing); Assert.AreEqual(swingThenTwist, q); } [TestMethod] public void TestDecomposeIntoSwingThenTwistAlongY() { Quaternion q = Quaternion.RotationYawPitchRoll(0.1f, 0.2f, 0.3f); q.DecomposeIntoTwistThenSwing(Vector3.UnitY, out Quaternion twist, out Quaternion swing); //check that twist only has Y component Assert.AreEqual(0, twist.X); Assert.AreEqual(0, twist.Z); //check that swing has no Y component Assert.AreEqual(0, swing.Y); //check that swing-then-twist is equivalent to original rotation Quaternion swingThenTwist = twist.Chain(swing); Assert.AreEqual(swingThenTwist, q); } [TestMethod] public void TestRotateBetween() { Vector3 v1 = new Vector3(2, 3, 4); Vector3 v2 = new Vector3(7, 6, 5); Quaternion q = QuaternionExtensions.RotateBetween(v1, v2); Assert.AreEqual( 0, Vector3.Distance( Vector3.Normalize(Vector3.Transform(v1, q)), Vector3.Normalize(v2)), 1e-6); } [TestMethod] public void TestHlslRotate() { Vector3 p = new Vector3(2, 3, 4); Quaternion q = Quaternion.RotationYawPitchRoll(0.1f, 0.2f, 0.3f); Vector3 expectedResult = Vector3.Transform(p, q); Vector3 qXYZ = new Vector3(q.X, q.Y, q.Z); Vector3 actualResult = p + 2 * Vector3.Cross(Vector3.Cross(p, qXYZ) - q.W * p, qXYZ); Assert.AreEqual( 0, Vector3.Distance( expectedResult, actualResult), 1e-6); } }
mit
C#
f20e3ff31d8feb9984256416819f07a8312c57df
Fix ApproachRate setting only DEFAULT_DIFFICULTY
DrabWeb/osu,UselessToucan/osu,2yangk23/osu,johnneijzen/osu,Frontear/osuKyzer,peppy/osu,ppy/osu,Nabile-Rahmani/osu,peppy/osu-new,johnneijzen/osu,UselessToucan/osu,2yangk23/osu,DrabWeb/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,NeoAdonis/osu,DrabWeb/osu,EVAST9919/osu,NeoAdonis/osu,smoogipoo/osu,ZLima12/osu,naoey/osu,EVAST9919/osu,peppy/osu,ZLima12/osu,naoey/osu
osu.Game/Beatmaps/BeatmapDifficulty.cs
osu.Game/Beatmaps/BeatmapDifficulty.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; namespace osu.Game.Beatmaps { public class BeatmapDifficulty { /// <summary> /// The default value used for all difficulty settings except <see cref="SliderMultiplier"/> and <see cref="SliderTickRate"/>. /// </summary> public const float DEFAULT_DIFFICULTY = 5; [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [JsonIgnore] public int ID { get; set; } public float DrainRate { get; set; } = DEFAULT_DIFFICULTY; public float CircleSize { get; set; } = DEFAULT_DIFFICULTY; public float OverallDifficulty { get; set; } = DEFAULT_DIFFICULTY; private float? approachRate = null; public float ApproachRate { get { return approachRate ?? OverallDifficulty; } set { approachRate = value; } } public float SliderMultiplier { get; set; } = 1; public float SliderTickRate { get; set; } = 1; /// <summary> /// Maps a difficulty value [0, 10] to a two-piece linear range of values. /// </summary> /// <param name="difficulty">The difficulty value to be mapped.</param> /// <param name="min">Minimum of the resulting range which will be achieved by a difficulty value of 0.</param> /// <param name="mid">Midpoint of the resulting range which will be achieved by a difficulty value of 5.</param> /// <param name="max">Maximum of the resulting range which will be achieved by a difficulty value of 10.</param> /// <returns>Value to which the difficulty value maps in the specified range.</returns> public static double DifficultyRange(double difficulty, double min, double mid, double max) { if (difficulty > 5) return mid + (max - mid) * (difficulty - 5) / 5; if (difficulty < 5) return mid - (mid - min) * (5 - difficulty) / 5; return mid; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; namespace osu.Game.Beatmaps { public class BeatmapDifficulty { /// <summary> /// The default value used for all difficulty settings except <see cref="SliderMultiplier"/> and <see cref="SliderTickRate"/>. /// </summary> public const float DEFAULT_DIFFICULTY = 5; [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [JsonIgnore] public int ID { get; set; } public float DrainRate { get; set; } = DEFAULT_DIFFICULTY; public float CircleSize { get; set; } = DEFAULT_DIFFICULTY; public float OverallDifficulty { get; set; } = DEFAULT_DIFFICULTY; private float? approachRate = null; public float ApproachRate { get { return approachRate ?? OverallDifficulty; } set { approachRate = DEFAULT_DIFFICULTY; } } public float SliderMultiplier { get; set; } = 1; public float SliderTickRate { get; set; } = 1; /// <summary> /// Maps a difficulty value [0, 10] to a two-piece linear range of values. /// </summary> /// <param name="difficulty">The difficulty value to be mapped.</param> /// <param name="min">Minimum of the resulting range which will be achieved by a difficulty value of 0.</param> /// <param name="mid">Midpoint of the resulting range which will be achieved by a difficulty value of 5.</param> /// <param name="max">Maximum of the resulting range which will be achieved by a difficulty value of 10.</param> /// <returns>Value to which the difficulty value maps in the specified range.</returns> public static double DifficultyRange(double difficulty, double min, double mid, double max) { if (difficulty > 5) return mid + (max - mid) * (difficulty - 5) / 5; if (difficulty < 5) return mid - (mid - min) * (5 - difficulty) / 5; return mid; } } }
mit
C#
9062fe1935b114fd214b5d84f9319fbdb7cd2053
Fix crashes on custom skins due to extension-less file lookups
UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,johnneijzen/osu
osu.Game/Skinning/LegacySkinResourceStore.cs
osu.Game/Skinning/LegacySkinResourceStore.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using osu.Framework.IO.Stores; using osu.Game.Database; namespace osu.Game.Skinning { public class LegacySkinResourceStore<T> : IResourceStore<byte[]> where T : INamedFileInfo { private readonly IHasFiles<T> source; private readonly IResourceStore<byte[]> underlyingStore; private string getPathForFile(string filename) { if (source.Files == null) return null; var file = source.Files.Find(f => string.Equals(f.Filename, filename, StringComparison.InvariantCultureIgnoreCase)); return file?.FileInfo.StoragePath; } public LegacySkinResourceStore(IHasFiles<T> source, IResourceStore<byte[]> underlyingStore) { this.source = source; this.underlyingStore = underlyingStore; } public Stream GetStream(string name) { string path = getPathForFile(name); return path == null ? null : underlyingStore.GetStream(path); } public IEnumerable<string> GetAvailableResources() => source.Files.Select(f => f.Filename); byte[] IResourceStore<byte[]>.Get(string name) => GetAsync(name).Result; public Task<byte[]> GetAsync(string name) { string path = getPathForFile(name); return path == null ? Task.FromResult<byte[]>(null) : underlyingStore.GetAsync(path); } #region IDisposable Support private bool isDisposed; protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; } } ~LegacySkinResourceStore() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using osu.Framework.IO.Stores; using osu.Game.Database; namespace osu.Game.Skinning { public class LegacySkinResourceStore<T> : IResourceStore<byte[]> where T : INamedFileInfo { private readonly IHasFiles<T> source; private readonly IResourceStore<byte[]> underlyingStore; private string getPathForFile(string filename) { if (source.Files == null) return null; bool hasExtension = filename.Contains('.'); var file = source.Files.Find(f => string.Equals(hasExtension ? f.Filename : Path.ChangeExtension(f.Filename, null), filename, StringComparison.InvariantCultureIgnoreCase)); return file?.FileInfo.StoragePath; } public LegacySkinResourceStore(IHasFiles<T> source, IResourceStore<byte[]> underlyingStore) { this.source = source; this.underlyingStore = underlyingStore; } public Stream GetStream(string name) { string path = getPathForFile(name); return path == null ? null : underlyingStore.GetStream(path); } public IEnumerable<string> GetAvailableResources() => source.Files.Select(f => f.Filename); byte[] IResourceStore<byte[]>.Get(string name) => GetAsync(name).Result; public Task<byte[]> GetAsync(string name) { string path = getPathForFile(name); return path == null ? Task.FromResult<byte[]>(null) : underlyingStore.GetAsync(path); } #region IDisposable Support private bool isDisposed; protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; } } ~LegacySkinResourceStore() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
mit
C#
c3ec3a66b339f1a6289922586a8cd3cdff7ab9d6
Fix random generate data in url no spaces (#676)
StefH/WireMock.Net,WireMock-Net/WireMock.Net,StefH/WireMock.Net
src/WireMock.Net.OpenApiParser/Settings/WireMockOpenApiParserDynamicExampleValues.cs
src/WireMock.Net.OpenApiParser/Settings/WireMockOpenApiParserDynamicExampleValues.cs
using System; using RandomDataGenerator.FieldOptions; using RandomDataGenerator.Randomizers; namespace WireMock.Net.OpenApiParser.Settings { /// <summary> /// A class defining the random example values to use for the different types. /// </summary> public class WireMockOpenApiParserDynamicExampleValues : IWireMockOpenApiParserExampleValues { /// <inheritdoc /> public bool Boolean { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBoolean()).Generate() ?? true; } set { } } /// <inheritdoc /> public int Integer { get { return RandomizerFactory.GetRandomizer(new FieldOptionsInteger()).Generate() ?? 42; } set { } } /// <inheritdoc /> public float Float { get { return RandomizerFactory.GetRandomizer(new FieldOptionsFloat()).Generate() ?? 4.2f; } set { } } /// <inheritdoc /> public double Double { get { return RandomizerFactory.GetRandomizer(new FieldOptionsDouble()).Generate() ?? 4.2d; } set { } } /// <inheritdoc /> public Func<DateTime> Date { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow.Date; } set { } } /// <inheritdoc /> public Func<DateTime> DateTime { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow; } set { } } /// <inheritdoc /> public byte[] Bytes { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBytes()).Generate(); } set { } } /// <inheritdoc /> public object Object { get; set; } = "example-object"; /// <inheritdoc /> public string String { get { return RandomizerFactory.GetRandomizer(new FieldOptionsTextRegex { Pattern = @"^[0-9]{2}[A-Z]{5}[0-9]{2}" }).Generate() ?? "example-string"; } set { } } } }
using System; using RandomDataGenerator.FieldOptions; using RandomDataGenerator.Randomizers; namespace WireMock.Net.OpenApiParser.Settings { /// <summary> /// A class defining the random example values to use for the different types. /// </summary> public class WireMockOpenApiParserDynamicExampleValues : IWireMockOpenApiParserExampleValues { /// <inheritdoc /> public bool Boolean { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBoolean()).Generate() ?? true; } set { } } /// <inheritdoc /> public int Integer { get { return RandomizerFactory.GetRandomizer(new FieldOptionsInteger()).Generate() ?? 42; } set { } } /// <inheritdoc /> public float Float { get { return RandomizerFactory.GetRandomizer(new FieldOptionsFloat()).Generate() ?? 4.2f; } set { } } /// <inheritdoc /> public double Double { get { return RandomizerFactory.GetRandomizer(new FieldOptionsDouble()).Generate() ?? 4.2d; } set { } } /// <inheritdoc /> public Func<DateTime> Date { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow.Date; } set { } } /// <inheritdoc /> public Func<DateTime> DateTime { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow; } set { } } /// <inheritdoc /> public byte[] Bytes { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBytes()).Generate(); } set { } } /// <inheritdoc /> public object Object { get; set; } = "example-object"; /// <inheritdoc /> public string String { get { return RandomizerFactory.GetRandomizer(new FieldOptionsTextWords()).Generate() ?? "example-string"; } set { } } } }
apache-2.0
C#
fb2907e5bd43c249533640737b623d6b89dbd5be
Fix comments
dpoeschl/roslyn,davkean/roslyn,dpoeschl/roslyn,nguerrera/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,bartdesmet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,wvdd007/roslyn,VSadov/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,genlu/roslyn,jasonmalinowski/roslyn,aelij/roslyn,agocke/roslyn,ErikSchierboom/roslyn,gafter/roslyn,davkean/roslyn,abock/roslyn,diryboy/roslyn,cston/roslyn,eriawan/roslyn,abock/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,KevinRansom/roslyn,mavasani/roslyn,dotnet/roslyn,agocke/roslyn,tmat/roslyn,MichalStrehovsky/roslyn,heejaechang/roslyn,diryboy/roslyn,reaction1989/roslyn,physhi/roslyn,KirillOsenkov/roslyn,jcouv/roslyn,AlekseyTs/roslyn,MichalStrehovsky/roslyn,tannergooding/roslyn,swaroop-sridhar/roslyn,tmat/roslyn,tmat/roslyn,aelij/roslyn,DustinCampbell/roslyn,xasx/roslyn,nguerrera/roslyn,physhi/roslyn,heejaechang/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,gafter/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,reaction1989/roslyn,swaroop-sridhar/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,davkean/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn,aelij/roslyn,sharwell/roslyn,agocke/roslyn,swaroop-sridhar/roslyn,mavasani/roslyn,cston/roslyn,physhi/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,jcouv/roslyn,wvdd007/roslyn,panopticoncentral/roslyn,VSadov/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,genlu/roslyn,sharwell/roslyn,DustinCampbell/roslyn,jcouv/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,abock/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,stephentoub/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,cston/roslyn,AmadeusW/roslyn,brettfo/roslyn,tannergooding/roslyn,eriawan/roslyn,brettfo/roslyn,panopticoncentral/roslyn,dpoeschl/roslyn,dotnet/roslyn,weltkante/roslyn,AmadeusW/roslyn,xasx/roslyn,weltkante/roslyn,diryboy/roslyn,xasx/roslyn,AmadeusW/roslyn,mavasani/roslyn,heejaechang/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,VSadov/roslyn,bartdesmet/roslyn,nguerrera/roslyn,brettfo/roslyn
src/Workspaces/Core/Portable/Classification/SyntaxClassification/ISyntaxClassifier.cs
src/Workspaces/Core/Portable/Classification/SyntaxClassification/ISyntaxClassifier.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.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal interface ISyntaxClassifier { /// <summary> /// The syntax node types this classifier is able to classify /// </summary> ImmutableArray<Type> SyntaxNodeTypes { get; } /// <summary> /// The syntax token kinds this classifier is able to classify /// </summary> ImmutableArray<int> SyntaxTokenKinds { get; } /// <summary> /// This method will be called for all nodes that match the types specified by the <see cref="SyntaxNodeTypes"/> property. /// </summary> void AddClassifications(Workspace workspace, SyntaxNode node, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken); /// <summary> /// This method will be called for all tokens that match the kinds specified by the <see cref="SyntaxTokenKinds"/> property. /// </summary> void AddClassifications(Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken); } }
// 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.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal interface ISyntaxClassifier { /// <summary> /// The syntax node types this classifier is able to classify /// </summary> ImmutableArray<Type> SyntaxNodeTypes { get; } /// <summary> /// The syntax token kinds this classifier is able to classify /// </summary> ImmutableArray<int> SyntaxTokenKinds { get; } /// <summary> /// This method will be called for all nodes that match the types specified by the SyntaxNodeTypes property. /// Implementations should return null (instead of an empty enumerable) if they have no classifications for the provided node. /// </summary> void AddClassifications(Workspace workspace, SyntaxNode node, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken); /// <summary> /// This method will be called for all nodes that match the types specified by the SyntaxTokenKinds property. /// Implementations should return null (instead of an empty enumerable) if they have no classifications for the provided token. /// </summary> void AddClassifications(Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken); } }
mit
C#
bed90c57eb66a9c7665b523f39620ec9ef540116
Update GivenAnOperationIsStarted.cs
grzesiek-galezowski/component-based-test-tool
ComponentBasedTestTool/ComponentSpecification/GivenAnOperationIsStarted.cs
ComponentBasedTestTool/ComponentSpecification/GivenAnOperationIsStarted.cs
using ComponentSpecification.AutomationLayer; using TddXt.AnyRoot; using Xunit; namespace ComponentSpecification; public class GivenAnOperationIsStarted { [Fact] public void ShouldStartPluginOperation() { var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); //GIVEN context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); //THEN context.Operations.AssertWasRun(operationName11); } [Fact] public void ShouldDisplayStartedOperationAsInProgress() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); //WHEN context.StartOperation(componentName1, operationName11); //THEN context.OperationsView.AssertSelectedOperationIsDisplayedAsInProgress(); } [Fact] public void ShouldDisplayStoppedOperationAsStopped() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); //WHEN context.Operations.MakeRunningOperationStop(); context.OperationsView.AssertSelectedOperationIsDisplayedAsStopped(); } [Fact] public void ShouldDisplaySuccessfulOperationAsSuccessful() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); context.Operations.MakeRunningOperationSucceed(); context.OperationsView.AssertSelectedOperationIsDisplayedAsSuccessful(); } [Fact] public void ShouldDisplayFailedOperationAsFailed() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); var exception = Any.Exception(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); //WHEN context.Operations.MakeRunningOperationFailWith(exception); //THEN context.OperationsView.AssertSelectedOperationIsDisplayedAsFailedWith(exception); } }
using ComponentSpecification.AutomationLayer; using TddXt.AnyRoot; using Xunit; namespace ComponentSpecification; public class GivenAnOperationIsStarted { [Fact] public void ShouldStartPluginOperation() { var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); //GIVEN context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); //THEN context.Operations.AssertWasRun(operationName11); } [Fact] public void ShouldDisplayStartedOperationAsInProgress() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); //WHEN context.StartOperation(componentName1, operationName11); //THEN context.OperationsView.AssertSelectedOperationIsDisplayedAsInProgress(); } [Fact] public void ShouldDisplayStoppedOperationAsStopped() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); //WHEN context.Operations.MakeRunningOperationStop(); context.OperationsView.AssertSelectedOperationIsDisplayedAsStopped(); } [Fact] public void ShouldDisplaySuccessfulOperationAsSuccessful() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); context.Operations.MakeRunningOperationSucceed(); context.OperationsView.AssertSelectedOperationIsDisplayedAsSuccessful(); } [Fact] public void ShouldDisplayFailedOperationAsFailed() { //GIVEN var context = new ComponentBasedTestToolDriver(); var componentName1 = Any.ComponentName(); var operationName11 = Any.OperationName(); var exception = Any.Exception(); context.ComponentsSetup.Add(componentName1) .WithOperation(operationName11); context.StartApplication(); context.ComponentsView.AddInstanceOf(componentName1); context.StartOperation(componentName1, operationName11); //WHEN context.Operations.MakeRunningOperationFailWith(exception); //THEN context.OperationsView.AssertSelectedOperationIsDisplayedAsFailedWith(exception); } }
mit
C#
2d93811b924520d8d775b1defa1a00b3a61102b7
Fix typo.
cube-soft/Cube.Core,cube-soft/Cube.Core
Tests/Sources/Behaviors/CloseBehaviorTest.cs
Tests/Sources/Behaviors/CloseBehaviorTest.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using Cube.Xui.Behaviors; using NUnit.Framework; using System.Threading; using System.Windows; namespace Cube.Xui.Tests.Behaviors { /* --------------------------------------------------------------------- */ /// /// CloseBehaviorTest /// /// <summary> /// Tests for the CloseBehavior class. /// </summary> /// /* --------------------------------------------------------------------- */ [TestFixture] [Apartment(ApartmentState.STA)] class CloseBehaviorTest { #region Tests /* ----------------------------------------------------------------- */ /// /// Create /// /// <summary> /// Executes the test to create, attach, and detach method. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Create() => Assert.DoesNotThrow(() => { var vm = new MockViewModel(); var view = new Window { DataContext = vm }; var src = new CloseBehavior(); src.Attach(view); src.Detach(); }); /* ----------------------------------------------------------------- */ /// /// Create_WithoutVM /// /// <summary> /// Executes the test to create, attach, and detach method without /// any ViewModel objects. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Create_WithoutVM() => Assert.DoesNotThrow(() => { var view = new Window(); var src = new CloseBehavior(); src.Attach(view); src.Detach(); }); #endregion } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using Cube.Xui.Behaviors; using NUnit.Framework; using System.Threading; using System.Windows; namespace Cube.Xui.Tests.Behaviors { /* --------------------------------------------------------------------- */ /// /// CloseBehaviorTest /// /// <summary> /// Tests for the CloseBehavior class. /// </summary> /// /* --------------------------------------------------------------------- */ [TestFixture] [Apartment(ApartmentState.STA)] class CloseBehaviorTest { #region Tests /* ----------------------------------------------------------------- */ /// /// Create /// /// <summary> /// Executes the test to create, attach, and detach method. /// </summary> /// /* ----------------------------------------------------------------- */ public void Create() => Assert.DoesNotThrow(() => { var vm = new MockViewModel(); var view = new Window { DataContext = vm }; var src = new CloseBehavior(); src.Attach(view); src.Detach(); }); /* ----------------------------------------------------------------- */ /// /// Create_WithoutVM /// /// <summary> /// Executes the test to create, attach, and detach method without /// any ViewModel objects. /// </summary> /// /* ----------------------------------------------------------------- */ public void Create_WithoutVM() => Assert.DoesNotThrow(() => { var view = new Window(); var src = new CloseBehavior(); src.Attach(view); src.Detach(); }); #endregion } }
apache-2.0
C#
463db2c82f11d5fa96da93f021a89b6d655f5858
Fix self patching
pardeike/Harmony
Harmony/Tools/SelfPatching.cs
Harmony/Tools/SelfPatching.cs
using Harmony.ILCopying; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; namespace Harmony.Tools { internal class SelfPatching { static readonly string upgradeToLatestVersionFullName = typeof(UpgradeToLatestVersion).FullName; static int GetVersion(MethodInfo method) { var attribute = method.GetCustomAttributes(false) .Where(attr => attr.GetType().FullName == upgradeToLatestVersionFullName) .FirstOrDefault(); if (attribute == null) return -1; return Traverse.Create(attribute).Field("version").GetValue<int>(); } static string MethodKey(MethodInfo method) { return method.DeclaringType + " " + method; } static bool IsHarmonyAssembly(Assembly assembly) { try { var attribute = assembly.GetCustomAttributes(typeof(GuidAttribute), false); if (attribute.Length < 1) return false; var guidAttribute = attribute.GetValue(0) as GuidAttribute; return guidAttribute.Value.ToString() == "69aee16a-b6e7-4642-8081-3928b32455df"; } catch (Exception) { return false; } } // globally shared between all our identical versions static HashSet<MethodInfo> patchedMethods = new HashSet<MethodInfo>(); // public static void PatchOldHarmonyMethods() { var potentialMethodsToUpgrade = new Dictionary<string, MethodInfo>(); var ourAssembly = typeof(SelfPatching).Assembly; ourAssembly.GetTypes() .SelectMany(type => type.GetMethods(AccessTools.all)) .Where(method => method.GetCustomAttributes(false).Any(attr => attr is UpgradeToLatestVersion)) .Do(method => potentialMethodsToUpgrade.Add(MethodKey(method), method)); AppDomain.CurrentDomain.GetAssemblies() .Where(assembly => IsHarmonyAssembly(assembly) && assembly != ourAssembly) .SelectMany(assembly => assembly.GetTypes()) .SelectMany(type => type.GetMethods(AccessTools.all)) .Select(method => { potentialMethodsToUpgrade.TryGetValue(MethodKey(method), out var newMethod); return new KeyValuePair<MethodInfo, MethodInfo>(method, newMethod); }) .DoIf(pair => pair.Value != null, pair => { var oldMethod = pair.Key; var oldVersion = GetVersion(oldMethod); var newMethod = pair.Value; var newVersion = GetVersion(newMethod); if (oldVersion != -1 && newVersion != -1 && oldVersion < newVersion) { if (patchedMethods.Contains(oldMethod) == false) { patchedMethods.Add(oldMethod); Memory.DetourMethod(oldMethod, newMethod); } } }); } } }
using Harmony.ILCopying; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; namespace Harmony.Tools { internal class SelfPatching { static int GetVersion(MethodInfo method) { var attribute = method.GetCustomAttributes(false).OfType<UpgradeToLatestVersion>().FirstOrDefault(); return attribute?.version ?? -1; } static string MethodKey(MethodInfo method) { return method.DeclaringType + " " + method; } static bool IsHarmonyAssembly(Assembly assembly) { try { var attribute = assembly.GetCustomAttributes(typeof(GuidAttribute), false); if (attribute.Length < 1) return false; var guidAttribute = attribute.GetValue(0) as GuidAttribute; return guidAttribute.Value.ToString() == "69aee16a-b6e7-4642-8081-3928b32455df"; } catch (Exception) { return false; } } // globally shared between all our identical versions static HashSet<MethodInfo> patchedMethods = new HashSet<MethodInfo>(); // public static void PatchOldHarmonyMethods() { var potentialMethodsToUpgrade = new Dictionary<string, MethodInfo>(); typeof(SelfPatching).Assembly.GetTypes() .SelectMany(type => type.GetMethods(AccessTools.all)) .Where(method => method.GetCustomAttributes(false).Any(attr => attr is UpgradeToLatestVersion)) .Do(method => potentialMethodsToUpgrade.Add(MethodKey(method), method)); AppDomain.CurrentDomain.GetAssemblies() .Where(assembly => IsHarmonyAssembly(assembly)) .SelectMany(assembly => assembly.GetTypes()) .SelectMany(type => type.GetMethods(AccessTools.all)) .Select(method => { potentialMethodsToUpgrade.TryGetValue(MethodKey(method), out var newMethod); return new KeyValuePair<MethodInfo, MethodInfo>(method, newMethod); }) .Do(pair => { var oldMethod = pair.Key; var newMethod = pair.Value; if (newMethod != null && GetVersion(oldMethod) < GetVersion(newMethod)) { if (patchedMethods.Contains(oldMethod) == false) { patchedMethods.Add(oldMethod); Memory.DetourMethod(oldMethod, newMethod); } } }); } } }
mit
C#
2382651592bf107ee26ccb479d1f66f3e57ff136
use GetComponentInParent so composed collider will work with colliders in child GameObjects
JScott/ViveGrip
Assets/ViveGrip/Scripts/Internal/ViveGrip_TouchDetection.cs
Assets/ViveGrip/Scripts/Internal/ViveGrip_TouchDetection.cs
using UnityEngine; using System.Collections.Generic; public class ViveGrip_TouchDetection : MonoBehaviour { public float radius = 1f; private List<GameObject> collidingObjects = new List<GameObject>(); void Start () { GetComponent<SphereCollider>().isTrigger = true; } void OnTriggerEnter(Collider other) { collidingObjects.Add(other.gameObject); } void OnTriggerExit(Collider other) { collidingObjects.Remove(other.gameObject); } public GameObject NearestObject() { float closestDistance = radius + 1f; GameObject touchedObject = null; foreach (GameObject gameObject in collidingObjects) { GameObject activeGameObject = ActiveViveGripObject(gameObject); if (activeGameObject!=null) { float distance = Vector3.Distance(transform.position, gameObject.transform.position); if (distance < closestDistance) { touchedObject = activeGameObject; closestDistance = distance; } } } return touchedObject; } GameObject ActiveViveGripObject(GameObject gameObject) { if (gameObject == null) { return null; } // Happens with Destroy() sometimes ViveGrip_Grabbable grabbable = gameObject.GetComponentInParent<ViveGrip_Grabbable>(); bool validGrabbable = grabbable != null && grabbable.enabled; if (validGrabbable) return grabbable.gameObject; ViveGrip_Interactable interactable = gameObject.GetComponentInParent<ViveGrip_Interactable>(); bool validInteractable = interactable != null && interactable.enabled; if (validInteractable) return interactable.gameObject; return null; } }
using UnityEngine; using System.Collections.Generic; public class ViveGrip_TouchDetection : MonoBehaviour { public float radius = 1f; private List<GameObject> collidingObjects = new List<GameObject>(); void Start () { GetComponent<SphereCollider>().isTrigger = true; } void OnTriggerEnter(Collider other) { collidingObjects.Add(other.gameObject); } void OnTriggerExit(Collider other) { collidingObjects.Remove(other.gameObject); } public GameObject NearestObject() { float closestDistance = radius + 1f; GameObject touchedObject = null; foreach (GameObject gameObject in collidingObjects) { if (!ActiveViveGripObject(gameObject)) { continue; } float distance = Vector3.Distance(transform.position, gameObject.transform.position); if (distance < closestDistance) { touchedObject = gameObject; closestDistance = distance; } } return touchedObject; } bool ActiveViveGripObject(GameObject gameObject) { if (gameObject == null) { return false; } // Happens with Destroy() sometimes ViveGrip_Grabbable grabbable = gameObject.GetComponent<ViveGrip_Grabbable>(); ViveGrip_Interactable interactable = gameObject.GetComponent<ViveGrip_Interactable>(); bool validGrabbable = grabbable != null && grabbable.enabled; bool validInteractable = interactable != null && interactable.enabled; return validGrabbable || validInteractable; } }
mit
C#
af3cfdf26025ac0ae88e2889730ce863ca8feb04
Revert "Added working solution"
blstream/AugmentedSzczecin_WP,blstream/AugmentedSzczecin_WP,blstream/AugmentedSzczecin_WP
AugmentedSzczecin/AugmentedSzczecin/Services/DataService.cs
AugmentedSzczecin/AugmentedSzczecin/Services/DataService.cs
using AugmentedSzczecin.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Formatting; using System.Text; using System.Threading.Tasks; using Windows.Data.Json; using Newtonsoft.Json; using System.Collections.ObjectModel; using System.Runtime.Serialization.Json; using System.IO; namespace AugmentedSzczecin.Services { public class DataService { private static string _page = "https://patronatwp.azure-mobile.net/tables/Place"; public async Task<ObservableCollection<Place>> RunAsync() { ObservableCollection<Place> model = null; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(_page); response.EnsureSuccessStatusCode(); string jsonString = await response.Content.ReadAsStringAsync(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObservableCollection<Place>)); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); model = (ObservableCollection<Place>)ser.ReadObject(stream); //IMPORTANT!!! //model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(jsonString); //string x = "[{ \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }, { \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }]"; //model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(x); return model; } } }
using AugmentedSzczecin.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Formatting; using System.Text; using System.Threading.Tasks; using Windows.Data.Json; using Newtonsoft.Json; using System.Collections.ObjectModel; using System.Runtime.Serialization.Json; using System.IO; namespace AugmentedSzczecin.Services { public class DataService { private static string _page = "https://patronatwp.azure-mobile.net/tables/Place"; public async Task<ObservableCollection<Place>> RunAsync() { ObservableCollection<Place> model = null; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(_page); response.EnsureSuccessStatusCode(); string jsonString = await response.Content.ReadAsStringAsync(); //ALTERNATIVE SOLUTION DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObservableCollection<Place>)); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); model = (ObservableCollection<Place>)ser.ReadObject(stream); //ORIGINAL SOLUTION - nulls //model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(jsonString); //string x = "[{ \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }, { \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }]"; //model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(x); return model; } } }
apache-2.0
C#
6ed95029837b3051682c1f2d75a796293a65230e
Add generic version of interface
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
osu.Framework/Bindables/ILeasedBindable.cs
osu.Framework/Bindables/ILeasedBindable.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Bindables { /// <summary> /// An interface that represents a read-only leased bindable. /// </summary> public interface ILeasedBindable : IBindable { /// <summary> /// End the lease on the source <see cref="Bindable{T}"/>. /// </summary> void Return(); } /// <summary> /// An interface that representes a read-only leased bindable. /// </summary> /// <typeparam name="T">The value type of the bindable.</typeparam> public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T> { } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Bindables { /// <summary> /// An interface that represents a read-only leased bindable. /// </summary> public interface ILeasedBindable : IBindable { /// <summary> /// End the lease on the source <see cref="Bindable{T}"/>. /// </summary> void Return(); } }
mit
C#
62f9edf87b8675da8ef350e45a800bb2bb44d680
Bump version to 1.5.O
zpqrtbnk/Zbu.ModelsBuilder,danlister/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder
Zbu.ModelsBuilder/Properties/CommonInfo.cs
Zbu.ModelsBuilder/Properties/CommonInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("ZpqrtBnk Umbraco ModelsBuilder")] [assembly: AssemblyCompany("Pilotine - ZpqrtBnk")] [assembly: AssemblyCopyright("Copyright © Pilotine - ZpqrtBnk 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.5.0.0")] [assembly: AssemblyFileVersion("1.5.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("ZpqrtBnk Umbraco ModelsBuilder")] [assembly: AssemblyCompany("Pilotine - ZpqrtBnk")] [assembly: AssemblyCopyright("Copyright © Pilotine - ZpqrtBnk 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
mit
C#
44c9c7dd16dc83992a456249d1d7dc48a8c265db
Allow null urlOptions in EndpointBase.Get...()
arthurrump/Zermelo.API
Zermelo/Zermelo.API/Endpoints/EndpointBase.cs
Zermelo/Zermelo.API/Endpoints/EndpointBase.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Exceptions; using Zermelo.API.Helpers; using Zermelo.API.Interfaces; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Endpoints { abstract internal class EndpointBase { protected IAuthentication _auth; protected IUrlBuilder _urlBuilder; protected IHttpService _httpService; protected IJsonService _jsonService; protected EndpointBase(IAuthentication auth, IUrlBuilder urlBuilder, IHttpService httpService, IJsonService jsonService) { _auth = auth; _urlBuilder = urlBuilder; _httpService = httpService; _jsonService = jsonService; } protected async Task<IEnumerable<T>> GetByCustomUrlOptionsAsync<T>(string endpoint, Dictionary<string, string> urlOptions, List<string> fields = null) { if (fields != null && fields.Any()) { if (urlOptions == null) { urlOptions = new Dictionary<string, string>(); } urlOptions.Add("fields", fields.ToCommaSeperatedString()); } string url = _urlBuilder.GetAuthenticatedUrl(_auth, endpoint, urlOptions); IHttpResponse httpResponse = await _httpService.GetAsync(url); if (httpResponse.StatusCode != 200) throw new ZermeloHttpException(httpResponse); string json = httpResponse.Response; return _jsonService.DeserializeCollection<T>(json); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Exceptions; using Zermelo.API.Helpers; using Zermelo.API.Interfaces; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Endpoints { abstract internal class EndpointBase { protected IAuthentication _auth; protected IUrlBuilder _urlBuilder; protected IHttpService _httpService; protected IJsonService _jsonService; protected EndpointBase(IAuthentication auth, IUrlBuilder urlBuilder, IHttpService httpService, IJsonService jsonService) { _auth = auth; _urlBuilder = urlBuilder; _httpService = httpService; _jsonService = jsonService; } protected async Task<IEnumerable<T>> GetByCustomUrlOptionsAsync<T>(string endpoint, Dictionary<string, string> urlOptions, List<string> fields = null) { if (fields != null && fields.Any()) urlOptions.Add("fields", fields.ToCommaSeperatedString()); string url = _urlBuilder.GetAuthenticatedUrl(_auth, endpoint, urlOptions); IHttpResponse httpResponse = await _httpService.GetAsync(url); if (httpResponse.StatusCode != 200) throw new ZermeloHttpException(httpResponse); string json = httpResponse.Response; return _jsonService.DeserializeCollection<T>(json); } } }
mit
C#
b780d0f74bcbe4471427cb0b81cf5be5d79685c4
Add GetUniqueName method
cube-soft/Cube.FileSystem,cube-soft/Cube.Core,cube-soft/Cube.Core,cube-soft/Cube.FileSystem
Libraries/Operations/Files.cs
Libraries/Operations/Files.cs
/* ------------------------------------------------------------------------- */ /// /// Copyright (c) 2010 CubeSoft, Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /* ------------------------------------------------------------------------- */ using System; using System.Runtime.InteropServices; namespace Cube.FileSystem.Files { /* --------------------------------------------------------------------- */ /// /// Files.Operations /// /// <summary> /// FileInfo に対する拡張メソッドを定義するためのクラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ public static class Operations { /* ----------------------------------------------------------------- */ /// /// GetTypeName /// /// <summary> /// ファイルの種類を表す文字列を取得します。 /// </summary> /// /// <param name="fi">FileInfo オブジェクト</param> /// /* ----------------------------------------------------------------- */ public static string GetTypeName(this System.IO.FileInfo fi) { if (fi == null) return null; var attr = Shell32.NativeMethods.FILE_ATTRIBUTE_NORMAL; var flags = Shell32.NativeMethods.SHGFI_TYPENAME | Shell32.NativeMethods.SHGFI_USEFILEATTRIBUTES; var shfi = new SHFILEINFO(); var result = Shell32.NativeMethods.SHGetFileInfo(fi.FullName, attr, ref shfi, (uint)Marshal.SizeOf(shfi), flags); return (result != IntPtr.Zero) ? shfi.szTypeName : null; } /* ----------------------------------------------------------------- */ /// /// GetUniqueName /// /// <summary> /// FileInfo オブジェクトを基にした一意なパスを取得します。 /// </summary> /// /// <param name="fi">FileInfo オブジェクト</param> /// /* ----------------------------------------------------------------- */ public static string GetUniqueName(this System.IO.FileInfo fi) { if (!fi.Exists) return fi.FullName; var path = fi.FullName; var dir = fi.DirectoryName; var name = System.IO.Path.GetFileNameWithoutExtension(path); var ext = fi.Extension; for (var i = 2; ; ++i) { var dest = System.IO.Path.Combine(dir, $"{name}({i}){ext}"); if (!System.IO.File.Exists(dest) && !System.IO.Directory.Exists(dest)) return dest; } } } }
/* ------------------------------------------------------------------------- */ /// /// Copyright (c) 2010 CubeSoft, Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /* ------------------------------------------------------------------------- */ using System; using System.Runtime.InteropServices; namespace Cube.FileSystem.Files { /* --------------------------------------------------------------------- */ /// /// Files.Operations /// /// <summary> /// FileInfo に対する拡張メソッドを定義するためのクラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ public static class Operations { /* ----------------------------------------------------------------- */ /// /// GetTypeName /// /// <summary> /// ファイルの種類を表す文字列を取得します。 /// </summary> /// /* ----------------------------------------------------------------- */ public static string GetTypeName(this System.IO.FileInfo fi) { if (fi == null) return null; var attr = Shell32.NativeMethods.FILE_ATTRIBUTE_NORMAL; var flags = Shell32.NativeMethods.SHGFI_TYPENAME | Shell32.NativeMethods.SHGFI_USEFILEATTRIBUTES; var shfi = new SHFILEINFO(); var result = Shell32.NativeMethods.SHGetFileInfo(fi.FullName, attr, ref shfi, (uint)Marshal.SizeOf(shfi), flags); return (result != IntPtr.Zero) ? shfi.szTypeName : null; } } }
apache-2.0
C#
7522fd495560e0ada2f59be5cb45de6d69fa3fca
Remove file structure comment from doc summary
ddpruitt/morelinq,ddpruitt/morelinq,morelinq/MoreLINQ,morelinq/MoreLINQ,fsateler/MoreLINQ,fsateler/MoreLINQ
MoreLinq/MoreEnumerable.cs
MoreLinq/MoreEnumerable.cs
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; /// <summary> /// Provides a set of static methods for querying objects that /// implement <see cref="IEnumerable{T}" />. /// </summary> public static partial class MoreEnumerable { static int? TryGetCollectionCount<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source is ICollection<T> collection ? collection.Count : source is IReadOnlyCollection<T> readOnlyCollection ? readOnlyCollection.Count : (int?)null; } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; /// <summary> /// Provides a set of static methods for querying objects that /// implement <see cref="IEnumerable{T}" />. The actual methods /// are implemented in files reflecting the method name. /// </summary> public static partial class MoreEnumerable { static int? TryGetCollectionCount<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source is ICollection<T> collection ? collection.Count : source is IReadOnlyCollection<T> readOnlyCollection ? readOnlyCollection.Count : (int?)null; } } }
apache-2.0
C#
b38200dfd16669cfefefbc27929a815f660cfbca
Create the keyboard only when receiving RegisterWindowsKeyboardMessage
RagingBool/RagingBool.Carcosa
projects/RagingBool.Carcosa.Core_cs/Control/CarcosaControlActor.cs
projects/RagingBool.Carcosa.Core_cs/Control/CarcosaControlActor.cs
// [[[[INFO> // Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool) // // 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. // // For more information check https://github.com/RagingBool/RagingBool.Carcosa // ]]]] using Akka.Actor; using RagingBool.Carcosa.Commons.Control.Akka.System; using RagingBool.Carcosa.Devices.InputControl; namespace RagingBool.Carcosa.Core.Control { internal sealed class CarcosaControlActor : UntypedActor { private readonly IActorRef _controlSystemActor; public CarcosaControlActor() { _controlSystemActor = Context.ActorOf<ControlSystemActor>("system"); } protected override void OnReceive(object message) { if (message is RegisterWindowsKeyboardMessage) { _controlSystemActor.Tell(new CreateComponentMesssage("keyboard", typeof(KeyboardControlActor<WindowsKey, TimedKey>))); } else { Unhandled(message); } } } }
// [[[[INFO> // Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool) // // 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. // // For more information check https://github.com/RagingBool/RagingBool.Carcosa // ]]]] using Akka.Actor; using RagingBool.Carcosa.Commons.Control.Akka.System; using RagingBool.Carcosa.Devices.InputControl; namespace RagingBool.Carcosa.Core.Control { internal sealed class CarcosaControlActor : UntypedActor { private readonly IActorRef _controlSystemActor; public CarcosaControlActor() { _controlSystemActor = Context.ActorOf<ControlSystemActor>("system"); _controlSystemActor.Tell(new CreateComponentMesssage("keyboard", typeof(KeyboardControlActor<WindowsKey, TimedKey>))); } protected override void OnReceive(object message) { Unhandled(message); } } }
apache-2.0
C#
5589dbf6f7c2ec0f17271e4af44047f3ec9b3442
Add config in compile
joemcbride/es-microservice,joemcbride/es-microservice,joemcbride/es-microservice
cake-scripts/compile.csx
cake-scripts/compile.csx
#load "helpers/Constants.cs" #load "helpers/Methods.cs" using System; using System.IO; using System.Linq; Task("dotnetCompile").Does(()=> { var config = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production" ? "Release" : "Debug"; Run("dotnet", string.Format("build src -c {0}", config)); });
#load "helpers/Constants.cs" #load "helpers/Methods.cs" using System; using System.IO; using System.Linq; Task("dotnetCompile").Does(()=> { Run("dotnet", "build src"); });
mit
C#
8d51628acec4dcb63a8e1d2249406d87adad4c0f
Revert "Added XML documentation"
darrylwhitmore/NScrape
NScrape/JsonWebResponse.cs
NScrape/JsonWebResponse.cs
using System; using System.Text; namespace NScrape { public class JsonWebResponse : TextWebResponse { internal JsonWebResponse(bool success, Uri url, string text, Encoding encoding) : base(url, WebResponseType.JavaScript, success, text, encoding) { } /// <summary> /// Gets the JSON data. /// </summary> public string Json { get { return Text; } } } }
using System; using System.Text; namespace NScrape { /// <summary> /// Represents a web response for a request that returned JSON. /// </summary> public class JsonWebResponse : TextWebResponse { internal JsonWebResponse( bool success, Uri url, string text, Encoding encoding ) : base( url, WebResponseType.JavaScript, success, text, encoding ) { } /// <summary> /// Gets the JSON data. /// </summary> public string Json { get { return Text; } } } }
mit
C#
15fad097aa95bfdbf1f681685bfafbf1d05b4aa6
Add test cases based on inheritance from Case
yawaramin/TDDUnit
Runner.cs
Runner.cs
using System; using System.Linq; using System.Reflection; namespace TDDUnit { class Runner { public Runner(Type callingType) { Suite suite = new Suite(); m_result = new Result(); Type[] forbiddenTypes = new Type[] { callingType , typeof (TDDUnit.WasRunObj) , typeof (TDDUnit.WasRunSetUpFailed) }; foreach (Type t in Assembly.GetEntryAssembly().GetTypes()) { if (t.IsSubclassOf(typeof (TDDUnit.Case)) && !forbiddenTypes.Contains(t)) suite.Add(t); } foreach (string test in suite.FailedTests(m_result)) { Console.WriteLine("Failed: " + test); } Console.WriteLine(m_result.Summary); } public string Summary { get { return m_result.Summary; } } private Result m_result; } }
using System; using System.Linq; using System.Reflection; namespace TDDUnit { class Runner { public Runner(Type exceptType) { Suite suite = new Suite(); m_result = new Result(); foreach (Type t in Assembly.GetEntryAssembly().GetTypes()) { if (t.Name.StartsWith("Test") && t.Name != exceptType.Name) suite.Add(t); } foreach (string test in suite.FailedTests(m_result)) { Console.WriteLine("Failed: " + test); } Console.WriteLine(m_result.Summary); } public string Summary { get { return m_result.Summary; } } private Result m_result; } }
apache-2.0
C#
ab08d802a8a6d31d4d33c9030f416afbf5dc4a7d
Update version to 1.2.16
anonymousthing/ListenMoeClient
Properties/AssemblyInfo.cs
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("Listen.moe Client")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Listen.moe Client")] [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("88b02799-425e-4622-a849-202adb19601b")] // 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.2.16.0")] [assembly: AssemblyFileVersion("1.2.16.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("Listen.moe Client")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Listen.moe Client")] [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("88b02799-425e-4622-a849-202adb19601b")] // 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.2.15.0")] [assembly: AssemblyFileVersion("1.2.15.0")]
mit
C#
d3183fb2367ab5e48334949c1656b3ad3b5622d0
Implement `ConstantExpressionAst.ToString()`
WimObiwan/Pash,ForNeVeR/Pash,Jaykul/Pash,WimObiwan/Pash,WimObiwan/Pash,sburnicki/Pash,sillvan/Pash,sillvan/Pash,sburnicki/Pash,JayBazuzi/Pash,sburnicki/Pash,Jaykul/Pash,JayBazuzi/Pash,JayBazuzi/Pash,WimObiwan/Pash,mrward/Pash,mrward/Pash,Jaykul/Pash,ForNeVeR/Pash,sillvan/Pash,mrward/Pash,JayBazuzi/Pash,mrward/Pash,ForNeVeR/Pash,sburnicki/Pash,Jaykul/Pash,ForNeVeR/Pash,sillvan/Pash
Source/Pash.System.Management/Automation/Language/ConstantExpressionAst.cs
Source/Pash.System.Management/Automation/Language/ConstantExpressionAst.cs
using System; using System.Collections.Generic; using System.Management.Automation; namespace System.Management.Automation.Language { public class ConstantExpressionAst : ExpressionAst { public ConstantExpressionAst(IScriptExtent extent, object value) : base(extent) { this.Value = value; } public override Type StaticType { get { return this.Value.GetType(); } } public object Value { get; private set; } public override string ToString() { return this.Value.ToString(); } } }
using System; using System.Collections.Generic; using System.Management.Automation; namespace System.Management.Automation.Language { public class ConstantExpressionAst : ExpressionAst { public ConstantExpressionAst(IScriptExtent extent, object value) : base(extent) { this.Value = value; } public override Type StaticType { get { return this.Value.GetType(); } } public object Value { get; private set; } } }
bsd-3-clause
C#
1cc0f5be5a1d9a44a711f301a9e1e59402c1c1f1
Add return value
danielmundt/csremote
source/Remoting.Interface/ICommand.cs
source/Remoting.Interface/ICommand.cs
#region Header // Copyright (C) 2012 Daniel Schubert // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion Header using System; using System.Collections.Generic; using System.Linq; using System.Text; using Remoting.Interface.Enums; namespace Remoting.Interface { public interface ICommand { bool SendCommand(Command command); } }
#region Header // Copyright (C) 2012 Daniel Schubert // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion Header using System; using System.Collections.Generic; using System.Linq; using System.Text; using Remoting.Interface.Enums; namespace Remoting.Interface { public interface ICommand { void SendCommand(Command command); } }
mit
C#
84e892a5a30dc4975b92f736d6722325a53f9a77
fix dumy fix
michael-reichenauer/GitMind
GitMind/GitModel/Branch.cs
GitMind/GitModel/Branch.cs
using System.Collections.Generic; using System.Linq; namespace GitMind.GitModel { // Some extra Branch internal class Branch { private readonly Repository repository; private readonly string tipCommitId; private readonly string firstCommitId; private readonly string parentCommitId; private readonly IReadOnlyList<string> commitIds; private readonly string parentBranchId; public Branch( Repository repository, string id, string name, string tipCommitId, string firstCommitId, string parentCommitId, IReadOnlyList<string> commitIds, string parentBranchId, IReadOnlyList<string> childBranchNames, bool isActive, bool isMultiBranch, int localAheadCount, int remoteAheadCount) { this.repository = repository; this.tipCommitId = tipCommitId; this.firstCommitId = firstCommitId; this.parentCommitId = parentCommitId; this.commitIds = commitIds; this.parentBranchId = parentBranchId; Id = id; Name = name; ChildBranchNames = childBranchNames; IsActive = isActive; IsMultiBranch = isMultiBranch; LocalAheadCount = localAheadCount; RemoteAheadCount = remoteAheadCount; } public string Id { get; } public string Name { get; } public IReadOnlyList<string> ChildBranchNames { get; } public bool IsActive { get; } public bool IsMultiBranch { get; } public int LocalAheadCount { get; } public int RemoteAheadCount { get; } public Commit TipCommit => repository.Commits[tipCommitId]; public Commit FirstCommit => repository.Commits[firstCommitId]; public Commit ParentCommit => repository.Commits[parentCommitId]; public IEnumerable<Commit> Commits => commitIds.Select(id => repository.Commits[id]); public bool HasParentBranch => parentBranchId != null; public Branch ParentBranch => repository.Branches[parentBranchId]; public bool IsCurrentBranch => repository.CurrentBranch == this; public bool IsMergeable => IsCurrentBranch && repository.Status.ConflictCount == 0 && repository.Status.StatusCount == 0; public IEnumerable<Branch> GetChildBranches() { foreach (Branch branch in repository.Branches .Where(b => b.HasParentBranch && b.ParentBranch == this) .Distinct() .OrderByDescending(b => b.ParentCommit.CommitDate)) { yield return branch; } } public IEnumerable<Branch> Parents() { Branch current = this; while (current.HasParentBranch) { current = current.ParentBranch; yield return current; } } public override string ToString() => Name; } }
using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace GitMind.GitModel { // A Branch internal class Branch { private readonly Repository repository; private readonly string tipCommitId; private readonly string firstCommitId; private readonly string parentCommitId; private readonly IReadOnlyList<string> commitIds; private readonly string parentBranchId; public Branch( Repository repository, string id, string name, string tipCommitId, string firstCommitId, string parentCommitId, IReadOnlyList<string> commitIds, string parentBranchId, IReadOnlyList<string> childBranchNames, bool isActive, bool isMultiBranch, int localAheadCount, int remoteAheadCount) { this.repository = repository; this.tipCommitId = tipCommitId; this.firstCommitId = firstCommitId; this.parentCommitId = parentCommitId; this.commitIds = commitIds; this.parentBranchId = parentBranchId; Id = id; Name = name; ChildBranchNames = childBranchNames; IsActive = isActive; IsMultiBranch = isMultiBranch; LocalAheadCount = localAheadCount; RemoteAheadCount = remoteAheadCount; } public string Id { get; } public string Name { get; } public IReadOnlyList<string> ChildBranchNames { get; } public bool IsActive { get; } public bool IsMultiBranch { get; } public int LocalAheadCount { get; } public int RemoteAheadCount { get; } public Commit TipCommit => repository.Commits[tipCommitId]; public Commit FirstCommit => repository.Commits[firstCommitId]; public Commit ParentCommit => repository.Commits[parentCommitId]; public IEnumerable<Commit> Commits => commitIds.Select(id => repository.Commits[id]); public bool HasParentBranch => parentBranchId != null; public Branch ParentBranch => repository.Branches[parentBranchId]; public bool IsCurrentBranch => repository.CurrentBranch == this; public bool IsMergeable => IsCurrentBranch && repository.Status.ConflictCount == 0 && repository.Status.StatusCount == 0; public IEnumerable<Branch> GetChildBranches() { foreach (Branch branch in repository.Branches .Where(b => b.HasParentBranch && b.ParentBranch == this) .Distinct() .OrderByDescending(b => b.ParentCommit.CommitDate)) { yield return branch; } } public IEnumerable<Branch> Parents() { Branch current = this; while (current.HasParentBranch) { current = current.ParentBranch; yield return current; } } public override string ToString() => Name; } }
mit
C#
3fcf40d07eea4048450896d813b89c2e236fbaa4
Update Sprite, Implement IRenderable2D
Silvertorch5/RobustEngine
Graphics/Sprites/Sprite.cs
Graphics/Sprites/Sprite.cs
using System.Drawing; using OpenTK; namespace RobustEngine.Graphics.Sprites { public class Sprite : IRenderable2D { public string ID; //GL VBO'S public int VertexBuffer; public int IndexBuffer; public Color ColorBuffer; public Rectangle SpriteAABB; public Texture2D Texture; public Vector2 Scale; public Vector2 Position; //Accessors TODO public double Rotation; public int Width; public int Height; public Sprite(string id, Texture2D texture) { ID = id; Texture = texture; Setup(); } private void Setup() { SpriteAABB = Texture.TextureAABB; Width = SpriteAABB.Width; Height = SpriteAABB.Height; Rotation = 0.0; Scale = Vector2.One; Position = Vector2.Zero; } public void SetRotation(double newRotation) { Rotation = newRotation; } public void SetPosition(Vector2 newPosition) { Position = newPosition; } public void SetScale(Vector2 newScale) { Scale = newScale; } public void Draw() { } } }
using System.Drawing; using OpenTK; namespace RobustEngine.Graphics.Sprites { public class Sprite { public string ID; //GL VBO'S public int VertexBuffer; public int TextureBuffer; public int ColorBuffer; //Accessors TODO public double Rotation; public int Width; public int Height; public Rectangle SpriteAABB; public Texture2D Texture; public Vector2 Scale; public Vector2 Position; public Sprite(string id, Texture2D texture) { ID = id; Texture = texture; Setup(); } private void Setup() { SpriteAABB = Texture.TextureAABB; Width = SpriteAABB.Width; Height = SpriteAABB.Height; Rotation = 0.0; Scale = Vector2.One; Position = Vector2.Zero; } public void SetRotation(double newRotation) { Rotation = newRotation; } public void SetPosition(Vector2 newPosition) { Position = newPosition; } public void SetScale(Vector2 newScale) { Scale = newScale; } public void Blit() { } } }
mit
C#
1ada0fdde3cd4b53386545ca041d95e01140d471
Update Program.cs
mmolhov333/SupplyDepot
TestApp/TestApp/Program.cs
TestApp/TestApp/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestApp { class Program { static void Main(string[] args) { Console.WriteLine("GitHub rules the seven seas!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestApp { class Program { static void Main(string[] args) { Console.WriteLine("GitHub rules the seven seas! Also I like cars"); } } }
mit
C#
4b12b847e43e15369c618bdbf973c46ccd570c0f
Use ReadOnlyCollection for extensions.
GetTabster/Tabster
Tabster.Data/FileType.cs
Tabster.Data/FileType.cs
#region using System.Collections.Generic; using System.Collections.ObjectModel; #endregion namespace Tabster.Data { public sealed class FileType { private readonly List<string> _extensions = new List<string>(); public FileType(string name, IEnumerable<string> extensions) { Name = name; _extensions.AddRange(extensions); } public FileType(string name, string extension) : this(name, new[] {extension}) { } public string Name { get; set; } public ReadOnlyCollection<string> Extensions { get { return _extensions.AsReadOnly(); } } public string Extension { get { return Extensions.Count > 0 ? Extensions[0] : null; } } } }
#region using System.Collections.Generic; using System.Collections.ObjectModel; #endregion namespace Tabster.Data { public sealed class FileType { public readonly Collection<string> Extensions; public FileType(string name, IList<string> extensions) { Name = name; Extensions = new Collection<string>(extensions); } public FileType(string name, string extension) : this(name, new[] {extension}) { } public string Name { get; set; } public string Extension { get { return Extensions.Count > 0 ? Extensions[0] : null; } } } }
apache-2.0
C#
82e9998e35652d5bd0cf33790803168284d3a615
add type constraints for view view-model mapping
tibel/Caliburn.Light
src/Caliburn.Xaml/ViewModelTypeResolver.cs
src/Caliburn.Xaml/ViewModelTypeResolver.cs
using System; using System.Collections.Generic; using System.ComponentModel; #if NETFX_CORE using Windows.UI.Xaml; #else using System.Windows; #endif namespace Caliburn.Light { /// <summary> /// Resolves view and view-model types. /// </summary> public class ViewModelTypeResolver : IViewModelTypeResolver { private readonly Dictionary<Type, Type> _modelTypeLookup = new Dictionary<Type, Type>(); private readonly Dictionary<Tuple<Type, string>, Type> _viewTypeLookup = new Dictionary<Tuple<Type, string>, Type>(); /// <summary> /// Determines the view model type based on the specified view type. /// </summary> /// <param name="viewType">The view type.</param> /// <returns>The view model type or null, if not found.</returns> public Type GetModelType(Type viewType) { if (viewType == null) throw new ArgumentNullException(nameof(viewType)); Type modelType; _modelTypeLookup.TryGetValue(viewType, out modelType); return modelType; } /// <summary> /// Locates the view type based on the specified model type. /// </summary> /// <param name="modelType">The model type.</param> /// <param name="context">The context instance (or null).</param> /// <returns>The view type or null, if not found.</returns> public Type GetViewType(Type modelType, string context) { if (modelType == null) throw new ArgumentNullException(nameof(modelType)); Type viewType; _viewTypeLookup.TryGetValue(new Tuple<Type, string>(modelType, context ?? string.Empty), out viewType); return viewType; } /// <summary> /// Adds a view view-model mapping. /// </summary> /// <typeparam name="TView">The view type.</typeparam> /// <typeparam name="TViewModel">The view-model type.</typeparam> /// <param name="context">The context instance (or null).</param> public void AddMapping<TView, TViewModel>(string context = null) where TView : UIElement where TViewModel : INotifyPropertyChanged { var viewType = typeof(TView); var modelType = typeof(TViewModel); if (context == null) _modelTypeLookup.Add(viewType, modelType); _viewTypeLookup.Add(new Tuple<Type, string>(modelType, context ?? string.Empty), viewType); } } }
using System; using System.Collections.Generic; namespace Caliburn.Light { /// <summary> /// Resolves view and view-model types. /// </summary> public class ViewModelTypeResolver : IViewModelTypeResolver { private readonly Dictionary<Type, Type> _modelTypeLookup = new Dictionary<Type, Type>(); private readonly Dictionary<Tuple<Type, string>, Type> _viewTypeLookup = new Dictionary<Tuple<Type, string>, Type>(); /// <summary> /// Determines the view model type based on the specified view type. /// </summary> /// <param name="viewType">The view type.</param> /// <returns>The view model type or null, if not found.</returns> public Type GetModelType(Type viewType) { if (viewType == null) throw new ArgumentNullException(nameof(viewType)); Type modelType; _modelTypeLookup.TryGetValue(viewType, out modelType); return modelType; } /// <summary> /// Locates the view type based on the specified model type. /// </summary> /// <param name="modelType">The model type.</param> /// <param name="context">The context instance (or null).</param> /// <returns>The view type or null, if not found.</returns> public Type GetViewType(Type modelType, string context) { if (modelType == null) throw new ArgumentNullException(nameof(modelType)); Type viewType; _viewTypeLookup.TryGetValue(new Tuple<Type, string>(modelType, context ?? string.Empty), out viewType); return viewType; } /// <summary> /// Adds a view view-model mapping. /// </summary> /// <typeparam name="TView">The view type.</typeparam> /// <typeparam name="TViewModel">The view-model type.</typeparam> /// <param name="context">The context instance (or null).</param> public void AddMapping<TView, TViewModel>(string context = null) { var viewType = typeof(TView); var modelType = typeof(TViewModel); if (context == null) _modelTypeLookup.Add(viewType, modelType); _viewTypeLookup.Add(new Tuple<Type, string>(modelType, context ?? string.Empty), viewType); } } }
mit
C#
85cdf95d7c905f220df0bca80cdad6327b2a50b4
Use the version number present in the global.json file when generating documentation. (#3557)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/CodeGeneration/DocGenerator/Program.cs
src/CodeGeneration/DocGenerator/Program.cs
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace DocGenerator { public static class Program { static Program() { string P(string path) { return path.Replace(@"\", Path.DirectorySeparatorChar.ToString()); } var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory()); var globalJson = P(@"..\..\..\global.json"); if (currentDirectory.Name == "DocGenerator" && currentDirectory.Parent.Name == "CodeGeneration") { Console.WriteLine("IDE: " + currentDirectory); InputDirPath = P(@"..\..\"); OutputDirPath = P(@"..\..\..\docs"); BuildOutputPath = P(@"..\..\..\src"); } else { globalJson = P(@"..\..\..\..\global.json"); Console.WriteLine("CMD: " + currentDirectory); InputDirPath = P(@"..\..\..\..\src"); OutputDirPath = P(@"..\..\..\..\docs"); BuildOutputPath = P(@"..\..\..\..\build\output"); } var globalJsonVersion = string.Join(".", Regex.Matches(File.ReadAllText(globalJson), "\"version\": \"(.*)\"") .Last().Groups .Last().Value .Split(".") .Take(2)); Console.WriteLine("Using global.json version: " + globalJsonVersion); DocVersion = globalJsonVersion; var process = new Process { StartInfo = new ProcessStartInfo { UseShellExecute = false, RedirectStandardOutput = true, FileName = "git.exe", CreateNoWindow = true, WorkingDirectory = Environment.CurrentDirectory, Arguments = "rev-parse --abbrev-ref HEAD" } }; try { process.Start(); BranchName = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); } catch (Exception) { BranchName = "master"; } finally { process.Dispose(); } } /// <summary> /// The branch name to include in generated docs to link back to the original source file /// </summary> public static string BranchName { get; set; } public static string BuildOutputPath { get; } /// <summary> /// The Elasticsearch documentation version to link to /// </summary> public static string DocVersion { get; set; } public static string InputDirPath { get; } public static string OutputDirPath { get; } private static int Main(string[] args) { try { if (args.Length > 0) BranchName = args[0]; Console.WriteLine($"Using branch name {BranchName} in documentation"); LitUp.GoAsync(args).Wait(); return 0; } catch (AggregateException ae) { var ex = ae.InnerException ?? ae; Console.WriteLine(ex.Message); return 1; } } } }
using System; using System.Diagnostics; using System.IO; namespace DocGenerator { public static class Program { static Program() { string P(string path) { return path.Replace(@"\", Path.DirectorySeparatorChar.ToString()); } var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory()); if (currentDirectory.Name == "DocGenerator" && currentDirectory.Parent.Name == "CodeGeneration") { Console.WriteLine("IDE: " + currentDirectory); InputDirPath = P(@"..\..\"); OutputDirPath = P(@"..\..\..\docs"); BuildOutputPath = P(@"..\..\..\src"); } else { Console.WriteLine("CMD: " + currentDirectory); InputDirPath = P(@"..\..\..\..\src"); OutputDirPath = P(@"..\..\..\..\docs"); BuildOutputPath = P(@"..\..\..\..\build\output"); } var process = new Process { StartInfo = new ProcessStartInfo { UseShellExecute = false, RedirectStandardOutput = true, FileName = "git.exe", CreateNoWindow = true, WorkingDirectory = Environment.CurrentDirectory, Arguments = "rev-parse --abbrev-ref HEAD" } }; try { process.Start(); BranchName = process.StandardOutput.ReadToEnd().Trim(); process.WaitForExit(); } catch (Exception) { BranchName = "master"; } finally { process.Dispose(); } } /// <summary> /// The branch name to include in generated docs to link back to the original source file /// </summary> public static string BranchName { get; set; } public static string BuildOutputPath { get; } /// <summary> /// The Elasticsearch documentation version to link to /// </summary> public static string DocVersion => "6.4"; public static string InputDirPath { get; } public static string OutputDirPath { get; } private static int Main(string[] args) { try { if (args.Length > 0) BranchName = args[0]; Console.WriteLine($"Using branch name {BranchName} in documentation"); LitUp.GoAsync(args).Wait(); return 0; } catch (AggregateException ae) { var ex = ae.InnerException ?? ae; Console.WriteLine(ex.Message); return 1; } } } }
apache-2.0
C#
3828018bd8c3e32561edc1b41f8c85a8137f7532
Use var instead.
dlemstra/Magick.NET,dlemstra/Magick.NET
src/Magick.NET/Native/NativeHelper.cs
src/Magick.NET/Native/NativeHelper.cs
// Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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; namespace ImageMagick { internal abstract class NativeHelper { private EventHandler<WarningEventArgs> _warningEvent; public event EventHandler<WarningEventArgs> Warning { add { _warningEvent += value; } remove { _warningEvent -= value; } } protected void CheckException(IntPtr exception) { var magickException = MagickExceptionHelper.Check(exception); RaiseWarning(magickException); } protected void RaiseWarning(MagickException exception) { if (_warningEvent == null) return; if (exception is MagickWarningException warning) _warningEvent.Invoke(this, new WarningEventArgs(warning)); } } }
// Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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; namespace ImageMagick { internal abstract class NativeHelper { private EventHandler<WarningEventArgs> _warningEvent; public event EventHandler<WarningEventArgs> Warning { add { _warningEvent += value; } remove { _warningEvent -= value; } } protected void CheckException(IntPtr exception) { MagickException magickException = MagickExceptionHelper.Check(exception); RaiseWarning(magickException); } protected void RaiseWarning(MagickException exception) { if (_warningEvent == null) return; MagickWarningException warning = exception as MagickWarningException; if (warning != null) _warningEvent.Invoke(this, new WarningEventArgs(warning)); } } }
apache-2.0
C#
7471f040c885bcb36218531c45f48f935d23e58d
Simplify ParserQuery tests now that tuples have shorthand syntax.
plioi/parsley
src/Parsley.Tests/ParserQueryTests.cs
src/Parsley.Tests/ParserQueryTests.cs
using System.Globalization; using static Parsley.Grammar; namespace Parsley.Tests; class ParserQueryTests { static readonly Parser<char, char> Next = Single<char>(_ => true, "character"); static readonly Parser<char, string> Fail = (ReadOnlySpan<char> input, ref int index, out bool succeeded, out string? expectation) => { expectation = "unsatisfiable expectation"; succeeded = false; return null; }; public void CanBuildParserWhichSimulatesSuccessfulParsingOfGivenValueWithoutConsumingInput() { var parser = 1.SucceedWithThisValue<char, int>(); parser.PartiallyParses("input", "input").ShouldBe(1); } public void CanBuildParserFromSingleSimplerParser() { var parser = from x in Next select char.ToUpper(x, CultureInfo.InvariantCulture); parser.PartiallyParses("xy", "y").ShouldBe('X'); } public void CanBuildParserFromOrderedSequenceOfSimplerParsers() { var parser = (from a in Next from b in Next from c in Next select $"{a}{b}{c}".ToUpper(CultureInfo.InvariantCulture)); parser.PartiallyParses("abcdef", "def").ShouldBe("ABC"); } public void PropogatesErrorsWithoutRunningRemainingParsers() { (from _ in Fail from x in Next from y in Next select (x, y)).FailsToParse("xy", "xy", "unsatisfiable expectation expected"); (from x in Next from _ in Fail from y in Next select (x, y)).FailsToParse("xy", "y", "unsatisfiable expectation expected"); (from x in Next from y in Next from _ in Fail select (x, y)).FailsToParse("xy", "", "unsatisfiable expectation expected"); } }
using System.Globalization; using static Parsley.Grammar; namespace Parsley.Tests; class ParserQueryTests { static readonly Parser<char, char> Next = Single<char>(_ => true, "character"); static readonly Parser<char, string> Fail = (ReadOnlySpan<char> input, ref int index, out bool succeeded, out string? expectation) => { expectation = "unsatisfiable expectation"; succeeded = false; return null; }; public void CanBuildParserWhichSimulatesSuccessfulParsingOfGivenValueWithoutConsumingInput() { var parser = 1.SucceedWithThisValue<char, int>(); parser.PartiallyParses("input", "input").ShouldBe(1); } public void CanBuildParserFromSingleSimplerParser() { var parser = from x in Next select char.ToUpper(x, CultureInfo.InvariantCulture); parser.PartiallyParses("xy", "y").ShouldBe('X'); } public void CanBuildParserFromOrderedSequenceOfSimplerParsers() { var parser = (from a in Next from b in Next from c in Next select $"{a}{b}{c}".ToUpper(CultureInfo.InvariantCulture)); parser.PartiallyParses("abcdef", "def").ShouldBe("ABC"); } public void PropogatesErrorsWithoutRunningRemainingParsers() { (from _ in Fail from x in Next from y in Next select Tuple.Create(x, y)).FailsToParse("xy", "xy", "unsatisfiable expectation expected"); (from x in Next from _ in Fail from y in Next select Tuple.Create(x, y)).FailsToParse("xy", "y", "unsatisfiable expectation expected"); (from x in Next from y in Next from _ in Fail select Tuple.Create(x, y)).FailsToParse("xy", "", "unsatisfiable expectation expected"); } }
mit
C#
c26347249227d17c6ef1594a387580578c2533f9
fix for build 5
sachatrauwaen/openform,sachatrauwaen/openform,sachatrauwaen/openform
AlpacaFormBuilder.ascx.cs
AlpacaFormBuilder.ascx.cs
#region Copyright // // Copyright (c) 2015 // by Satrabel // #endregion #region Using Statements using System; using DotNetNuke.Entities.Modules; using DotNetNuke.Common; using Satrabel.OpenContent.Components; using Satrabel.OpenContent.Components.Alpaca; using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Web.Client; using System.Web.UI.WebControls; #endregion namespace Satrabel.OpenForm { public partial class AlpacaFormBuilder : PortalModuleBase { protected override void OnInit(EventArgs e) { base.OnInit(e); hlCancel.NavigateUrl = Globals.NavigateURL(); cmdSave.NavigateUrl = Globals.NavigateURL(); AlpacaEngine alpaca = new AlpacaEngine(Page, ModuleContext, "" /*settings.Template.Uri().FolderPath*/, "builder"); alpaca.RegisterAll(true); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/OpenForm/js/builder/formbuilder.js", FileOrder.Js.DefaultPriority); ClientResourceManager.RegisterStyleSheet(Page, "~/DesktopModules/OpenForm/js/builder/formbuilder.css", FileOrder.Css.DefaultPriority); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/OpenContent/js/bootstrap/js/bootstrap.min.js", FileOrder.Js.DefaultPriority); ClientResourceManager.RegisterStyleSheet(Page, "~/DesktopModules/OpenContent/js/bootstrap/css/bootstrap.min.css", FileOrder.Css.DefaultPriority); } } }
#region Copyright // // Copyright (c) 2015 // by Satrabel // #endregion #region Using Statements using System; using DotNetNuke.Entities.Modules; using DotNetNuke.Common; using Satrabel.OpenContent.Components; using Satrabel.OpenContent.Components.Alpaca; using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Web.Client; using System.Web.UI.WebControls; #endregion namespace Satrabel.OpenForm { public partial class AlpacaFormBuilder : PortalModuleBase { protected override void OnInit(EventArgs e) { base.OnInit(e); hlCancel.NavigateUrl = Globals.NavigateURL(); cmdSave.NavigateUrl = Globals.NavigateURL(); OpenContentSettings settings = this.OpenContentSettings(); AlpacaEngine alpaca = new AlpacaEngine(Page, ModuleContext, "" /*settings.Template.Uri().FolderPath*/, "builder"); alpaca.RegisterAll(true); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/OpenForm/js/builder/formbuilder.js", FileOrder.Js.DefaultPriority); ClientResourceManager.RegisterStyleSheet(Page, "~/DesktopModules/OpenForm/js/builder/formbuilder.css", FileOrder.Css.DefaultPriority); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/OpenContent/js/bootstrap/js/bootstrap.min.js", FileOrder.Js.DefaultPriority); ClientResourceManager.RegisterStyleSheet(Page, "~/DesktopModules/OpenContent/js/bootstrap/css/bootstrap.min.css", FileOrder.Css.DefaultPriority); } } }
mit
C#
2aa2191be7412b665731beb2cea81f02c7b8a766
Update KelvinTegelaar.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/KelvinTegelaar.cs
src/Firehose.Web/Authors/KelvinTegelaar.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class KelvinTegelaar : IAmAMicrosoftMVP { public string FirstName => "Kelvin"; public string LastName => "Tegelaar"; public string ShortBioOrTagLine => "For every monitoring automation there is an equal PowerShell remediation."; public string StateOrRegion => "Rotterdam, Netherlands"; public string EmailAddress => "ktegelaar@cyberdrain.com"; public string TwitterHandle => "KelvinTegelaar"; public string GitHubHandle => "KelvinTegelaar"; public string GravatarHash => "4dc012d6848c8403805130f2fefcf64b"; public GeoPosition Position => new GeoPosition(51.921638,4.528056); public Uri WebSite => new Uri("https://www.cyberdrain.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.cyberdrain.com/feed.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class KelvinTegelaar : IAmACommunityMember { public string FirstName => "Kelvin"; public string LastName => "Tegelaar"; public string ShortBioOrTagLine => "For every monitoring automation there is an equal PowerShell remediation."; public string StateOrRegion => "Rotterdam, Netherlands"; public string EmailAddress => "ktegelaar@cyberdrain.com"; public string TwitterHandle => "KelvinTegelaar"; public string GitHubHandle => "KelvinTegelaar"; public string GravatarHash => "4dc012d6848c8403805130f2fefcf64b"; public GeoPosition Position => new GeoPosition(51.921638,4.528056); public Uri WebSite => new Uri("https://www.cyberdrain.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.cyberdrain.com/feed/"); } } public string FeedLanguageCode => "en"; } }
mit
C#
fea782a2b3d7c2564798a54f52473dc3bc4c07be
Fix the Coupon resource as percent_off is now a decimal
stripe/stripe-dotnet,richardlawley/stripe.net
src/Stripe.net/Entities/StripeCoupon.cs
src/Stripe.net/Entities/StripeCoupon.cs
namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; public class StripeCoupon : StripeEntityWithId, ISupportMetadata { [JsonProperty("object")] public string Object { get; set; } [JsonProperty("amount_off")] public int? AmountOff { get; set; } [JsonProperty("created")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime Created { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("duration")] public string Duration { get; set; } [JsonProperty("duration_in_months")] public int? DurationInMonths { get; set; } [JsonProperty("livemode")] public bool LiveMode { get; set; } [JsonProperty("max_redemptions")] public int? MaxRedemptions { get; set; } [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("percent_off")] public decimal? PercentOff { get; set; } [JsonProperty("redeem_by")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime? RedeemBy { get; set; } [JsonProperty("times_redeemed")] public int TimesRedeemed { get; private set; } [JsonProperty("valid")] public bool Valid { get; set; } } }
namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; public class StripeCoupon : StripeEntityWithId, ISupportMetadata { [JsonProperty("object")] public string Object { get; set; } [JsonProperty("amount_off")] public int? AmountOff { get; set; } [JsonProperty("created")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime Created { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("duration")] public string Duration { get; set; } [JsonProperty("duration_in_months")] public int? DurationInMonths { get; set; } [JsonProperty("livemode")] public bool LiveMode { get; set; } [JsonProperty("max_redemptions")] public int? MaxRedemptions { get; set; } [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("percent_off")] public int? PercentOff { get; set; } [JsonProperty("redeem_by")] [JsonConverter(typeof(StripeDateTimeConverter))] public DateTime? RedeemBy { get; set; } [JsonProperty("times_redeemed")] public int TimesRedeemed { get; private set; } [JsonProperty("valid")] public bool Valid { get; set; } } }
apache-2.0
C#
61b769f703ec75062b126aa1d997db98066d912e
Fix including links in _Layout.cshtml.
neptuo/com.neptuo.go,neptuo/com.neptuo.go
src/WebSite/Views/Shared/_Layout.cshtml
src/WebSite/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/web.css" rel="stylesheet" /> </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/bootstrap.min.css") @Styles.Render("~/Content/web.css") </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
apache-2.0
C#
9d6dfe5ff9841f946288fab7f4080e57d73d2254
Fix up the AssemblyInfo
tom-overton/fe12-guide-name-tool
Properties/AssemblyInfo.cs
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("FE12GuideNameTool")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FE12GuideNameTool")] [assembly: AssemblyCopyright("Copyright © 2016 Tom Overton")] [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("f42bf98a-7432-48a5-b91f-574bf985b14a")] // 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("FE12GuideNameTool")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FE12GuideNameTool")] [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("f42bf98a-7432-48a5-b91f-574bf985b14a")] // 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#
fe829b0e01b5943f729ed34fbcdf45576dce85a8
Bump version
o11c/WebMConverter,nixxquality/WebMConverter,Yuisbean/WebMConverter
Properties/AssemblyInfo.cs
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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // 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.10.1")]
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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // 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.10.0")]
mit
C#
9eb1f79d15de7257b0634bb5f76431690a4b516e
Increment version number.
rmarinho/babysmash,DavidRieman/babysmash,shanselman/babysmash
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("BabySmash")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Scott Hanselman")] [assembly: AssemblyProduct("BabySmash")] [assembly: AssemblyCopyright("Copyright ©2008 Scott Hanselman")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.2.0")] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("BabySmash")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Scott Hanselman")] [assembly: AssemblyProduct("BabySmash")] [assembly: AssemblyCopyright("Copyright ©2008 Scott Hanselman")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.1.0")] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
mit
C#
8d944cb6c9f4e5c0cfb44663288e332572dba776
Remove out of date docs about precompiled manifest from the example project.
damiensawyer/cassette,andrewdavey/cassette,honestegg/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette,BluewireTechnologies/cassette,damiensawyer/cassette,damiensawyer/cassette
examples/Precompiled/Views/Home/Index.cshtml
examples/Precompiled/Views/Home/Index.cshtml
@{ Layout = null; Bundles.Reference("Content"); Bundles.Reference("Scripts"); } <!DOCTYPE html> <html> <head> <title>Precompiled Cassette Sample</title> @Bundles.RenderStylesheets() @Bundles.RenderScripts() </head> <body> <h1>Compile-time bundling example</h1> <p>This web application is using Cassette's MSBuild task to build the asset bundles at compile time.</p> <p>Take a look at Cassette.targets file, it contains:</p> <pre>&lt;UsingTask TaskName="CreateBundles" AssemblyFile="$(OutputPath)\Cassette.MSBuild.dll" /&gt; &lt;Target Name="Bundle"&gt; &lt;MakeDir Directories="App_Data" /&gt; &lt;CreateBundles Input="$(OutputPath)" Output="App_Data\cassette.xml" /&gt; &lt;/Target&gt;</pre> <p> After the web application project is built, the <code>CreateBundles</code> task is run. This executes the <code>CassetteConfiguration</code> and generates all the application's bundles. The output of this is saved to a file in App_Data. </p> <p>Then in the Web.config file, there is this:</p> <pre>&lt;configuration&gt; &lt;configSections&gt; &lt;section name="cassette" type="Cassette.Configuration.CassetteConfigurationSection"/&gt; &lt;/configSections&gt; &lt;cassette precompiledManifest="App_Data/cassette.xml"/&gt; ... &lt;/configuration&gt;</pre> <p>When the web application starts, Cassette will load the pre-compiled bundles from the file in App_Data. This removes just about all of Cassette's start-up overhead.</p> </body> </html>
@{ Layout = null; Bundles.Reference("Content"); Bundles.Reference("Scripts"); } <!DOCTYPE html> <html> <head> <title>Precompiled Cassette Sample</title> @Bundles.RenderStylesheets() @Bundles.RenderScripts() </head> <body> <h1>Compile-time bundling example</h1> <p>This web application is using Cassette's MSBuild task to build the asset bundles at compile time.</p> <p>Take a look at the Precompiled.csproj file, it contains the following addition:</p> <pre>&lt;UsingTask TaskName="CreateBundles" AssemblyFile="..\..\src\Cassette.MSBuild\bin\$(Configuration)\Cassette.MSBuild.dll" /&gt; &lt;Target Name="CreateBundles" AfterTargets="AfterBuild"&gt; &lt;CreateBundles Input="$(OutputPath)" Output="App_Data\cassette.xml" /&gt; &lt;/Target&gt;</pre> <p> After the web application project is built, the <code>CreateBundles</code> task is run. This executes the <code>CassetteConfiguration</code> and generates all the application's bundles. The output of this is saved to a file in App_Data. </p> <p>Then in the Web.config file, there is this:</p> <pre>&lt;configuration&gt; &lt;configSections&gt; &lt;section name="cassette" type="Cassette.Configuration.CassetteConfigurationSection"/&gt; &lt;/configSections&gt; &lt;cassette precompiledManifest="App_Data/cassette.xml"/&gt; ... &lt;/configuration&gt;</pre> <p>When the web application starts, Cassette will load the pre-compiled bundles from the file in App_Data. This removes just about all of Cassette's start-up overhead.</p> <h2>Important CassetteConfiguration Note</h2> <p>The application's <code>CassetteConfiguration</code> is used at both compile-time and run-time.</p> <p>However, at runtime the bundles will be added from the manifest, so you MUST NOT try to add them in the configuration. Use the following code to handle this scenario:</p> <pre>public class CassetteConfiguration : ICassetteConfiguration { public void Configure(BundleCollection bundles, CassetteSettings settings) { // Put any code that runs at both compile-time and run-time here. // For example, assigning settings.UrlModifier <strong>if (settings.IsUsingPrecompiledManifest) return;</strong> // Add your bundles here - this only runs at compile-time. bundles.Add&lt;StylesheetBundle&gt;("Content"); bundles.Add&lt;ScriptBundle&gt;("Scripts"); } }</pre> </body> </html>
mit
C#