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
4abb9b86460f90e11b84b10d2846533b8a0914d6
Bump version to 3.2.
jcheng31/DarkSkyApi,jcheng31/ForecastPCL
DarkSkyApi/Properties/AssemblyInfo.cs
DarkSkyApi/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("DarkSkyApi")] [assembly: AssemblyDescription("An unofficial PCL for the Dark Sky weather API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jerome Cheng")] [assembly: AssemblyProduct("DarkSkyApi")] [assembly: AssemblyCopyright("")] [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("3.2.0.0")] [assembly: AssemblyFileVersion("3.2.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("DarkSkyApi")] [assembly: AssemblyDescription("An unofficial PCL for the Dark Sky weather API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jerome Cheng")] [assembly: AssemblyProduct("DarkSkyApi")] [assembly: AssemblyCopyright("")] [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("3.1.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")]
mit
C#
be3359c38b61396df912c15515987ed846231275
read me add image
cythilya/Dotchi,cythilya/Dotchi,cythilya/Dotchi
Dotchi/Dotchi/Views/Home/Index.cshtml
Dotchi/Dotchi/Views/Home/Index.cshtml
@{ Layout = "~/Views/Shared/_Layout.cshtml"; } <div id="index" class="dotch"> <div class="main"> <h1>吃什麼,どっち</h1> <h2>讓朋友幫你決定吃什麼</h2> <div class="inputArea"> <input type="text" class="query" placeholder="請輸入你的美食欲望,例:台北市中山區 火鍋" /> </div> <a href="#" class="button search"><span>尋找餐廳</span></a> <a href="#" class="button fb"><span>看看朋友吃什麼?</span></a> @*<img src="/Content/dotchi/img/step.png" alt="">*@ </div> </div>
@{ Layout = "~/Views/Shared/_Layout.cshtml"; } <div id="index" class="dotch"> <div class="main"> <h1>吃什麼,どっち</h1> <h2>讓朋友幫你決定吃什麼</h2> <div class="inputArea"> <input type="text" class="query" placeholder="請輸入你的美食欲望,例:台北市中山區 火鍋" /> </div> <a href="#" class="button search"><span>尋找餐廳</span></a> <a href="#" class="button fb"><span>看看朋友吃什麼?</span></a> <img src="/Content/dotchi/img/step.png" alt=""> </div> </div>
mit
C#
20c357be01bb6dc79e40fde9a2139c8d985ce2bb
Remove debug logs
flagbug/Espera,punker76/Espera
Espera/Espera.Core/Audio/VlcPlayer.cs
Espera/Espera.Core/Audio/VlcPlayer.cs
using System; using Vlc.DotNet.Core; using Vlc.DotNet.Core.Medias; using Vlc.DotNet.Wpf; namespace Espera.Core.Audio { internal class VlcPlayer : IDisposable { private readonly VlcControl player; public VlcPlayer() { if (Environment.Is64BitOperatingSystem) { VlcContext.LibVlcDllsPath = CommonStrings.LIBVLC_DLLS_PATH_DEFAULT_VALUE_AMD64; VlcContext.LibVlcPluginsPath = CommonStrings.PLUGINS_PATH_DEFAULT_VALUE_AMD64; } else { VlcContext.LibVlcDllsPath = CommonStrings.LIBVLC_DLLS_PATH_DEFAULT_VALUE_X86; VlcContext.LibVlcPluginsPath = CommonStrings.PLUGINS_PATH_DEFAULT_VALUE_X86; } VlcContext.StartupOptions.IgnoreConfig = true; VlcContext.Initialize(); this.player = new VlcControl(); } public void Play(string url) { var media = new LocationMedia(url); this.player.Media = media; this.player.Play(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { VlcContext.CloseAll(); } } }
using System; using Vlc.DotNet.Core; using Vlc.DotNet.Core.Medias; using Vlc.DotNet.Wpf; namespace Espera.Core.Audio { internal class VlcPlayer : IDisposable { private readonly VlcControl player; public VlcPlayer() { if (Environment.Is64BitOperatingSystem) { VlcContext.LibVlcDllsPath = CommonStrings.LIBVLC_DLLS_PATH_DEFAULT_VALUE_AMD64; VlcContext.LibVlcPluginsPath = CommonStrings.PLUGINS_PATH_DEFAULT_VALUE_AMD64; } else { VlcContext.LibVlcDllsPath = CommonStrings.LIBVLC_DLLS_PATH_DEFAULT_VALUE_X86; VlcContext.LibVlcPluginsPath = CommonStrings.PLUGINS_PATH_DEFAULT_VALUE_X86; } //Set the startup options VlcContext.StartupOptions.IgnoreConfig = true; VlcContext.StartupOptions.LogOptions.LogInFile = true; VlcContext.StartupOptions.LogOptions.ShowLoggerConsole = true; VlcContext.StartupOptions.LogOptions.Verbosity = VlcLogVerbosities.Debug; //Initialize the VlcContext VlcContext.Initialize(); this.player = new VlcControl(); } public void Play(string url) { var media = new LocationMedia(url); this.player.Media = media; this.player.Play(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { VlcContext.CloseAll(); } } }
mit
C#
cbde5b30633a599e8535f53ecd2e3e56e2d78f1a
Update Indentation.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/Formatting/ConfiguringAlignmentSettings/Indentation.cs
Examples/CSharp/Formatting/ConfiguringAlignmentSettings/Indentation.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Formatting.ConfiguringAlignmentSettings { public class Indentation { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Obtaining the reference of the worksheet Worksheet worksheet = workbook.Worksheets[0]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Visit Aspose!"); //Setting the horizontal alignment of the text in the "A1" cell Style style = cell.GetStyle(); //Setting the indentation level of the text (inside the cell) to 2 style.IndentLevel = 2; cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Formatting.ConfiguringAlignmentSettings { public class Indentation { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Obtaining the reference of the worksheet Worksheet worksheet = workbook.Worksheets[0]; //Accessing the "A1" cell from the worksheet Aspose.Cells.Cell cell = worksheet.Cells["A1"]; //Adding some value to the "A1" cell cell.PutValue("Visit Aspose!"); //Setting the horizontal alignment of the text in the "A1" cell Style style = cell.GetStyle(); //Setting the indentation level of the text (inside the cell) to 2 style.IndentLevel = 2; cell.SetStyle(style); //Saving the Excel file workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); } } }
mit
C#
c0d5d13968b9e2de9a28945050452c044ab2cfe8
connect and disconnect #46
richardschneider/net-ipfs-core
src/CoreApi/ISwarmApi.cs
src/CoreApi/ISwarmApi.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ipfs.CoreApi { /// <summary> /// Manages the swarm of peers. /// </summary> /// <remarks> /// The swarm is a sequence of connected peer nodes. /// </remarks> /// <seealso href="https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/SWARM.md">Swarm API spec</seealso> public interface ISwarmApi { /// <summary> /// Get the peers in the current swarm. /// </summary> /// <param name="cancel"> /// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised. /// </param> /// <returns> /// A task that represents the asynchronous operation. The task's value /// is a sequence of peer nodes. /// </returns> Task<IEnumerable<Peer>> AddressesAsync(CancellationToken cancel = default(CancellationToken)); /// <summary> /// Get the peers that are connected to this node. /// </summary> /// <param name="cancel"> /// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised. /// </param> /// <returns> /// A task that represents the asynchronous operation. The task's value /// is a sequence of <see cref="Peer">Connected Peers</see>. /// </returns> Task<IEnumerable<Peer>> PeersAsync(CancellationToken cancel = default(CancellationToken)); /// <summary> /// Connect to a peer. /// </summary> /// <param name="address"> /// An ipfs <see cref="MultiAddress"/>, such as /// <c>/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ</c>. /// </param> /// <param name="cancel"> /// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised. /// </param> Task ConnectAsync(MultiAddress address, CancellationToken cancel = default(CancellationToken)); /// <summary> /// Disconnect from a peer. /// </summary> /// <param name="address"> /// An ipfs <see cref="MultiAddress"/>, such as /// <c>/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ</c>. /// </param> /// <param name="cancel"> /// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised. /// </param> Task DisconnectAsync(MultiAddress address, CancellationToken cancel = default(CancellationToken)); } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ipfs.CoreApi { /// <summary> /// Manages the swarm of peers. /// </summary> /// <remarks> /// The swarm is a sequence of connected peer nodes. /// </remarks> /// <seealso href="https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/SWARM.md">Swarm API spec</seealso> public interface ISwarmApi { /// <summary> /// Get the peers in the current swarm. /// </summary> /// <param name="cancel"> /// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised. /// </param> /// <returns> /// A task that represents the asynchronous operation. The task's value /// is a sequence of peer nodes. /// </returns> Task<IEnumerable<Peer>> AddressesAsync(CancellationToken cancel = default(CancellationToken)); /// <summary> /// Get the peers that are connected to this node. /// </summary> /// <param name="cancel"> /// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised. /// </param> /// <returns> /// A task that represents the asynchronous operation. The task's value /// is a sequence of <see cref="Peer">Connected Peers</see>. /// </returns> Task<IEnumerable<Peer>> PeersAsync(CancellationToken cancel = default(CancellationToken)); } }
mit
C#
afe6018bc66f306f4902c5d0727ccc73336d2460
Update TypeClassMonad.cs
louthy/language-ext,StefanBertels/language-ext,StanJav/language-ext
LanguageExt.Tests/TypeClassMonad.cs
LanguageExt.Tests/TypeClassMonad.cs
using Xunit; using System.Linq; using LanguageExt.TypeClasses; using LanguageExt.ClassInstances; using static LanguageExt.Prelude; using static LanguageExt.TypeClass; using LanguageExt; namespace LanguageExtTests { public class TypeClassMonad { [Fact] public void MonadReturnTest() { Option<int> x = DoubleAndLift<MOption<int>, Option<int>, TInt, int>(100); Assert.True(x.IfNone(0) == 200); } public static MA DoubleAndLift<MONAD, MA, NUM, A>(A num) where MONAD : struct, Monad<MA, A> where NUM : struct, Num<A> => Return<MONAD, MA, A>(product<NUM, A>(num, fromInteger<NUM, A>(2))); } }
using Xunit; using System.Linq; using LanguageExt.TypeClasses; using LanguageExt.ClassInstances; using static LanguageExt.Prelude; using static LanguageExt.TypeClass; using LanguageExt; namespace LanguageExtTests { public class TypeClassMonad { [Fact] public void MonadReturnTest() { var x = DoubleAndLift<MOption<int>, Option<int>, TInt, int>(100); Assert.True(x.IfNone(0) == 200); } public static MA DoubleAndLift<MONAD, MA, NUM, A>(A num) where MONAD : struct, Monad<MA, A> where NUM : struct, Num<A> => Return<MONAD, MA, A>(product<NUM, A>(num, fromInteger<NUM, A>(2))); } }
mit
C#
e1a22724829831a111147c78c1c44bf7e13dfd23
fix for GA
autumn009/TanoCSharpSamples
Chap37/ImprovedDefiniteAssignment/ImprovedDefiniteAssignment/Program.cs
Chap37/ImprovedDefiniteAssignment/ImprovedDefiniteAssignment/Program.cs
using System; MyClass c = new MyClass(); if ((c != null && c.MyMethod(out object obj1))) { // obj1は初期化済みと見抜ける Console.WriteLine(obj1.ToString()); } if ((c != null && c.MyMethod(out object obj2)) == true) { // obj2は初期化済みと見抜けない→見抜ける Console.WriteLine(obj2.ToString()); } public class MyClass { public bool MyMethod(out object obj) { obj = "hello"; return true; } }
MyClass c = new MyClass(); if ((c != null && c.MyMethod(out object obj1))) { // obj1は初期化済みと見抜ける Console.WriteLine(obj1.ToString()); } if ((c != null && c.MyMethod(out object obj2)) == true) { // obj2は初期化済みと見抜けない→見抜ける Console.WriteLine(obj2.ToString()); } public class MyClass { public bool MyMethod(out object obj) { obj = "hello"; return true; } }
mit
C#
2339765af633aee18b7321f629a11cf527b32380
Add more words that can be used to indicate that you are submitting your answer.
samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays
Assets/Scripts/ComponentSolvers/Modded/Misc/ColorMorseComponentSolver.cs
Assets/Scripts/ComponentSolvers/Modded/Misc/ColorMorseComponentSolver.cs
using System; using System.Linq; using System.Reflection; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ColorMorseComponentSolver : ComponentSolver { public ColorMorseComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) : base(bombCommander, bombComponent, ircConnection, canceller) { _buttons = (KMSelectable[]) _buttonsField.GetValue(bombComponent.GetComponent(_componentType)); modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType()); } protected override IEnumerator RespondToCommandInternal(string inputCommand) { var commands = inputCommand.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (commands.Length >= 2 && ValidSubmitWords.Any(x => x.Equals(commands[0]))) { List<int> buttonIndexes = new List<int>(); foreach (string morse in commands.Skip(1)) { foreach (char character in morse) { int index = 0; switch (character) { case '.': index = 0; break; case '-': index = 1; break; default: yield break; } buttonIndexes.Add(index); } buttonIndexes.Add(2); } foreach (int index in buttonIndexes.Take(buttonIndexes.Count - 1)) { yield return DoInteractionClick(_buttons[index]); } } } static ColorMorseComponentSolver() { _componentType = ReflectionHelper.FindType("FlashingMathModule"); _buttonsField = _componentType.GetField("Buttons"); } private static readonly string[] ValidSubmitWords = { "transmit", "submit", "trans", "tx", "xmit" }; private static Type _componentType = null; private static FieldInfo _buttonsField = null; private KMSelectable[] _buttons = null; }
using System; using System.Linq; using System.Reflection; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ColorMorseComponentSolver : ComponentSolver { public ColorMorseComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) : base(bombCommander, bombComponent, ircConnection, canceller) { _buttons = (KMSelectable[]) _buttonsField.GetValue(bombComponent.GetComponent(_componentType)); modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType()); } protected override IEnumerator RespondToCommandInternal(string inputCommand) { var commands = inputCommand.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (commands.Length >= 2 && (commands[0] == "submit" || commands[0] == "transmit")) { List<int> buttonIndexes = new List<int>(); foreach (string morse in commands.Skip(1)) { foreach (char character in morse) { int index = 0; switch (character) { case '.': index = 0; break; case '-': index = 1; break; default: yield break; } buttonIndexes.Add(index); } buttonIndexes.Add(2); } foreach (int index in buttonIndexes.Take(buttonIndexes.Count - 1)) { yield return DoInteractionClick(_buttons[index]); } } } static ColorMorseComponentSolver() { _componentType = ReflectionHelper.FindType("FlashingMathModule"); _buttonsField = _componentType.GetField("Buttons"); } private static Type _componentType = null; private static FieldInfo _buttonsField = null; private KMSelectable[] _buttons = null; }
mit
C#
61c1a4910487fca0e681c0846cee0211351680be
use registry
quandl/quandl-excel-windows
QuandlShared/QuandlConfig.cs
QuandlShared/QuandlConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace Quandl.Shared { public class QuandlConfig { private const string RegistrySubKey = @"SOFTWARE\Quandl\ExcelAddin"; public static string ApiKey { get { return GetRegistry<string>("ApiKey"); } set { SetRegistryKeyValue("ApiKey", value); } } public static bool AutoUpdate { get { return Convert.ToBoolean(GetRegistry<int>("AutoUpdate")); } set { SetRegistryKeyValue("AutoUpdate", Convert.ToInt32(value), RegistryValueKind.DWord); } } public static void Reset() { Registry.CurrentUser.DeleteSubKeyTree(RegistrySubKey); } private static void SetRegistryKeyValue(string key, object value, RegistryValueKind regValueKing = RegistryValueKind.String) { var appKeyPath = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(RegistrySubKey); var apiSubKey = appKeyPath.CreateSubKey(key); apiSubKey.SetValue(key, value, regValueKing); apiSubKey.Close(); } private static T GetRegistry<T>(string key) { var quandlRootKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistrySubKey); if (quandlRootKey != null) { var subKey = quandlRootKey.OpenSubKey(key); if (subKey != null) { return (T)subKey.GetValue(key, default(T)); } } return default(T); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quandl.Shared { public class QuandlConfig { public static string ApiKey { get { return Properties.Settings.Default.ApiKey; } set { Properties.Settings.Default.ApiKey = value; Properties.Settings.Default.Save(); } } public static bool AutoUpdate { get { return Properties.Settings.Default.AutoUpdate; } set { Properties.Settings.Default.AutoUpdate = value; Properties.Settings.Default.Save(); } } public static void Reset() { Properties.Settings.Default.Reset(); } } }
mit
C#
b41726668440d58c48f38ae623c94711cc9cf980
Change formatting to match C# style
versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla
VersionOne.ServiceHost.ConfigurationTool/Entities/VersionOneSettings.cs
VersionOne.ServiceHost.ConfigurationTool/Entities/VersionOneSettings.cs
using System.Xml.Serialization; using VersionOne.ServiceHost.ConfigurationTool.Validation; using VersionOne.ServiceHost.ConfigurationTool.Attributes; namespace VersionOne.ServiceHost.ConfigurationTool.Entities { /// <summary> /// VersionOne connection settings node backing class. /// </summary> [XmlRoot("Settings")] public class VersionOneSettings { public const string ApplicationUrlProperty = "ApplicationUrl"; public const string UsernameProperty = "Username"; public const string PasswordProperty = "Password"; public const string IntegratedAuthProperty = "IntegratedAuth"; public VersionOneSettings() { ProxySettings = new ProxyConnectionSettings(); } [XmlElement("APIVersion")] public string ApiVersion { get { return "7.2.0.0"; } set { } } [HelpString(HelpResourceKey = "V1PageVersionOneUrl")] [NonEmptyStringValidator] public string ApplicationUrl { get; set; } [NonEmptyStringValidator] public string Username { get; set; } [NonEmptyStringValidator] public string Password { get; set; } [HelpString(HelpResourceKey = "V1PageIntegratedAuth")] public bool IntegratedAuth { get; set; } public ProxyConnectionSettings ProxySettings { get; set; } } }
using System.Xml.Serialization; using VersionOne.ServiceHost.ConfigurationTool.Validation; using VersionOne.ServiceHost.ConfigurationTool.Attributes; namespace VersionOne.ServiceHost.ConfigurationTool.Entities { /// <summary> /// VersionOne connection settings node backing class. /// </summary> [XmlRoot("Settings")] public class VersionOneSettings { public const string ApplicationUrlProperty = "ApplicationUrl"; public const string UsernameProperty = "Username"; public const string PasswordProperty = "Password"; public const string IntegratedAuthProperty = "IntegratedAuth"; public VersionOneSettings() { ProxySettings = new ProxyConnectionSettings(); } [XmlElement("APIVersion")] public string ApiVersion { get { return "7.2.0.0"; } set { } } [HelpString(HelpResourceKey="V1PageVersionOneUrl")] [NonEmptyStringValidator] public string ApplicationUrl { get; set; } [NonEmptyStringValidator] public string Username { get; set; } [NonEmptyStringValidator] public string Password { get; set; } [HelpString(HelpResourceKey="V1PageIntegratedAuth")] public bool IntegratedAuth { get; set; } public ProxyConnectionSettings ProxySettings { get; set; } } }
bsd-3-clause
C#
967ca1f9bc6183da785ba668da16e4a7652dedbc
Add ISavable to IBusinessBase
MarimerLLC/csla,rockfordlhotka/csla,jonnybee/csla,JasonBock/csla,jonnybee/csla,ronnymgm/csla-light,BrettJaner/csla,ronnymgm/csla-light,rockfordlhotka/csla,JasonBock/csla,BrettJaner/csla,MarimerLLC/csla,JasonBock/csla,ronnymgm/csla-light,BrettJaner/csla,jonnybee/csla,rockfordlhotka/csla,MarimerLLC/csla
Source/Csla/IBusinessBase.cs
Source/Csla/IBusinessBase.cs
using System; using Csla.Core; using System.ComponentModel; using Csla.Security; using Csla.Rules; using Csla.Serialization.Mobile; namespace Csla { /// <summary> /// Consolidated interface of public elements from the /// BusinessBase type. /// </summary> public interface IBusinessBase : IBusinessObject, IEditableBusinessObject, IEditableObject, ICloneable, ISavable, IAuthorizeReadWrite, IParent, IHostRules, ICheckRules, INotifyBusy, INotifyChildChanged, ISerializationNotification #if (SILVERLIGHT || NETFX_CORE) && !__ANDROID__ && !IOS ,INotifyDataErrorInfo #else , IDataErrorInfo #endif { } }
using System; using Csla.Core; using System.ComponentModel; using Csla.Security; using Csla.Rules; using Csla.Serialization.Mobile; namespace Csla { /// <summary> /// Consolidated interface of public elements from the /// BusinessBase type. /// </summary> public interface IBusinessBase : IBusinessObject, IEditableBusinessObject, IEditableObject, ICloneable, IAuthorizeReadWrite, IParent, IHostRules, ICheckRules, INotifyBusy, INotifyChildChanged, ISerializationNotification #if (SILVERLIGHT || NETFX_CORE) && !__ANDROID__ && !IOS ,INotifyDataErrorInfo #else , IDataErrorInfo #endif { } }
mit
C#
958451694cf4c7c45d7064363d4f83137ffaa16a
Update dev version to 3.0.0
Ixonos-USA/SharpDX,davidlee80/SharpDX-1,jwollen/SharpDX,manu-silicon/SharpDX,manu-silicon/SharpDX,RobyDX/SharpDX,dazerdude/SharpDX,mrvux/SharpDX,waltdestler/SharpDX,PavelBrokhman/SharpDX,PavelBrokhman/SharpDX,fmarrabal/SharpDX,waltdestler/SharpDX,mrvux/SharpDX,TechPriest/SharpDX,jwollen/SharpDX,dazerdude/SharpDX,andrewst/SharpDX,TechPriest/SharpDX,manu-silicon/SharpDX,waltdestler/SharpDX,TigerKO/SharpDX,weltkante/SharpDX,sharpdx/SharpDX,PavelBrokhman/SharpDX,sharpdx/SharpDX,Ixonos-USA/SharpDX,fmarrabal/SharpDX,weltkante/SharpDX,manu-silicon/SharpDX,davidlee80/SharpDX-1,davidlee80/SharpDX-1,sharpdx/SharpDX,mrvux/SharpDX,dazerdude/SharpDX,fmarrabal/SharpDX,andrewst/SharpDX,weltkante/SharpDX,weltkante/SharpDX,davidlee80/SharpDX-1,waltdestler/SharpDX,RobyDX/SharpDX,Ixonos-USA/SharpDX,Ixonos-USA/SharpDX,PavelBrokhman/SharpDX,dazerdude/SharpDX,andrewst/SharpDX,TechPriest/SharpDX,TigerKO/SharpDX,TigerKO/SharpDX,RobyDX/SharpDX,TigerKO/SharpDX,TechPriest/SharpDX,RobyDX/SharpDX,jwollen/SharpDX,fmarrabal/SharpDX,jwollen/SharpDX
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.cs
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly:AssemblyCompany("Alexandre Mutel")] [assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly:AssemblyVersion("3.0.0")] [assembly:AssemblyFileVersion("3.0.0")] [assembly: NeutralResourcesLanguage("en-us")] #if DEBUG [assembly:AssemblyConfiguration("Debug")] #else [assembly:AssemblyConfiguration("Release")] #endif [assembly:ComVisible(false)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)] [assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)]
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly:AssemblyCompany("Alexandre Mutel")] [assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly:AssemblyVersion("2.6.3")] [assembly:AssemblyFileVersion("2.6.3")] [assembly: NeutralResourcesLanguage("en-us")] #if DEBUG [assembly:AssemblyConfiguration("Debug")] #else [assembly:AssemblyConfiguration("Release")] #endif [assembly:ComVisible(false)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)] [assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)] [assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)] [assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)]
mit
C#
bd03df5f9be05306da6f161017a7aeb39b497da5
Create const for targetdir key
tvdburgt/subtle
Subtle.Registry/Installer.cs
Subtle.Registry/Installer.cs
using Subtle.Model; using System.Collections; using System.ComponentModel; using System.Configuration.Install; using System.IO; namespace Subtle.Registry { [RunInstaller(true)] public partial class Installer : System.Configuration.Install.Installer { private const string TargetDirKey = "targetdir"; public Installer() { InitializeComponent(); } public override void Commit(IDictionary savedState) { base.Commit(savedState); if (!Context.Parameters.ContainsKey(TargetDirKey)) { throw new InstallException($"Missing '{TargetDirKey}' parameter"); } var targetDir = Context.Parameters[TargetDirKey].TrimEnd(Path.DirectorySeparatorChar); RegistryHelper.SetShellCommands( FileTypes.VideoTypes, Path.Combine(targetDir, "Subtle.exe"), Path.Combine(targetDir, "Subtle.ico")); } public override void Rollback(IDictionary savedState) { base.Rollback(savedState); //RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes); } } }
using Subtle.Model; using System.Collections; using System.ComponentModel; using System.Configuration.Install; using System.IO; namespace Subtle.Registry { [RunInstaller(true)] public partial class Installer : System.Configuration.Install.Installer { public Installer() { InitializeComponent(); } public override void Commit(IDictionary savedState) { base.Commit(savedState); if (!Context.Parameters.ContainsKey("targetdir")) { throw new InstallException("Missing 'targetdir' parameter"); } var targetDir = Context.Parameters["targetdir"].TrimEnd(Path.DirectorySeparatorChar); RegistryHelper.SetShellCommands( FileTypes.VideoTypes, Path.Combine(targetDir, "Subtle.exe"), Path.Combine(targetDir, "Subtle.ico")); } public override void Rollback(IDictionary savedState) { base.Rollback(savedState); //RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes); } } }
mit
C#
cc5f09d32bb3b8a962d79cd8c4707a18a7ba865e
remove test
wilcommerce/Wilcommerce.Catalog.Data.EFCore
Wilcommerce.Catalog.Data.EFCore.Test/ReadModels/CatalogDatabaseTest.cs
Wilcommerce.Catalog.Data.EFCore.Test/ReadModels/CatalogDatabaseTest.cs
using System.Linq; using Wilcommerce.Catalog.Data.EFCore.ReadModels; using Wilcommerce.Catalog.Data.EFCore.Test.Fixtures; using Wilcommerce.Catalog.ReadModels; using Xunit; namespace Wilcommerce.Catalog.Data.EFCore.Test.ReadModels { public class CatalogDatabaseTest : IClassFixture<CatalogContextFixture> { private CatalogContextFixture _fixture; private CatalogDatabase _database; public CatalogDatabaseTest(CatalogContextFixture fixture) { _fixture = fixture; _database = new CatalogDatabase(_fixture.Context); } [Fact] public void Products_Must_Have_AtLeast_One_Record() { var products = _database.Products; Assert.NotEmpty(products); } [Fact] public void CustomAttributes_Must_Contains_A_Color_Attribute() { var attribute = _database.CustomAttributes.Any(a => a.Name == "color"); Assert.True(attribute); } } }
using System.Linq; using Wilcommerce.Catalog.Data.EFCore.ReadModels; using Wilcommerce.Catalog.Data.EFCore.Test.Fixtures; using Wilcommerce.Catalog.ReadModels; using Xunit; namespace Wilcommerce.Catalog.Data.EFCore.Test.ReadModels { public class CatalogDatabaseTest : IClassFixture<CatalogContextFixture> { private CatalogContextFixture _fixture; private CatalogDatabase _database; public CatalogDatabaseTest(CatalogContextFixture fixture) { _fixture = fixture; _database = new CatalogDatabase(_fixture.Context); } [Fact] public void Products_Must_Have_AtLeast_One_Record() { var products = _database.Products; Assert.NotEmpty(products); } [Fact] public void CustomAttributes_Must_Contains_A_Color_Attribute() { var attribute = _database.CustomAttributes.Any(a => a.Name == "color"); Assert.True(attribute); } [Fact] public void Product_Must_Contains_TierPrices() { var product = _database.Products.FirstOrDefault(p => p.TierPriceEnabled && p.TierPrices.Any()); Assert.NotNull(product); Assert.True(product.TierPrices.Any()); } } }
mit
C#
4dffedf5b190720bd70f060c98f666bc56e2c57a
Switch to version 1.2.7
Abc-Arbitrage/Zebus,Abc-Arbitrage/Zebus.Directory
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.2.7")] [assembly: AssemblyFileVersion("1.2.7")] [assembly: AssemblyInformationalVersion("1.2.7")]
using System.Reflection; [assembly: AssemblyVersion("1.2.6")] [assembly: AssemblyFileVersion("1.2.6")] [assembly: AssemblyInformationalVersion("1.2.6")]
mit
C#
aaf0b3ef16e9ff089f002d393c07dba120a88bbc
Fix AppVeyor
lecaillon/Evolve
test/Evolve.Test/DatabaseFixture.cs
test/Evolve.Test/DatabaseFixture.cs
using System; using System.Threading; using Evolve.Test.Utilities; using Xunit; namespace Evolve.Test { public class DatabaseFixture : IDisposable { public DatabaseFixture() { MySql = new MySqlDockerContainer(); MsSql = new MsSqlDockerContainer(); Pg = new PostgreSqlDockerContainer(); #if DEBUG MySql.Start(); MsSql.Start(); Pg.Start(); Thread.Sleep(10000); #endif } public MySqlDockerContainer MySql { get; } public MsSqlDockerContainer MsSql { get; } public PostgreSqlDockerContainer Pg { get; } public void Dispose() { #if DEBUG MySql.Dispose(); MsSql.Dispose(); Pg.Dispose(); #endif } } [CollectionDefinition("Database collection")] public class DatabaseCollection : ICollectionFixture<DatabaseFixture> { } }
using System; using System.Threading; using Evolve.Test.Utilities; using Xunit; namespace Evolve.Test { public class DatabaseFixture : IDisposable { public DatabaseFixture() { #if DEBUG MySql = new MySqlDockerContainer(); MySql.Start(); MsSql = new MsSqlDockerContainer(); MsSql.Start(); Pg = new PostgreSqlDockerContainer(); Pg.Start(); Thread.Sleep(10000); #endif } public MySqlDockerContainer MySql { get; } public MsSqlDockerContainer MsSql { get; } public PostgreSqlDockerContainer Pg { get; } public void Dispose() { #if DEBUG MySql.Dispose(); MsSql.Dispose(); Pg.Dispose(); #endif } } [CollectionDefinition("Database collection")] public class DatabaseCollection : ICollectionFixture<DatabaseFixture> { } }
mit
C#
3536760f9fa3278014d83ce43f04a90a18d5374f
Change redirecturi to tryfunctionspage
projectkudu/TryAppService,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS
SimpleWAWS/Authentication/GoogleAuthProvider.cs
SimpleWAWS/Authentication/GoogleAuthProvider.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); //TODO:Add a whitelisted location list if (context.IsFunctionsPortalRequest()) { builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}/?Login=true", context.Request.Headers["Origin"]))); } else { builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); } builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()|| context.IsFunctionsPortalRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()|| context.IsFunctionsPortalRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
apache-2.0
C#
46e970c91d9f148c24551d605124fe9e7a289223
adjust code.
Roommetro/Friendly.WPFStandardControls,Roommetro/Friendly.WPFStandardControls
Project/Test/CaptureTest/Capture.cs
Project/Test/CaptureTest/Capture.cs
using Codeer.Friendly.Windows; namespace Test.CaptureTest { public class Capture { WindowsAppFriend app = null; public void Test() { } } }
using Codeer.Friendly.Dynamic; using Codeer.Friendly.Windows; using Codeer.Friendly.Windows.Grasp; using RM.Friendly.WPFStandardControls; using System.Windows; using Test.CaptureTest; namespace Test.CaptureTest { public class Capture { WindowsAppFriend app = null; public void Test() { } } }
apache-2.0
C#
1950126ebe49154bdc8f33239915fc62e869d7dd
Rename parameter
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/LiteNetLibMessageHandler.cs
Scripts/LiteNetLibMessageHandler.cs
using LiteNetLib; using LiteNetLib.Utils; namespace LiteNetLibManager { public class LiteNetLibMessageHandler { public ushort msgType { get; private set; } public TransportHandler transportHandler { get; private set; } public long connectionId { get; private set; } public NetDataReader reader { get; private set; } public LiteNetLibMessageHandler(ushort msgType, TransportHandler transportHandler, long connectionId, NetDataReader reader) { this.msgType = msgType; this.transportHandler = transportHandler; this.connectionId = connectionId; this.reader = reader; } public T ReadMessage<T>() where T : INetSerializable, new() { T msg = new T(); msg.Deserialize(reader); return msg; } public void ReadMessage<T>(T msg) where T : INetSerializable { msg.Deserialize(reader); } } }
using LiteNetLib; using LiteNetLib.Utils; namespace LiteNetLibManager { public class LiteNetLibMessageHandler { public ushort msgType { get; private set; } public TransportHandler transportHandler { get; private set; } public long connectionId { get; private set; } public NetDataReader reader { get; private set; } public LiteNetLibMessageHandler(ushort msgType, TransportHandler peerHandler, long connectionId, NetDataReader reader) { this.msgType = msgType; this.transportHandler = peerHandler; this.connectionId = connectionId; this.reader = reader; } public T ReadMessage<T>() where T : INetSerializable, new() { T msg = new T(); msg.Deserialize(reader); return msg; } public void ReadMessage<T>(T msg) where T : INetSerializable { msg.Deserialize(reader); } } }
mit
C#
7154731be49c9d874e05394bc75ccedc9f402c6c
Use exposed property rather than internal.
Ecu/Part-System
Part.cs
Part.cs
using UnityEngine; using System.Collections; [DisallowMultipleComponent] [ExecuteInEditMode] public class Part : MonoBehaviour { [SerializeField] private GameObject _collection = null; [SerializeField] private float _frame = 0.0f; private bool changed = false; public string part { get { if (_collection == null || frame == 0) { return "None"; } else { return _collection.transform.GetChild (frame - 1).gameObject.name; } } set { value = value.Replace (" ", "_"); if (_collection == null || value == "None") { frame = 0; } else { int index = _collection.transform.FindChild (value).GetSiblingIndex (); if (index != -1) { frame = index + 1; } else { frame = 0; } } } } public int frame { get { return Mathf.FloorToInt (_frame); } set { _frame = (float)value; changed = true; } } void OnValidate () { changed = true; } void OnDidApplyAnimationProperties () { changed = true; } void Update () { if (changed) { changed = false; MeshFilter meshFilter = GetComponent<MeshFilter> (); MeshRenderer meshRenderer = GetComponent<MeshRenderer> (); if (_collection != null && frame != 0) { GameObject found = _collection.transform.GetChild (frame - 1).gameObject; meshFilter.mesh = found.GetComponent<MeshFilter> ().sharedMesh; meshRenderer.material = found.GetComponent<MeshRenderer> ().sharedMaterial; } else { meshFilter.mesh = null; meshRenderer.material = null; } } } }
using UnityEngine; using System.Collections; [DisallowMultipleComponent] [ExecuteInEditMode] public class Part : MonoBehaviour { [SerializeField] private GameObject _collection = null; [SerializeField] private float _frame = 0.0f; private bool changed = false; public string part { get { if (_collection == null || _frame == 0.0f) { return "None"; } else { return _collection.transform.GetChild (Mathf.FloorToInt (_frame) - 1).gameObject.name; } } set { value = value.Replace (" ", "_"); if (_collection == null || value == "None") { frame = 0; } else { int index = _collection.transform.FindChild (value).GetSiblingIndex (); if (index != -1) { frame = index + 1; } else { frame = 0; } } } } public int frame { get { return Mathf.FloorToInt (_frame); } set { _frame = (float)value; changed = true; } } void OnValidate () { changed = true; } void OnDidApplyAnimationProperties () { changed = true; } void Update () { if (changed) { changed = false; MeshFilter meshFilter = GetComponent<MeshFilter> (); MeshRenderer meshRenderer = GetComponent<MeshRenderer> (); if (_collection != null && _frame != 0.0f) { GameObject found = _collection.transform.GetChild (Mathf.FloorToInt (_frame) - 1).gameObject; meshFilter.mesh = found.GetComponent<MeshFilter> ().sharedMesh; meshRenderer.material = found.GetComponent<MeshRenderer> ().sharedMaterial; } else { meshFilter.mesh = null; meshRenderer.material = null; } } } }
mit
C#
27921b99be9131e1b8ee22af4f298cfc01a01536
Allow `HidePopover()` to be called directly on popover containers
peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Extensions/PopoverExtensions.cs
osu.Framework/Extensions/PopoverExtensions.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; #nullable enable namespace osu.Framework.Extensions { public static class PopoverExtensions { /// <summary> /// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover); /// <summary> /// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null); private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target) { var popoverContainer = origin as PopoverContainer ?? origin.FindClosestParent<PopoverContainer>() ?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy"); popoverContainer.SetTarget(target); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; #nullable enable namespace osu.Framework.Extensions { public static class PopoverExtensions { /// <summary> /// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover); /// <summary> /// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor. /// </summary> public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null); private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target) { var popoverContainer = origin.FindClosestParent<PopoverContainer>() ?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy"); popoverContainer.SetTarget(target); } } }
mit
C#
6216c1e5f92c3562e7c4252634a9d14d90b08048
Add NextLine to execution context
SaxxonPike/roton,SaxxonPike/roton
Roton/Emulation/ExecuteCodeContext.cs
Roton/Emulation/ExecuteCodeContext.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Roton.Emulation { internal class ExecuteCodeContext : ICodeSeekable { private ICodeSeekable _instructionSource; public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name) { _instructionSource = instructionSource; this.Index = index; this.Name = name; } public Actor Actor { get; set; } public int CommandsExecuted { get; set; } public bool Died { get; set; } public bool Finished { get; set; } public int Index { get; set; } public int Instruction { get { return _instructionSource.Instruction; } set { _instructionSource.Instruction = value; } } public string Message { get; set; } public bool Moved { get; set; } public string Name { get; set; } public bool NextLine { get; set; } public int PreviousInstruction { get; set; } public bool Repeat { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Roton.Emulation { internal class ExecuteCodeContext : ICodeSeekable { private ICodeSeekable _instructionSource; public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name) { _instructionSource = instructionSource; this.Index = index; this.Name = name; } public Actor Actor { get; set; } public int CommandsExecuted { get; set; } public bool Died { get; set; } public bool Finished { get; set; } public int Index { get; set; } public int Instruction { get { return _instructionSource.Instruction; } set { _instructionSource.Instruction = value; } } public string Message { get; set; } public bool Moved { get; set; } public string Name { get; set; } public int PreviousInstruction { get; set; } public bool Repeat { get; set; } } }
isc
C#
ce4f7ae34b1c6dc41eff8b6738929950b450d4d5
Fix AssemblyVersion attribute
bitwalker/SharpTools,bitwalker/SharpTools
SharpTools/Properties/AssemblyInfo.cs
SharpTools/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("SharpTools")] [assembly: AssemblyDescription("A collection of pratical C# code to build upon.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("IronForged Softworks, LLC.")] [assembly: AssemblyProduct("SharpTools")] [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("bab38356-49cb-49c2-8803-ff75fd79f632")] // 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")] // Permit the Test project to access internals of this assembly [assembly: InternalsVisibleTo("SharpTools.Test")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SharpTools")] [assembly: AssemblyDescription("A collection of pratical C# code to build upon.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("IronForged Softworks, LLC.")] [assembly: AssemblyProduct("SharpTools")] [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("bab38356-49cb-49c2-8803-ff75fd79f632")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.*")] // Permit the Test project to access internals of this assembly [assembly: InternalsVisibleTo("SharpTools.Test")]
mit
C#
ecef56fe6de6f79a324b9e20d8e054f402be27e4
Fix typo.
bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto
Source/Eto.Test/Eto.Test/TestIcons.cs
Source/Eto.Test/Eto.Test/TestIcons.cs
using System; using System.Reflection; using Eto.Drawing; namespace Eto.Test { public static class TestIcons { #if PCL static Assembly Assembly { get { return typeof(TestIcons).GetTypeInfo().Assembly; } } // Don't use GetExecutingAssembly, it is not cross-platform safe. #else static Assembly Assembly { get { return typeof(TestIcons).Assembly; } } // Don't use GetExecutingAssembly, it is not cross-platform safe. #endif static string prefix; public static string Prefix { get { return prefix = prefix ?? Assembly.GetName().Name + "."; } } public static string TestIconName = "TestIcon.ico"; public static string TestImageName = "TestImage.png"; public static string TexturesName = "Textures.png"; /// <summary> /// An app can set this to translate resource names if they are linking them in. /// </summary> public static Func<string, string> TranslateResourceName { get; set; } static string GetTranslatedResourceName(string s) { return TranslateResourceName != null ? TranslateResourceName(s) : s; } public static Icon TestIcon(Generator generator = null) { return Icon.FromResource(Assembly, GetTranslatedResourceName(Prefix + TestIconName), generator); } public static Bitmap TestImage(Generator generator = null) { return Bitmap.FromResource(GetTranslatedResourceName(Prefix + TestImageName), Assembly, generator: generator); } public static Bitmap Textures(Generator generator = null) { return Bitmap.FromResource(GetTranslatedResourceName(Prefix + TexturesName), Assembly, generator: generator); } } }
using System; using System.Reflection; using Eto.Drawing; namespace Eto.Test { public static class TestIcons { #if PCL static Assembly Assembly { get { return typeof(TestIcons).GetTypeInfo().Assembly; } } // Don't use GetExecutingAssembly, it is not cross-platform safe. #else static Assembly Assembly { get { return typeof(TestIcons).Assembly; } } // Don't use GetExecutingAssembly, it is not cross-platform safe. #endif static string prefix; public static string Prefix { get { return prefix = prefix ?? Assembly.GetName().Name + "."; } } public static string TestIconName = "TestIcon.ico"; public static string TestImageName = "TestImage.png"; public static string TexturesName = "Textures.png"; /// <summary> /// An app can set this to translate resource names if they are linking them in. /// </summary> public static Func<string, string> TranslateResourceName { get; set; } static string TranslatedResourceName(string s) { return TranslateResourceName != null ? TranslateResourceName(s) : s; } public static Icon TestIcon(Generator generator = null) { return Icon.FromResource(Assembly, TranslateResourceName(Prefix + TestIconName), generator); } public static Bitmap TestImage(Generator generator = null) { return Bitmap.FromResource(TranslateResourceName(Prefix + TestImageName), Assembly, generator: generator); } public static Bitmap Textures(Generator generator = null) { return Bitmap.FromResource(TranslateResourceName(Prefix + TexturesName), Assembly, generator: generator); } } }
bsd-3-clause
C#
0d4ecc3d4f0002ff79bd5f274838ae64f6d01855
add whitespace for formatting
kjnilsson/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2,kjnilsson/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,IdentityServer/IdentityServer2,rfavillejr/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2
src/OnPremise/WebSite/Areas/Admin/Views/Shared/EditorTemplates/Object.cshtml
src/OnPremise/WebSite/Areas/Admin/Views/Shared/EditorTemplates/Object.cshtml
@using Thinktecture.IdentityServer.Web.Utility @{ foreach(var prop in this.ViewData.ModelMetadata.Properties) { if (prop.ShowForEdit) { <div> @if (prop.TemplateHint == "HiddenInput") { @Html.Hidden(prop.PropertyName) } else { @Html.Label(prop.PropertyName) @: if(prop.IsReadOnly) { @Html.Display(prop.PropertyName) } else { @Html.Editor(prop.PropertyName) @: @Html.Validator(prop) @: } } </div> } } }
@using Thinktecture.IdentityServer.Web.Utility @{ foreach(var prop in this.ViewData.ModelMetadata.Properties) { if (prop.ShowForEdit) { <div> @if (prop.TemplateHint == "HiddenInput") { @Html.Hidden(prop.PropertyName) } else { @Html.Label(prop.PropertyName) if(prop.IsReadOnly) { @Html.Display(prop.PropertyName) } else { @Html.Editor(prop.PropertyName) @Html.Validator(prop) } } </div> } } }
bsd-3-clause
C#
3c0be1c5f2a98496477189aaff35b89230b4c177
print console metrics also on sample
ntent-ad/Metrics.NET,ntent-ad/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,huoxudong125/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET
Samples/NancyFx.Sample/Program.cs
Samples/NancyFx.Sample/Program.cs
using System; using System.Diagnostics; using Metrics; using Metrics.Samples; using Nancy.Hosting.Self; using Newtonsoft.Json; namespace NancyFx.Sample { class Program { static void Main(string[] args) { Metric.Reports.PrintConsoleReport(TimeSpan.FromSeconds(10)); JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; using (var host = new NancyHost(new Uri("http://localhost:1234"))) { host.Start(); Console.WriteLine("Nancy Running at http://localhost:1234"); Console.WriteLine("Press any key to exit"); Process.Start("http://localhost:1234/metrics/"); SampleMetrics.RunSomeRequests(); Console.ReadKey(); } } } }
using System; using System.Diagnostics; using Metrics.Samples; using Nancy.Hosting.Self; using Newtonsoft.Json; namespace NancyFx.Sample { class Program { static void Main(string[] args) { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; using (var host = new NancyHost(new Uri("http://localhost:1234"))) { host.Start(); Console.WriteLine("Nancy Running at http://localhost:1234"); Console.WriteLine("Press any key to exit"); Process.Start("http://localhost:1234/metrics/"); SampleMetrics.RunSomeRequests(); Console.ReadKey(); } } } }
apache-2.0
C#
b2aee2dec3e9ba60a4f0bece4337b573c08878eb
Destroy the game object to avoid multiple creations
PimDeWitte/UnityMainThreadDispatcher
UnityMainThreadDispatcher.cs
UnityMainThreadDispatcher.cs
/* Copyright 2015 Get Wrecked B.V. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using UnityEngine; using System.Collections; using System.Collections.Generic; using System; /// <summary> /// A thread-safe class which holds a queue with actions to execute on the next Update() method. It can be used to make calls to the main thread for /// things such as UI Manipulation in Unity. It was developed for use in combination with the Firebase Unity plugin, which uses separate threads for event handling /// </summary> public class UnityMainThreadDispatcher : MonoBehaviour { private readonly static Queue<Action> _executionQueue = new Queue<Action>(); public void Update() { lock(_executionQueue) { while (_executionQueue.Count > 0) { _executionQueue.Dequeue().Invoke(); } } } /// <summary> /// Locks the queue and adds the IEnumerator to the queue /// </summary> /// <param name="action">IEnumerator function that will be executed from the main thread.</param> public void Enqueue(IEnumerator action) { lock (_executionQueue) { _executionQueue.Enqueue (() => { StartCoroutine (action); }); } } private static UnityMainThreadDispatcher _instance = null; public static bool Exists() { return _instance != null; } public static UnityMainThreadDispatcher Instance() { if (!Exists ()) { throw new Exception ("UnityMainThreadDispatcher could not find the UnityMainThreadDispatcher object. Please ensure you have added the MainThreadExecutor Prefab to your scene."); } return _instance; } void Awake() { if (_instance == null) { _instance = this; DontDestroyOnLoad(this.gameObject); } else { Destroy (this.gameObject); } } void OnDestroy() { _instance = null; } }
/* Copyright 2015 Get Wrecked B.V. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using UnityEngine; using System.Collections; using System.Collections.Generic; using System; /// <summary> /// A thread-safe class which holds a queue with actions to execute on the next Update() method. It can be used to make calls to the main thread for /// things such as UI Manipulation in Unity. It was developed for use in combination with the Firebase Unity plugin, which uses separate threads for event handling /// </summary> public class UnityMainThreadDispatcher : MonoBehaviour { private readonly static Queue<Action> _executionQueue = new Queue<Action>(); public void Update() { lock(_executionQueue) { while (_executionQueue.Count > 0) { _executionQueue.Dequeue().Invoke(); } } } /// <summary> /// Locks the queue and adds the IEnumerator to the queue /// </summary> /// <param name="action">IEnumerator function that will be executed from the main thread.</param> public void Enqueue(IEnumerator action) { lock (_executionQueue) { _executionQueue.Enqueue (() => { StartCoroutine (action); }); } } private static UnityMainThreadDispatcher _instance = null; public static bool Exists() { return _instance != null; } public static UnityMainThreadDispatcher Instance() { if (!Exists ()) { throw new Exception ("UnityMainThreadDispatcher could not find the UnityMainThreadDispatcher object. Please ensure you have added the MainThreadExecutor Prefab to your scene."); } return _instance; } void Awake() { if (_instance == null) { _instance = this; DontDestroyOnLoad(this.gameObject); } } void OnDestroy() { _instance = null; } }
apache-2.0
C#
c1f7104f69d563e8ff6ce9866c66d5857d5b7dde
Fix environment custom tokens (cannot be static in model).
nortal/AssemblyVersioning
AssemblyVersioning/Generators/CustomVersionGeneratorModel.cs
AssemblyVersioning/Generators/CustomVersionGeneratorModel.cs
/* Copyright 2013 Imre Pühvel, AS Nortal 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. This file is from project https://github.com/NortalLTD/AssemblyVersioning, Nortal.Utilities.AssemblyVersioning, file 'GenerateExtendedAssemblyInfoTask.cs'. */ using System; namespace Nortal.Utilities.AssemblyVersioning.Generators { public sealed class CustomizedVersionModel { public CustomizedVersionModel(VersionGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } this.Context = context; } // storage for model properties private VersionGenerationContext Context { get; set; } private DateTime FixedNow = DateTime.Now; // to ensure it does not change between multiple calls private DateTime FixedUtcNow = DateTime.UtcNow; // to ensure it does not change between multiple calls // BaseVersion parts: public int Major { get { return this.Context.BaseVersion.Major; } } public int Minor { get { return this.Context.BaseVersion.Minor; } } public int Build { get { return this.Context.BaseVersion.Build; } } public int Revision { get { return this.Context.BaseVersion.Revision; } } // date components: public DateTime Now { get { return this.FixedNow; } } public int DateNumber { get { return DateToVersionNumberCalculation.BuildDatePart(this.FixedNow); } } public int TimeNumber { get { return DateToVersionNumberCalculation.BuildTimePart(this.FixedNow); } } public DateTime UtcNow { get { return this.FixedUtcNow; } } public int UtcDateNumber { get { return DateToVersionNumberCalculation.BuildDatePart(this.FixedUtcNow); } } public int UtcTimeNumber { get { return DateToVersionNumberCalculation.BuildTimePart(this.FixedUtcNow); } } // user context: public String BuildConfiguration { get { return this.Context.BuildConfiguration; } } // Environment public String Domain { get { return Environment.UserDomainName; } } public String UserName { get { return Environment.UserName; } } public String MachineName { get { return Environment.MachineName; } } } }
/* Copyright 2013 Imre Pühvel, AS Nortal 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. This file is from project https://github.com/NortalLTD/AssemblyVersioning, Nortal.Utilities.AssemblyVersioning, file 'GenerateExtendedAssemblyInfoTask.cs'. */ using System; namespace Nortal.Utilities.AssemblyVersioning.Generators { public sealed class CustomizedVersionModel { public CustomizedVersionModel(VersionGenerationContext context) { if (context == null) { throw new ArgumentNullException("context"); } this.Context = context; } // storage for model properties private VersionGenerationContext Context { get; set; } private DateTime FixedNow = DateTime.Now; // to ensure it does not change between multiple calls private DateTime FixedUtcNow = DateTime.UtcNow; // to ensure it does not change between multiple calls // BaseVersion parts: public int Major { get { return this.Context.BaseVersion.Major; } } public int Minor { get { return this.Context.BaseVersion.Minor; } } public int Build { get { return this.Context.BaseVersion.Build; } } public int Revision { get { return this.Context.BaseVersion.Revision; } } // date components: public DateTime Now { get { return this.FixedNow; } } public int DateNumber { get { return DateToVersionNumberCalculation.BuildDatePart(this.FixedNow); } } public int TimeNumber { get { return DateToVersionNumberCalculation.BuildTimePart(this.FixedNow); } } public DateTime UtcNow { get { return this.FixedUtcNow; } } public int UtcDateNumber { get { return DateToVersionNumberCalculation.BuildDatePart(this.FixedUtcNow); } } public int UtcTimeNumber { get { return DateToVersionNumberCalculation.BuildTimePart(this.FixedUtcNow); } } // user context: public String BuildConfiguration { get { return this.Context.BuildConfiguration; } } // Environment public static String Domain { get { return Environment.UserDomainName; } } public static String UserName { get { return Environment.UserName; } } public static String MachineName { get { return Environment.MachineName; } } } }
apache-2.0
C#
3294ef159e41d71383d7af3e7a2f26ae386a0b84
Fix victory delegate clearing in stage
Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare
Assets/Microgames/YuukaWater/Scripts/YuukaWaterController.cs
Assets/Microgames/YuukaWater/Scripts/YuukaWaterController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class YuukaWaterController : MonoBehaviour { public int requiredCompletion = 3; int completionCounter = 0; public delegate void VictoryAction(); public static event VictoryAction OnVictory; private void Awake() { OnVictory = null; } public void Notify() { completionCounter++; if (completionCounter >= requiredCompletion) { MicrogameController.instance.setVictory(true, true); OnVictory(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class YuukaWaterController : MonoBehaviour { public int requiredCompletion = 3; int completionCounter = 0; public delegate void VictoryAction(); public static event VictoryAction OnVictory; public void Notify() { completionCounter++; if (completionCounter >= requiredCompletion) { MicrogameController.instance.setVictory(true, true); OnVictory(); } } private void OnDestroy() { OnVictory = null; } }
mit
C#
0cb41265d11b01fb7fe170c68eaefce3990cdae1
Add comments to player
Onosume/battleships-cli-c-sharp
battleships-cli/battleships-cli/Application/GameObjects/Player/Player.cs
battleships-cli/battleships-cli/Application/GameObjects/Player/Player.cs
// battlships-cli // Player.cs // Author: Matthew Tinn namespace battleships_cli.Application.GameObjects.Player { /// <summary> /// The player class /// Holds the player's score and number of cannonballs remaining /// </summary> public class Player { private int score; private int cannonballs; // Accessor Methods public int Score { get { return score; } } public int Cannonballs { get { return cannonballs; } } /// <summary> /// Constructor /// </summary> /// <param name="numCannonballs">Player's maximum number of cannonballs</param> public Player(int numCannonballs) { Init(numCannonballs); } /// <summary> /// Initialise the player /// </summary> /// <param name="numCannonballs">Player's maximum number of cannonballs</param> private void Init(int numCannonballs) { score = 0; cannonballs = numCannonballs; } /// <summary> /// Decrement player cannonballs /// </summary> public void TakeShot() { cannonballs--; } /// <summary> /// Add specific value to player score /// </summary> /// <param name="points">Value to add</param> public void AddToScore(int points) { score += points; } } }
// battlships-cli // Player.cs // Author: Matthew Tinn namespace battleships_cli.Application.GameObjects.Player { /// <summary> /// The player class /// Holds the player's score and number of cannonballs remaining /// </summary> public class Player { private int score; private int cannonballs; // Accessor Methods public int Score { get { return score; } } public int Cannonballs { get { return cannonballs; } } public Player(int numCannonballs) { Init(numCannonballs); } private void Init(int numCannonballs) { score = 0; cannonballs = numCannonballs; } public void TakeShot() { cannonballs--; } public void AddToScore(int points) { score += points; } } }
mit
C#
c8a4805536c424c47b14c8ce569aae852247cebd
Add cascade for TripReadModelValidation
senioroman4uk/PathFinder
PathFinder.Trips.WebApi/Validators/TripReadModelValidator.cs
PathFinder.Trips.WebApi/Validators/TripReadModelValidator.cs
using FluentValidation; using PathFinder.Trips.WebApi.Models; using System; namespace PathFinder.Trips.WebApi.Validators { public class TripReadModelValidator:AbstractValidator<TripReadModel> { public TripReadModelValidator() { RuleFor(model => model.StartPoint).NotNull(); RuleFor(model => model.EndPoint).NotNull(); RuleFor(model => model.Algorithm).NotNull(); RuleFor(model => model.DepartureDate).Cascade(CascadeMode.StopOnFirstFailure).NotNull().GreaterThanOrEqualTo(DateTime.Now); RuleFor(model => model.Price).Cascade(CascadeMode.StopOnFirstFailure).NotEmpty().GreaterThanOrEqualTo(0m); } } }
using FluentValidation; using PathFinder.Trips.WebApi.Models; using System; namespace PathFinder.Trips.WebApi.Validators { public class TripReadModelValidator:AbstractValidator<TripReadModel> { public TripReadModelValidator() { RuleFor(model => model.StartPoint).NotNull(); RuleFor(model => model.EndPoint).NotNull(); RuleFor(model => model.Algorithm).NotNull(); RuleFor(model => model.DepartureDate).NotNull().GreaterThanOrEqualTo(DateTime.Now); RuleFor(model => model.Price).NotEmpty(); } } }
mit
C#
f09239ecec801309006994aeccfe5e920d563707
update vs for release
Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal
Master/Appleseed/Projects/Appleseed.Framework.Core/Properties/AssemblyInfo.cs
Master/Appleseed/Projects/Appleseed.Framework.Core/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Resources; // 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("Appleseed.Framework.Core")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("Appleseed Portal")] [assembly: AssemblyCopyright("Copyright ANANT Corporation 2010-2017")] [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( "acbff986-eea5-4c71-8bcd-c868dc78a20d" )] // 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.4.131.463")] [assembly: AssemblyFileVersion("1.4.131.463")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the "project output directory". The location of the project output // directory is dependent on whether you are working with a local or web project. // For local projects, the project output directory is defined as // <Project Directory>\obj\<Configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // For web projects, the project output directory is defined as // %HOMEPATH%\VSWebCache\<Machine Name>\<Project Directory>\obj\<Configuration>. // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign( false )] [assembly: AssemblyKeyFile( "" )] [assembly: NeutralResourcesLanguageAttribute("en-US")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Resources; // 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("Appleseed.Framework.Core")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("Appleseed Portal")] [assembly: AssemblyCopyright("Copyright ANANT Corporation 2010-2017")] [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( "acbff986-eea5-4c71-8bcd-c868dc78a20d" )] // 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.4.98.383")] [assembly: AssemblyFileVersion("1.4.98.383")] // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the "project output directory". The location of the project output // directory is dependent on whether you are working with a local or web project. // For local projects, the project output directory is defined as // <Project Directory>\obj\<Configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // For web projects, the project output directory is defined as // %HOMEPATH%\VSWebCache\<Machine Name>\<Project Directory>\obj\<Configuration>. // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign( false )] [assembly: AssemblyKeyFile( "" )] [assembly: NeutralResourcesLanguageAttribute("en-US")]
apache-2.0
C#
421308c5fd0923e0fb54c36697b63460c8a80fce
add logging
NDark/ndinfrastructure,NDark/ndinfrastructure
Unity/UnityTools/OnEscapeLeaveGame.cs
Unity/UnityTools/OnEscapeLeaveGame.cs
/** MIT License Copyright (c) 2017 NDark 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. */ /** @file OnEscapeLeaveGame.cs @author NDark @date 20170507 . file started. */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class OnEscapeLeaveGame : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if( Input.GetKeyUp(KeyCode.Escape) ) { // Debug.LogWarning("Application.Quit"); Application.Quit() ; } } }
/** MIT License Copyright (c) 2017 NDark 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. */ /** @file OnEscapeLeaveGame.cs @author NDark @date 20170507 . file started. */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class OnEscapeLeaveGame : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if( Input.GetKeyUp(KeyCode.Escape) ) { Application.Quit() ; } } }
mit
C#
073b6f36ae168cf67ffec6b9094ea4b65775673b
Use HTTPS protocol
mike-ward/VSColorOutput
VSColorOutput/VsColorOutputPackage.cs
VSColorOutput/VsColorOutputPackage.cs
using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell; using VSColorOutput.State; using Task = System.Threading.Tasks.Task; namespace VSColorOutput { [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [Guid(VSColorOutputPackage.PackageGuidString)] [ProvideOptionPage(typeof(VsColorOutputOptionsDialog), VsColorOutputOptionsDialog.Category, VsColorOutputOptionsDialog.SubCategory, 1000, 1001, true)] [ProvideProfile(typeof(VsColorOutputOptionsDialog), VsColorOutputOptionsDialog.Category, VsColorOutputOptionsDialog.SubCategory, 1000, 1001, true)] [InstalledProductRegistration("VSColorOutput", "Color output for build and debug windows - https://mike-ward.net/vscoloroutput", "2.6.5")] public sealed class VSColorOutputPackage : AsyncPackage { public const string PackageGuidString = "CD56B219-38CB-482A-9B2D-7582DF4AAF1E"; protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); } } }
using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell; using VSColorOutput.State; using Task = System.Threading.Tasks.Task; namespace VSColorOutput { [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [Guid(VSColorOutputPackage.PackageGuidString)] [ProvideOptionPage(typeof(VsColorOutputOptionsDialog), VsColorOutputOptionsDialog.Category, VsColorOutputOptionsDialog.SubCategory, 1000, 1001, true)] [ProvideProfile(typeof(VsColorOutputOptionsDialog), VsColorOutputOptionsDialog.Category, VsColorOutputOptionsDialog.SubCategory, 1000, 1001, true)] [InstalledProductRegistration("VSColorOutput", "Color output for build and debug windows - http://mike-ward.net/vscoloroutput", "2.6.5")] public sealed class VSColorOutputPackage : AsyncPackage { public const string PackageGuidString = "CD56B219-38CB-482A-9B2D-7582DF4AAF1E"; protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); } } }
mit
C#
4a0bed4e1a3aad8c1eac739896107f25d3204292
Remove unused field.
andrewdavey/cassette,damiensawyer/cassette,damiensawyer/cassette,honestegg/cassette,BluewireTechnologies/cassette,damiensawyer/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette,andrewdavey/cassette
src/Cassette/Assets/HtmlTemplates/HtmlTemplateModuleContainerBuilder.cs
src/Cassette/Assets/HtmlTemplates/HtmlTemplateModuleContainerBuilder.cs
using System.IO.IsolatedStorage; using System.Linq; using Cassette.ModuleBuilding; namespace Cassette.Assets.HtmlTemplates { public class HtmlTemplateModuleContainerBuilder : ModuleContainerBuilder { public HtmlTemplateModuleContainerBuilder(IsolatedStorageFile storage, string rootDirectory, string applicationRoot) : base(storage, rootDirectory) { } public override ModuleContainer Build() { var moduleBuilder = new UnresolvedHtmlTemplateModuleBuilder(rootDirectory); var unresolvedModules = relativeModuleDirectories.Select(x => moduleBuilder.Build(x.Item1, x.Item2)); var modules = UnresolvedModule.ResolveAll(unresolvedModules); return new ModuleContainer( modules, storage, textWriter => new HtmlTemplateModuleWriter(textWriter, rootDirectory, LoadFile) ); } } }
using System.IO.IsolatedStorage; using System.Linq; using Cassette.ModuleBuilding; namespace Cassette.Assets.HtmlTemplates { public class HtmlTemplateModuleContainerBuilder : ModuleContainerBuilder { readonly string applicationRoot; public HtmlTemplateModuleContainerBuilder(IsolatedStorageFile storage, string rootDirectory, string applicationRoot) : base(storage, rootDirectory) { this.applicationRoot = EnsureDirectoryEndsWithSlash(applicationRoot); } public override ModuleContainer Build() { var moduleBuilder = new UnresolvedHtmlTemplateModuleBuilder(rootDirectory); var unresolvedModules = relativeModuleDirectories.Select(x => moduleBuilder.Build(x.Item1, x.Item2)); var modules = UnresolvedModule.ResolveAll(unresolvedModules); return new ModuleContainer( modules, storage, textWriter => new HtmlTemplateModuleWriter(textWriter, rootDirectory, LoadFile) ); } } }
mit
C#
913b330accdcc604bbd66c764c1113be97272d8e
Add try catch
JoeBiellik/clipup
Windows/Forms/Provider/Preferences.cs
Windows/Forms/Provider/Preferences.cs
using System; using System.Windows.Forms; using ClipUp.Sdk.Interfaces; namespace ClipUp.Windows.Forms.Provider { public partial class Preferences : Form { public IUploadProvider Provider { get; } public Preferences(IUploadProvider provider) { if (!(provider is IConfigurableProvider)) { throw new ArgumentException("Provider must implement IConfigurableProvider", nameof(provider)); } this.Provider = provider; this.InitializeComponent(); } private void Preferences_Load(object sender, EventArgs e) { this.Text = this.Provider.Name + " Provider Preferences"; try { (this.Provider as IConfigurableProvider)?.Configure(this.panel.Controls); } catch (Exception) { // TODO: Handle throw; } } private void buttonOk_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } private void buttonCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } } }
using System; using System.Windows.Forms; using ClipUp.Sdk.Interfaces; namespace ClipUp.Windows.Forms.Provider { public partial class Preferences : Form { public IUploadProvider Provider { get; } public Preferences(IUploadProvider provider) { if (!(provider is IConfigurableProvider)) { throw new ArgumentException("Provider must implement IConfigurableProvider", nameof(provider)); } this.Provider = provider; this.InitializeComponent(); } private void Preferences_Load(object sender, EventArgs e) { this.Text = this.Provider.Name + " Provider Preferences"; (this.Provider as IConfigurableProvider)?.Configure(this.panel.Controls); } private void buttonOk_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } private void buttonCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } } }
mit
C#
a93b8e2dc9833a8856aa00df163b43b256099f34
Tweak the endpoint names
adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats
Website/Modules/NetgearApiModule.cs
Website/Modules/NetgearApiModule.cs
using System; using System.Collections.Generic; using BroadbandStats.NetgearRouter.Devices; using Nancy; using Nancy.Extensions; namespace BroadbandStats.Website.Modules { public sealed class NetgearApiModule : NancyModule { private readonly AttachedDevicesParser attachedDevicesParser; public NetgearApiModule(AttachedDevicesParser attachedDevicesParser) : base("/netgear") { if (attachedDevicesParser == null) { throw new ArgumentNullException(nameof(attachedDevicesParser)); } this.attachedDevicesParser = attachedDevicesParser; Post["/RecordAttachedDevices"] = _ => { var body = Request.Body.AsString(); var model = attachedDevicesParser.Parse(body); return RecordAttachedDevices(model); }; Post["/RecordTrafficStats"] = _ => { // var body = Request.Body.AsString(); // var model = new RouterTrafficParser().Parse(body); return RecordTrafficStats(); }; } private HttpStatusCode RecordAttachedDevices(IEnumerable<Device> attachedDevices) { return HttpStatusCode.Created; } private HttpStatusCode RecordTrafficStats() { return HttpStatusCode.Created; } } }
using System; using System.Collections.Generic; using BroadbandStats.NetgearRouter.Devices; using Nancy; using Nancy.Extensions; namespace BroadbandStats.Website.Modules { public sealed class NetgearApiModule : NancyModule { private readonly AttachedDevicesParser attachedDevicesParser; public NetgearApiModule(AttachedDevicesParser attachedDevicesParser) : base("/netgear") { if (attachedDevicesParser == null) { throw new ArgumentNullException(nameof(attachedDevicesParser)); } this.attachedDevicesParser = attachedDevicesParser; Post["/RecordRouterDevices"] = _ => { var body = Request.Body.AsString(); var model = attachedDevicesParser.Parse(body); return RecordRouterDevices(model); }; Post["/RecordRouterTraffic"] = _ => { // var body = Request.Body.AsString(); // var model = new RouterTrafficParser().Parse(body); return RecordRouterTraffic(); }; } private HttpStatusCode RecordRouterDevices(IEnumerable<Device> attachedDevices) { return HttpStatusCode.Created; } private HttpStatusCode RecordRouterTraffic() { return HttpStatusCode.Created; } } }
mit
C#
02a1bfb0022763a1a183289730319adda9582281
Remove unnecessary comment
timclipsham/tfs-hipchat
TfsHipChat/CheckinEventService.cs
TfsHipChat/CheckinEventService.cs
using System.IO; using System.Xml.Serialization; using Microsoft.TeamFoundation.VersionControl.Common; namespace TfsHipChat { public class CheckinEventService : IEventService { private INotifier _notifier; public CheckinEventService() { } public CheckinEventService(INotifier notifier) { this._notifier = notifier; } public void Notify(string eventXml, string tfsIdentityXml) { var serializer = new XmlSerializer(typeof(CheckinEvent)); CheckinEvent checkinEvent; using (var reader = new StringReader(eventXml)) { checkinEvent = serializer.Deserialize(reader) as CheckinEvent; } if (checkinEvent == null) { return; } // check whether the changeset has policy failures if (checkinEvent.PolicyFailures.Count > 0) { } } } }
using System.IO; using System.Xml.Serialization; using Microsoft.TeamFoundation.VersionControl.Common; namespace TfsHipChat { public class CheckinEventService : IEventService { private INotifier _notifier; public CheckinEventService() { } public CheckinEventService(INotifier notifier) { this._notifier = notifier; } public void Notify(string eventXml, string tfsIdentityXml) { var serializer = new XmlSerializer(typeof(CheckinEvent)); CheckinEvent checkinEvent; using (var reader = new StringReader(eventXml)) { checkinEvent = serializer.Deserialize(reader) as CheckinEvent; // double check "TryCast"... } if (checkinEvent == null) { return; } // check whether the changeset has policy failures if (checkinEvent.PolicyFailures.Count > 0) { } } } }
mit
C#
8f59d28d37148b8f1e4517218483ccfb7e8559f8
modify iceblockmanager
woolparty/DontEatMyFish
DonTouchMyFish/Assets/Assets/Scripts/GameControllers/IceBlockManager.cs
DonTouchMyFish/Assets/Assets/Scripts/GameControllers/IceBlockManager.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class IceBlockManager : MonoBehaviour { private List<IceBlock> m_iceBlocks; private List<IceBlock> m_matchedBlocks; // Use this for initialization void Awake () { m_iceBlocks = new List<IceBlock>(); m_matchedBlocks = new List<IceBlock>(); } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.U)) { CheckForMatch(); } } public int GetBlockCount() { return m_iceBlocks.Count; } public void AddBlock(IceBlock i_iceblock) { m_iceBlocks.Add(i_iceblock); FishType type = m_iceBlocks[m_iceBlocks.Count - 1].foodType; i_iceblock.transform.parent = transform; } public void DeleteBlock(IceBlock i_iceblock) { m_iceBlocks.Remove(i_iceblock); Destroy(i_iceblock.gameObject); GameManager.GetInstance().AddScore(10); } public void Clear() { m_iceBlocks.Clear(); m_matchedBlocks.Clear(); } public void InitBlocks(int count, FishType type1, FishType type2) { FishType lastBlockType; FishType lastlasltBlockType; for(int i = 0; i< count; i++) { float random = Random.Range(0, 0.999f); if(random > 0.5f) { Debug.Log("InitBlocks"); } } } public void CheckForMatch() { FishType type = FishType.None; for (int i = 0; i < m_iceBlocks.Count; i++) { if (type == m_iceBlocks[i].foodType) { m_matchedBlocks.Add(m_iceBlocks[i]); } else { if (m_matchedBlocks.Count >= 3) { break; } type = m_iceBlocks[i].foodType; m_matchedBlocks.Clear(); m_matchedBlocks.Add(m_iceBlocks[i]); } } if (m_matchedBlocks.Count < 3) { m_matchedBlocks.Clear(); } foreach (IceBlock block in m_matchedBlocks) { DeleteBlock(block); } m_matchedBlocks.Clear(); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class IceBlockManager : MonoBehaviour { private List<IceBlock> m_iceBlocks; private List<IceBlock> m_matchedBlocks; // Use this for initialization void Awake () { m_iceBlocks = new List<IceBlock>(); m_matchedBlocks = new List<IceBlock>(); } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.U)) { CheckForMatch(); } } public int GetBlockCount() { return m_iceBlocks.Count; } public void AddBlock(IceBlock i_iceblock) { m_iceBlocks.Add(i_iceblock); FishType type = m_iceBlocks[m_iceBlocks.Count - 1].foodType; i_iceblock.transform.parent = transform; } public void DeleteBlock(IceBlock i_iceblock) { m_iceBlocks.Remove(i_iceblock); Destroy(i_iceblock.gameObject); GameManager.GetInstance().AddScore(10); } public void Clear() { m_iceBlocks.Clear(); m_matchedBlocks.Clear(); } public void InitBlocks(int count) { for(int i = 0; i< count; i++) { } } public void CheckForMatch() { FishType type = FishType.None; for (int i = 0; i < m_iceBlocks.Count; i++) { if (type == m_iceBlocks[i].foodType) { m_matchedBlocks.Add(m_iceBlocks[i]); } else { if (m_matchedBlocks.Count >= 3) { break; } type = m_iceBlocks[i].foodType; m_matchedBlocks.Clear(); m_matchedBlocks.Add(m_iceBlocks[i]); } } if (m_matchedBlocks.Count < 3) { m_matchedBlocks.Clear(); } foreach (IceBlock block in m_matchedBlocks) { DeleteBlock(block); } m_matchedBlocks.Clear(); } }
apache-2.0
C#
c58af0433acdc4c0828b17103260d7f680ffc260
Update AddingWorksheetsToNewExcelFile.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Worksheets/Management/AddingWorksheetsToNewExcelFile.cs
Examples/CSharp/Worksheets/Management/AddingWorksheetsToNewExcelFile.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Management { public class AddingWorksheetsToNewExcelFile { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Workbook object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Setting the name of the newly added worksheet worksheet.Name = "My Worksheet"; //Saving the Excel file workbook.Save(dataDir + "output.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Management { public class AddingWorksheetsToNewExcelFile { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a new worksheet to the Workbook object int i = workbook.Worksheets.Add(); //Obtaining the reference of the newly added worksheet by passing its sheet index Worksheet worksheet = workbook.Worksheets[i]; //Setting the name of the newly added worksheet worksheet.Name = "My Worksheet"; //Saving the Excel file workbook.Save(dataDir + "output.out.xls"); } } }
mit
C#
43ee89e77de2765b16ae435e0721eba9965ac384
Add NameBR Features
augustocordeiro/NFaker,yanjustino/NFaker
FFaker.net/NameBR.cs
FFaker.net/NameBR.cs
using NFaker.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NFaker { public class NameBR { private static string NAME_BR = "name_br"; public static string Name { get { return string.Format("{0} {1}", FirstName, LasttName); } } public static string NameWithPrefix { get { return string.Format("{0} {1} {2}", Prefix, FirstName, LasttName); } } public static string FirstName { get { return NAME_BR.Rand("first_names"); } } public static string LasttName { get { return NAME_BR.Rand("last_names"); } } public static string Prefix { get { return "Sr. Sra. Srta.".Rand(); } } } }
using NFaker.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NFaker { public class NameBR : Faker { private static string KEY = "name_br"; public static string FirstName { get { return Rand(KEY, "first_names"); } } public static string LasttName { get { return Rand(KEY, "last_names"); } } } }
mit
C#
40f76704fa958ac784d0df0ebcf76e43902d829e
Change sitemap.xml to reference requested host
Red-Folder/WebCrawl-Functions
WebCrawlProcess/run.csx
WebCrawlProcess/run.csx
#r "Newtonsoft.Json" using System; using Red_Folder.WebCrawl; using Red_Folder.WebCrawl.Data; using Red_Folder.Logging; using Newtonsoft.Json; public static void Run(string request, out object outputDocument, TraceWriter log) { var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request); log.Info($"C# Queue trigger function processed: {crawlRequest.Id}"); var azureLogger = new AzureLogger(log); var crawler = new Crawler(crawlRequest, azureLogger); crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml"); var crawlResult = crawler.Crawl(); outputDocument = crawlResult; } public class AzureLogger : ILogger { private TraceWriter _log; public AzureLogger(TraceWriter log) { _log = log; } public void Info(string message) { _log.Info(message); } }
#r "Newtonsoft.Json" using System; using Red_Folder.WebCrawl; using Red_Folder.WebCrawl.Data; using Red_Folder.Logging; using Newtonsoft.Json; public static void Run(string request, out object outputDocument, TraceWriter log) { log.Info($"C# Queue trigger function processed: {crawlRequest.Id}"); var azureLogger = new AzureLogger(log); var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request); var crawler = new Crawler(crawlRequest, azureLogger); crawler.AddUrl("https://www.red-folder.com/sitemap.xml"); var crawlResult = crawler.Crawl(); outputDocument = crawlResult; } public class AzureLogger : ILogger { private TraceWriter _log; public AzureLogger(TraceWriter log) { _log = log; } public void Info(string message) { _log.Info(message); } }
mit
C#
80caa7211d73836fa6f72f498d03c6b0a7a566cc
Fix - WIP
Red-Folder/WebCrawl-Functions
WebCrawlProcess/run.csx
WebCrawlProcess/run.csx
#r "Newtonsoft.Json" using System; using Red_Folder.WebCrawl; using Red_Folder.WebCrawl.Data; using Red_Folder.Logging; using Newtonsoft.Json; public static void Run(string request, out object outputDocument, TraceWriter log) { CrawlRequest crawlRequest = null; try { crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request); log.Info($"C# Queue trigger function processed: {crawlRequest.Id}"); } catch (Exception ex) { log.Info($"Failed to get object - likely wrong format: {ex.Message}"); outputDocument = null; return; } var azureLogger = new AzureLogger(log); var crawler = new Crawler(crawlRequest, azureLogger); crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml"); var crawlResult = crawler.Crawl(); outputDocument = crawlResult; } public class AzureLogger : ILogger { private TraceWriter _log; public AzureLogger(TraceWriter log) { _log = log; } public void Info(string message) { _log.Info(message); } }
#r "Newtonsoft.Json" using System; using Red_Folder.WebCrawl; using Red_Folder.WebCrawl.Data; using Red_Folder.Logging; using Newtonsoft.Json; public static void Run(string request, out object outputDocument, TraceWriter log) { log.Info($"Started"); CrawlRequest crawlRequest = null; try { crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request); log.Info($"C# Queue trigger function processed: {crawlRequest.Id}"); } catch (Exception ex) { log.Info($"Failed to get object - likely wrong format: {ex.Message}"); outputDocument = null; return; } var azureLogger = new AzureLogger(log); var crawler = new Crawler(crawlRequest, azureLogger); crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml"); var crawlResult = crawler.Crawl(); outputDocument = crawlResult; //outputDocument = new { id = Guid.NewGuid().ToString() }; log.Info($"Finished"); } public class AzureLogger : ILogger { private TraceWriter _log; public AzureLogger(TraceWriter log) { _log = log; } public void Info(string message) { _log.Info(message); } }
mit
C#
d4ae8df177b08d04a9105596b1971320d27d5908
add footer
kreeben/resin,kreeben/resin
src/Sir.HttpServer/Views/_Layout.cshtml
src/Sir.HttpServer/Views/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> <style> textarea { float: left; } a { text-decoration: none; color: orangered; } a.result-link{ color: mediumblue; } a.result-link:visited { color: purple; } input[type=text]{ width: 260px; } hr{ width: 300px; } </style> <a href="/"><h1>Did you go go?</h1></a> @using (Html.BeginRouteForm("default", new { controller = "Search" }, FormMethod.Get)) { <div> <input type="text" id="q" name="q" placeholder="Ask anything." /> <input type="submit" value="Go" /> </div> } <div> @RenderBody() </div> <div><p>This is a web index. <a href="/add">Submit page.</a></p></div> <footer> <hr align="left" size="1" noshade/> <p>No cookies, no javascript, no tracking.</p> <p>Built on code <a href="https://github.com/kreeben/resin">hosted on GitHub</a></p> </footer> </body> </html>
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> <style> textarea { float: left; } a { text-decoration: none; color: orangered; } a.result-link{ color: mediumblue; } a.result-link:visited { color: purple; } input[type=text]{ width: 260px; } </style> <a href="/"><h1>Did you go go?</h1></a> @using (Html.BeginRouteForm("default", new { controller = "Search" }, FormMethod.Get)) { <div> <input type="text" id="q" name="q" placeholder="Ask anything." /> <input type="submit" value="Go" /> </div> } <div> @RenderBody() </div> <div><p>This is a web index. <a href="/add">Submit page.</a></p></div> </body> </html>
mit
C#
a1c11d17ea0f8a9888952161e64a5e520d4402bf
Fix typo
tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,tompipe/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,tompipe/Umbraco-CMS,lars-erik/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,WebCentrum/Umbraco-CMS,rasmuseeg/Umbraco-CMS,WebCentrum/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arknu/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,lars-erik/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,WebCentrum/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,hfloyd/Umbraco-CMS,tompipe/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,lars-erik/Umbraco-CMS
src/Umbraco.Compat7/Compat7Component.cs
src/Umbraco.Compat7/Compat7Component.cs
using System; using System.Collections.Generic; using LightInject; using System.Linq; using Umbraco.Core; using Umbraco.Core.Components; using Umbraco.Core.Logging; using Umbraco.Core.Plugins; namespace Umbraco.Compat7 { public class Compat7Component : UmbracoComponentBase, IUmbracoUserComponent { private List<IApplicationEventHandler> _handlers; private UmbracoApplicationBase _app; // these events replace the UmbracoApplicationBase corresponding events public static event EventHandler ApplicationStarting; public static event EventHandler ApplicationStarted; public override void Compose(Composition composition) { base.Compose(composition); var container = composition.Container; _app = container.GetInstance<UmbracoApplicationBase>(); var logger = container.GetInstance<ILogger>(); var pluginManager = container.GetInstance<PluginManager>(); var handlerTypes = pluginManager.ResolveTypes<IApplicationEventHandler>(); _handlers = handlerTypes.Select(Activator.CreateInstance).Cast<IApplicationEventHandler>().ToList(); foreach (var handler in _handlers) logger.Debug<Compat7Component>($"Adding ApplicationEventHandler {handler.GetType().FullName}."); foreach (var handler in _handlers) handler.OnApplicationInitialized(_app, ApplicationContext.Current); foreach (var handler in _handlers) handler.OnApplicationStarting(_app, ApplicationContext.Current); try { ApplicationStarting?.Invoke(_app, EventArgs.Empty); } catch (Exception ex) { logger.Error<Compat7Component>("An error occurred in an ApplicationStarting event handler", ex); throw; } } public void Initialize(ILogger logger) { foreach (var handler in _handlers) handler.OnApplicationStarted(_app, ApplicationContext.Current); try { ApplicationStarted?.Invoke(_app, EventArgs.Empty); } catch (Exception ex) { logger.Error<Compat7Component>("An error occurred in an ApplicationStarting event handler", ex); throw; } } } }
using System; using System.Collections.Generic; using LightInject; using System.Linq; using Umbraco.Core; using Umbraco.Core.Components; using Umbraco.Core.Logging; using Umbraco.Core.Plugins; namespace Umbraco.Compat7 { public class Compat7Component : UmbracoComponentBase, IUmbracoUserComponent { private List<IApplicationEventHandler> _handlers; private UmbracoApplicationBase _app; // these events replace the UmbracoApplicationBase corresponding events public static event EventHandler ApplicationStarting; public static event EventHandler ApplicationStarted; public override void Compose(Composition composition) { base.Compose(composition); var container = composition.Container; _app = container.GetInstance<UmbracoApplicationBase>(); var logger = container.GetInstance<ILogger>(); var pluginManager = container.GetInstance<PluginManager>(); var handlerTypes = pluginManager.ResolveTypes<IApplicationEventHandler>(); _handlers = handlerTypes.Select(Activator.CreateInstance).Cast<IApplicationEventHandler>().ToList(); foreach (var handler in _handlers) logger.Debug<Compat7Component>($"ADding ApplicationEventHandler {handler.GetType().FullName}."); foreach (var handler in _handlers) handler.OnApplicationInitialized(_app, ApplicationContext.Current); foreach (var handler in _handlers) handler.OnApplicationStarting(_app, ApplicationContext.Current); try { ApplicationStarting?.Invoke(_app, EventArgs.Empty); } catch (Exception ex) { logger.Error<Compat7Component>("An error occurred in an ApplicationStarting event handler", ex); throw; } } public void Initialize(ILogger logger) { foreach (var handler in _handlers) handler.OnApplicationStarted(_app, ApplicationContext.Current); try { ApplicationStarted?.Invoke(_app, EventArgs.Empty); } catch (Exception ex) { logger.Error<Compat7Component>("An error occurred in an ApplicationStarting event handler", ex); throw; } } } }
mit
C#
09a10a6cffc5682c49851282da53f5dae7db7ffb
Remove BrowserStack logo from page footer
martincostello/website,martincostello/website,martincostello/website,martincostello/website
src/Website/Views/Shared/_Footer.cshtml
src/Website/Views/Shared/_Footer.cshtml
@model SiteOptions <hr /> <footer> <p class="hidden-sm hidden-xs"> &copy; @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year | <a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" rel="noopener" target="_blank" title="View site uptime information"> Site Status &amp; Uptime </a> | Built from <a id="link-git-commit" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub"> @string.Join(string.Empty, GitMetadata.Commit.Take(7)) </a> on <a id="link-git-branch" href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub"> @GitMetadata.Branch </a> <span id="build-date" data-format="YYYY-MM-DD HH:mm Z" data-timestamp="@GitMetadata.Timestamp.ToString("u", CultureInfo.InvariantCulture)"></span> </p> <div class="row hidden-md hidden-lg"> <div class="col-sm-12 col-xs-12"> <p> &copy; @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year | <a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" rel="noopener" target="_blank" title="View site uptime information"> Site Status &amp; Uptime </a> </p> </div> </div> </footer>
@model SiteOptions <hr /> <footer> <p class="hidden-sm hidden-xs"> &copy; @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year | <a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" rel="noopener" target="_blank" title="View site uptime information"> Site Status &amp; Uptime </a> | Built from <a id="link-git-commit" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub"> @string.Join(string.Empty, GitMetadata.Commit.Take(7)) </a> on <a id="link-git-branch" href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub"> @GitMetadata.Branch </a> <span id="build-date" data-format="YYYY-MM-DD HH:mm Z" data-timestamp="@GitMetadata.Timestamp.ToString("u", CultureInfo.InvariantCulture)"></span> | Sponsored by <a id="link-browserstack" href="https://www.browserstack.com/"> <noscript> <img src="@Url.CdnContent("browserstack.svg", Model)" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" /> </noscript> <lazyimg src="@Url.CdnContent("browserstack.svg", Model)" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" /> </a> </p> <div class="row hidden-md hidden-lg"> <div class="col-sm-12 col-xs-12"> &copy; @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year | <a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" rel="noopener" target="_blank" title="View site uptime information"> Site Status &amp; Uptime </a> </div> <div class="col-sm-12 col-xs-12"> Sponsored by <a id="link-browserstack" href="https://www.browserstack.com/"> <noscript> <img src="@Url.CdnContent("browserstack.svg", Model)" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" /> </noscript> <lazyimg src="@Url.CdnContent("browserstack.svg", Model)" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" /> </a> </div> </div> </footer>
apache-2.0
C#
bb7ab08c9b5b05e229ba36d4de922f5786cf0110
Update XMLTests.cs
keith-hall/Extensions,keith-hall/Extensions
tests/XMLTests.cs
tests/XMLTests.cs
using System; using System.Xml.Linq; using HallLibrary.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class XMLTests { [TestMethod] public void TestToDataTable() { var xe = XElement.Parse(@"<root><row><id example='test'>7</id><name><last>Bloggs</last><first>Fred</first></name></row><anotherRow><id>6</id><name><first>Joe</first><last>Bloggs</last></name></anotherRow></root>"); var dt = XML.ToDataTable(xe, "/", true, true); Assert.IsTrue(dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName).SequenceEqual(new [] { "id/@example", "id", "name/first", "name/last" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(0).SequenceEqual(new object[] { "test", DBNull.Value })); Assert.IsTrue(dt.Rows.GetValuesInColumn(1).SequenceEqual(new [] { "7", "6" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(2).SequenceEqual(new [] { "Fred", "Joe" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(3).SequenceEqual(new [] { "Bloggs", "Bloggs" })); Assert.AreEqual(dt.TableName, "root"); xe = XElement.Parse(@"<root><row><id example='test'>7</id><name><last>Bloggs</last><first>Fred</first></name></row><row><id>6</id><name><first>Joe</first><last>Bloggs</last></name></row></root>"); dt = XML.ToDataTable(xe, ".", false, false); Assert.IsTrue(dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName).SequenceEqual(new [] { "id", "first.name", "last.name" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(0).SequenceEqual(new [] { "7", "6" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(1).SequenceEqual(new [] { "Fred", "Joe" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(2).SequenceEqual(new [] { "Bloggs", "Bloggs" })); Assert.AreEqual(dt.TableName, "row"); dt = XML.ToDataTable(xe, null, false, false); Assert.IsTrue(dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName).SequenceEqual(new [] { "id", "first", "last" })); } [TestMethod] public void TestToDataTableDuplicateColumnNames() { var xe = XElement.Parse(@"<root><row><client><id>1</id><name>Joe Bloggs</name></client><address><id>459</id><country>Ireland</country></address></row><row><client><id>2</id><name>Fred Bloggs</name></client><address><id>214</id><country>Wales</country></address></row></root>"); var dt = XML.ToDataTable(xe, null, false, false); Assert.IsTrue(dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName).SequenceEqual(new [] { "id/client", "name", "id/address", "country" })); } } }
using System; using System.Xml.Linq; using HallLibrary.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class XMLTests { [TestMethod] public void TestToDataTable() { var xe = XElement.Parse(@"<root><row><id example='test'>7</id><name><last>Bloggs</last><first>Fred</first></name></row><anotherRow><id>6</id><name><first>Joe</first><last>Bloggs</last></name></anotherRow></root>"); var dt = XML.ToDataTable(xe, "/", true, true); Assert.IsTrue(dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName).SequenceEqual(new [] { "id/@example", "id", "name/first", "name/last" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(0).SequenceEqual(new object[] { "test", DBNull.Value })); Assert.IsTrue(dt.Rows.GetValuesInColumn(1).SequenceEqual(new [] { "7", "6" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(2).SequenceEqual(new [] { "Fred", "Joe" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(3).SequenceEqual(new [] { "Bloggs", "Bloggs" })); Assert.AreEqual(dt.TableName, "root"); xe = XElement.Parse(@"<root><row><id example='test'>7</id><name><last>Bloggs</last><first>Fred</first></name></row><row><id>6</id><name><first>Joe</first><last>Bloggs</last></name></row></root>"); dt = XML.ToDataTable(xe, ".", false, false); Assert.IsTrue(dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName).SequenceEqual(new [] { "id", "first.name", "last.name" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(0).SequenceEqual(new [] { "7", "6" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(1).SequenceEqual(new [] { "Fred", "Joe" })); Assert.IsTrue(dt.Rows.GetValuesInColumn(2).SequenceEqual(new [] { "Bloggs", "Bloggs" })); Assert.AreEqual(dt.TableName, "row"); dt = XML.ToDataTable(xe, null, false, false); Assert.IsTrue(dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName).SequenceEqual(new [] { "id", "first", "last" })); } } }
apache-2.0
C#
d50501663533378778df3ef00403b8cbbdc135fa
Update PathSize.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/ViewModels/Shapes/Path/PathSize.cs
src/Core2D/ViewModels/Shapes/Path/PathSize.cs
using System; using System.Collections.Generic; using System.Globalization; namespace Core2D.Path { /// <summary> /// Path size. /// </summary> public class PathSize : ObservableObject, IPathSize { private double _width; private double _height; /// <inheritdoc/> public double Width { get => _width; set => Update(ref _width, value); } /// <inheritdoc/> public double Height { get => _height; set => Update(ref _height, value); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { throw new NotImplementedException(); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() => $"{Width.ToString(CultureInfo.InvariantCulture)},{Height.ToString(CultureInfo.InvariantCulture)}"; /// <summary> /// Check whether the <see cref="Width"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeWidth() => _width != default; /// <summary> /// Check whether the <see cref="Height"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeHeight() => _height != default; } }
using System; using System.Collections.Generic; namespace Core2D.Path { /// <summary> /// Path size. /// </summary> public class PathSize : ObservableObject, IPathSize { private double _width; private double _height; /// <inheritdoc/> public double Width { get => _width; set => Update(ref _width, value); } /// <inheritdoc/> public double Height { get => _height; set => Update(ref _height, value); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { throw new NotImplementedException(); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() => $"{Width},{Height}"; /// <summary> /// Check whether the <see cref="Width"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeWidth() => _width != default; /// <summary> /// Check whether the <see cref="Height"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeHeight() => _height != default; } }
mit
C#
d2ccf4a85a50d5a540f8f5d3f4959f8c8142e30b
Resolve #35 - Configure default options for view engine
csf-dev/ZPT-Sharp,csf-dev/ZPT-Sharp
CSF.Zpt.MVC/ZptViewEngine.cs
CSF.Zpt.MVC/ZptViewEngine.cs
using System; using System.Web.Mvc; using CSF.Zpt.Rendering; using CSF.Zpt.MVC.Rendering; namespace CSF.Zpt.MVC { public class ZptViewEngine : VirtualPathProviderViewEngine { #region constants private static readonly string[] ViewLocations = new [] { "~/Views/{1}/{0}.pt", "~/Views/Shared/{0}.pt", "~/Views/{1}/{0}.xml", "~/Views/Shared/{0}.xml", }; #endregion #region fields private RenderingMode _renderingMode; #endregion #region properties public RenderingOptions RenderingOptions { get; set; } public RenderingMode RenderingMode { get { return _renderingMode; } set { if(!value.IsDefinedValue()) { throw new ArgumentException(Resources.ExceptionMessages.InvalidRenderingMode, nameof(value)); } _renderingMode = value; } } public System.Text.Encoding InputEncoding { get; set; } #endregion #region overrides protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new ZptView(controllerContext.HttpContext.Server.MapPath(viewPath)) { RenderingOptions = RenderingOptions, RenderingMode = RenderingMode, InputEncoding = InputEncoding, }; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new ZptView(controllerContext.HttpContext.Server.MapPath(partialPath)) { RenderingOptions = RenderingOptions, RenderingMode = RenderingMode, InputEncoding = InputEncoding, }; } #endregion #region constructor public ZptViewEngine() { this.ViewLocationFormats = ViewLocations; this.PartialViewLocationFormats = ViewLocations; this.RenderingOptions = new DefaultRenderingOptions(contextFactory: new MvcRenderingContextFactory(), omitXmlDeclaration: true); } #endregion } }
using System; using System.Web.Mvc; using CSF.Zpt.Rendering; using CSF.Zpt.MVC.Rendering; namespace CSF.Zpt.MVC { public class ZptViewEngine : VirtualPathProviderViewEngine { #region constants private static readonly string[] ViewLocations = new [] { "~/Views/{1}/{0}.pt", "~/Views/Shared/{0}.pt", "~/Views/{1}/{0}.xml", "~/Views/Shared/{0}.xml", }; #endregion #region fields private RenderingMode _renderingMode; #endregion #region properties public RenderingOptions RenderingOptions { get; set; } public RenderingMode RenderingMode { get { return _renderingMode; } set { if(!value.IsDefinedValue()) { throw new ArgumentException(Resources.ExceptionMessages.InvalidRenderingMode, nameof(value)); } _renderingMode = value; } } public System.Text.Encoding InputEncoding { get; set; } #endregion #region overrides protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new ZptView(controllerContext.HttpContext.Server.MapPath(viewPath)) { RenderingOptions = RenderingOptions, RenderingMode = RenderingMode, InputEncoding = InputEncoding, }; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new ZptView(controllerContext.HttpContext.Server.MapPath(partialPath)) { RenderingOptions = RenderingOptions, RenderingMode = RenderingMode, InputEncoding = InputEncoding, }; } #endregion #region constructor public ZptViewEngine() { this.ViewLocationFormats = ViewLocations; this.PartialViewLocationFormats = ViewLocations; this.RenderingOptions = new DefaultRenderingOptions(contextFactory: new MvcRenderingContextFactory()); } #endregion } }
mit
C#
aab51be8ffe3339854dbb3784c38c1c178cdfd71
Comment unused code
Zeugma440/atldotnet
ATL/Utils/FNV1a.cs
ATL/Utils/FNV1a.cs
// Copyright (c) 2015, 2016 Sedat Kapanoglu // MIT License - see LICENSE file for details namespace HashDepot { /// <summary> /// FNV-1a Hash functions /// </summary> public static class Fnv1a { /// <summary> /// Calculate 32-bit FNV-1a hash value /// </summary> public static uint Hash32(byte[] buffer) { const uint offsetBasis32 = 2166136261; const uint prime32 = 16777619; //Require.NotNull(buffer, "buffer"); uint result = offsetBasis32; for (uint i=0;i<buffer.Length;i++) { result = prime32 * (result ^ i); } return result; } /* /// <summary> /// Calculate 64-bit FNV-1a hash value /// </summary> public static ulong Hash64(byte[] buffer) { const ulong offsetBasis64 = 14695981039346656037; const ulong prime64 = 1099511628211; //Require.NotNull(buffer, "buffer"); ulong result = offsetBasis64; for (uint i = 0; i < buffer.Length; i++) { result = prime64 * (result ^ i); } return result; } */ } }
// Copyright (c) 2015, 2016 Sedat Kapanoglu // MIT License - see LICENSE file for details namespace HashDepot { /// <summary> /// FNV-1a Hash functions /// </summary> public static class Fnv1a { /// <summary> /// Calculate 32-bit FNV-1a hash value /// </summary> public static uint Hash32(byte[] buffer) { const uint offsetBasis32 = 2166136261; const uint prime32 = 16777619; //Require.NotNull(buffer, "buffer"); uint result = offsetBasis32; for (uint i=0;i<buffer.Length;i++) { result = prime32 * (result ^ i); } return result; } /// <summary> /// Calculate 64-bit FNV-1a hash value /// </summary> public static ulong Hash64(byte[] buffer) { const ulong offsetBasis64 = 14695981039346656037; const ulong prime64 = 1099511628211; //Require.NotNull(buffer, "buffer"); ulong result = offsetBasis64; for (uint i = 0; i < buffer.Length; i++) { result = prime64 * (result ^ i); } return result; } } }
mit
C#
dde6896fcd51ccc4a878596a899f24c50de7822f
Update HeadlessGameHostTest post-rebase
Tom94/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,NeoAdonis/osu-framework,naoey/osu-framework,peppy/osu-framework,default0/osu-framework,smoogipooo/osu-framework,naoey/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,default0/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,Tom94/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,NeoAdonis/osu-framework,DrabWeb/osu-framework,RedNesto/osu-framework,ZLima12/osu-framework,paparony03/osu-framework,RedNesto/osu-framework
osu.Framework.Desktop.Tests/Platform/HeadlessGameHostTest.cs
osu.Framework.Desktop.Tests/Platform/HeadlessGameHostTest.cs
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Desktop.Platform; using osu.Framework.Platform; namespace osu.Framework.Desktop.Tests.Platform { [TestFixture] public class HeadlessGameHostTest { private class Foobar { public string Bar; } [Test] public async Task TestIPC() { using (var server = new HeadlessGameHost()) using (var client = new HeadlessGameHost()) { server.Load(null); client.Load(null); Assert.IsTrue(server.IsPrimaryInstance); Assert.IsFalse(client.IsPrimaryInstance); var serverChannel = new IpcChannel<Foobar>(server); var clientChannel = new IpcChannel<Foobar>(client); bool messageReceived = false; serverChannel.MessageReceived += message => { messageReceived = true; Assert.AreEqual("example", message.Bar); }; await clientChannel.SendMessage(new Foobar { Bar = "example" }); var watch = new Stopwatch(); while (!messageReceived) { // hacky, yes. This gives the server code time to process the message Thread.Sleep(1); if (watch.Elapsed.TotalSeconds > 1) Assert.Fail(); } Assert.Pass(); } } } }
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Desktop.Platform; using osu.Framework.Platform; namespace osu.Framework.Desktop.Tests.Platform { [TestFixture] public class HeadlessGameHostTest { private class Foobar { public string Bar; } [Test] public async Task TestIPC() { using (var server = new HeadlessGameHost()) using (var client = new HeadlessGameHost()) { server.Load(); client.Load(); Assert.IsTrue(server.IsPrimaryInstance); Assert.IsFalse(client.IsPrimaryInstance); var serverChannel = new IpcChannel<Foobar>(server); var clientChannel = new IpcChannel<Foobar>(client); bool messageReceived = false; serverChannel.MessageReceived += message => { messageReceived = true; Assert.AreEqual("example", message.Bar); }; await clientChannel.SendMessage(new Foobar { Bar = "example" }); var watch = new Stopwatch(); while (!messageReceived) { // hacky, yes. This gives the server code time to process the message Thread.Sleep(1); if (watch.Elapsed.TotalSeconds > 1) Assert.Fail(); } Assert.Pass(); } } } }
mit
C#
a7c7bb310fe8a5cd4cd82478d0ffb50c6846a5ca
Update Program.cs
Jungro/Test
TestWinform/Program.cs
TestWinform/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace TestWinform { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace TestWinform { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
mit
C#
56debce03599fa318b8eaa0b450ec5c67313ce32
Enable developer exception page
surlycoder/truck-router
TruckRouter/Program.cs
TruckRouter/Program.cs
using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
using TruckRouter.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddTransient<IMazeSolver, MazeSolverBFS>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); //app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
mit
C#
5c0f102927615362293c36b559d69f742eabd56f
Update LocationsController.cs
shijuvar/react-aspnet,chimpinano/react-aspnet,shijuvar/react-aspnet,shijuvar/react-aspnet,rartola/Test,rartola/Test,rartola/Test,chimpinano/react-aspnet,chimpinano/react-aspnet
ResourceMetadata/ResourceMetadata.API/Controllers/LocationsController.cs
ResourceMetadata/ResourceMetadata.API/Controllers/LocationsController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using ResourceMetadata.API.ViewModels; using ResourceMetadata.Model; using ResourceMetadata.Service; using AutoMapper; using System.Threading; using Microsoft.AspNet.Identity; namespace ResourceMetadata.API.Controllers { public class LocationsController : ApiController { private readonly ILocationService locationService; private readonly UserManager<ApplicationUser> userManager; public LocationsController(ILocationService locationService, UserManager<ApplicationUser> userManager) { this.locationService = locationService; this.userManager = userManager; } public IHttpActionResult Get() { var locations = locationService.GetLocations(); var locationViewModels = new List<LocationViewModel>(); Mapper.Map(locations, locationViewModels); return Ok(locationViewModels); } public IHttpActionResult Get(int id) { var location = locationService.GetLocationById(id); var viewModel = new LocationViewModel(); Mapper.Map(location, viewModel); return Ok(viewModel); } //[Authorize(Roles = "Admin")] public IHttpActionResult Post(LocationViewModel location) { Location entity = new Location(); Mapper.Map(location, entity); entity.CreatedOn = DateTime.UtcNow; locationService.AddLocation(entity); Mapper.Map(entity, location); return Created(Url.Link("DefaultApi", new { controller = "Locations", id = location.Id }), location); } //[Authorize(Roles = "Admin")] public IHttpActionResult Put(int id, LocationViewModel locationViewModel) { locationViewModel.Id = id; var location = locationService.GetLocationById(id); Mapper.Map(locationViewModel, location); locationService.UpdateLoaction(location); return Ok(locationViewModel); } //[Authorize(Roles = "Admin")] public IHttpActionResult Delete(int id) { locationService.DeleteLocation(id); return Ok(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using ResourceMetadata.API.ViewModels; using ResourceMetadata.Model; using ResourceMetadata.Service; using AutoMapper; using System.Threading; using Microsoft.AspNet.Identity; namespace ResourceMetadata.API.Controllers { public class LocationsController : ApiController { private readonly ILocationService locationService; private readonly UserManager<ApplicationUser> userManager; public LocationsController(ILocationService locationService, UserManager<ApplicationUser> userManager) { this.locationService = locationService; this.userManager = userManager; } public IHttpActionResult Get() { var locations = locationService.GetLocations(); var locationViewModels = new List<LocationViewModel>(); Mapper.Map(locations, locationViewModels); return Ok(locationViewModels); } public IHttpActionResult Get(int id) { var location = locationService.GetLocationById(id); var viewModel = new LocationViewModel(); Mapper.Map(location, viewModel); return Ok(viewModel); } //[Authorize(Roles = "Admin")] public IHttpActionResult Post(LocationViewModel location) { Location entity = new Location(); Mapper.Map(location, entity); entity.CreatedOn = DateTime.UtcNow; locationService.AddLocation(entity); Mapper.Map(entity, location); return Created(Url.Link("DefaultApi", new { controller = "Locations", id = location.Id }), location); } //[Authorize(Roles = "Admin")] public IHttpActionResult Put(int id, LocationViewModel locationViewModel) { locationViewModel.Id = id; var location = locationService.GetLocationById(id); Mapper.Map(locationViewModel, location); locationService.UpdateLoaction(location); return Ok(locationViewModel); } [Authorize(Roles = "Admin")] public IHttpActionResult Delete(int id) { locationService.DeleteLocation(id); return Ok(); } } }
mit
C#
1546a714dc1e59a9d3f7ffcdb8b7909e32dc5ae1
Fix NullReferenceException
dimmpixeye/Unity3dTools
Assets/[0]Framework/Editor/SceneProcessors/SceneGenerator.cs
Assets/[0]Framework/Editor/SceneProcessors/SceneGenerator.cs
using System.Linq; using Homebrew; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; using UnityEngine; [InitializeOnLoad] public class SceneGenerator { static SceneGenerator() { EditorSceneManager.newSceneCreated += SceneCreating; EditorSceneManager.sceneSaved += SceneSaved; } private static void SceneSaved(Scene scene) { var original = EditorBuildSettings.scenes; for (int i = 0; i < original.Length; i++) { var s = original[i].path; if (s != scene.path) continue; SaveSceneName.SaveScenesName(); return; } var newSettings = new EditorBuildSettingsScene[original.Length + 1]; System.Array.Copy(original, newSettings, original.Length); var sceneToAdd = new EditorBuildSettingsScene(scene.path, true); newSettings[newSettings.Length - 1] = sceneToAdd; EditorBuildSettings.scenes = newSettings; SaveSceneName.SaveScenesName(); } public static void SceneCreating(Scene scene, NewSceneSetup setup, NewSceneMode mode) { if (Camera.main == null) return; var camGO = Camera.main.gameObject; var light = GameObject.Find("Directional Light"); if (light != null) { GameObject.DestroyImmediate(light.gameObject); } GameObject.DestroyImmediate(camGO); new GameObject("[SETUP]"); var s = new GameObject("[SCENE]"); var d = new GameObject("Dynamic"); d.transform.parent = s.transform; Debug.Log("New scene created!"); } }
using System.Linq; using Homebrew; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; using UnityEngine; [InitializeOnLoad] public class SceneGenerator { static SceneGenerator() { EditorSceneManager.newSceneCreated += SceneCreating; EditorSceneManager.sceneSaved += SceneSaved; } private static void SceneSaved(Scene scene) { var original = EditorBuildSettings.scenes; for (int i = 0; i < original.Length; i++) { var s = original[i].path; if (s != scene.path) continue; SaveSceneName.SaveScenesName(); return; } var newSettings = new EditorBuildSettingsScene[original.Length + 1]; System.Array.Copy(original, newSettings, original.Length); var sceneToAdd = new EditorBuildSettingsScene(scene.path, true); newSettings[newSettings.Length - 1] = sceneToAdd; EditorBuildSettings.scenes = newSettings; SaveSceneName.SaveScenesName(); } public static void SceneCreating(Scene scene, NewSceneSetup setup, NewSceneMode mode) { if (Camera.main == null) return; var camGO = Camera.main.gameObject; var lightGO = GameObject.Find("Directional Light").gameObject; GameObject.DestroyImmediate(lightGO); GameObject.DestroyImmediate(camGO); new GameObject("[SETUP]"); var s = new GameObject("[SCENE]"); var d = new GameObject("Dynamic"); d.transform.parent = s.transform; Debug.Log("New scene created!"); } }
mit
C#
5882eb6c3f8fc4f70db8a55599029688952eb187
Revert to v3 of the moviedb
ronaldme/Watcher,ronaldme/Watcher,ronaldme/Watcher
Watcher.Common/Urls.cs
Watcher.Common/Urls.cs
using System; using System.Configuration; namespace Watcher.Common { public class Urls { private static readonly string SuffixUrl = "?api_key=" + ConfigurationManager.AppSettings.Get("theMovieDb"); private const string PreFixUrl = "http://api.themoviedb.org/3/"; /// <summary> /// Movie urls /// </summary> public static string SearchMovie = FormatUrl("search/movie"); public static string SearchMovieById = "movie/"; public static string UpcomingMovies = FormatUrl("movie/upcoming"); public static string PopularMovies = FormatUrl("movie/popular"); /// <summary> /// Tv urls /// </summary> public static string SearchTv = FormatUrl("search/tv"); public static string SearchTvById = "tv/"; public static string TopRated = FormatUrl("tv/top_rated"); public static string PopularShows = FormatUrl("tv/popular"); public static string Seasons = "tv/57243/season/8" + SuffixUrl; /// <summary> /// Person urls /// </summary> public static string SearchPerson = FormatUrl("search/person"); public static string SearchPersonById = "person/"; public static string PopularPersons = FormatUrl("person/popular"); public static string PrefixImages = "http://image.tmdb.org/t/p/w185"; public static string SearchTvSeasons(int tvId, int season) { return $"{PreFixUrl}tv/{tvId}/season/{season}{SuffixUrl}"; } public static string PersonCredits(int personId) { return $"{PreFixUrl}person/{personId}/combined_credits{SuffixUrl}"; } public static string SearchBy(string searchUrl, int id) { return $"{PreFixUrl}{searchUrl}{id}{SuffixUrl}"; } private static string FormatUrl(string urlMiddlePart) { return $"{PreFixUrl}{urlMiddlePart}{SuffixUrl}"; } } }
using System; using System.Configuration; namespace Watcher.Common { public class Urls { private static readonly string SuffixUrl = "?api_key=" + ConfigurationManager.AppSettings.Get("theMovieDb"); private const string PreFixUrl = "http://api.themoviedb.org/4/"; /// <summary> /// Movie urls /// </summary> public static string SearchMovie = FormatUrl("search/movie"); public static string SearchMovieById = "movie/"; public static string UpcomingMovies = FormatUrl("movie/upcoming"); public static string PopularMovies = FormatUrl("movie/popular"); /// <summary> /// Tv urls /// </summary> public static string SearchTv = FormatUrl("search/tv"); public static string SearchTvById = "tv/"; public static string TopRated = FormatUrl("tv/top_rated"); public static string PopularShows = FormatUrl("tv/popular"); public static string Seasons = "tv/57243/season/8" + SuffixUrl; /// <summary> /// Person urls /// </summary> public static string SearchPerson = FormatUrl("search/person"); public static string SearchPersonById = "person/"; public static string PopularPersons = FormatUrl("person/popular"); public static string PrefixImages = "http://image.tmdb.org/t/p/w185"; public static string SearchTvSeasons(int tvId, int season) { return $"{PreFixUrl}tv/{tvId}/season/{season}{SuffixUrl}"; } public static string PersonCredits(int personId) { return $"{PreFixUrl}person/{personId}/combined_credits{SuffixUrl}"; } public static string SearchBy(string searchUrl, int id) { return $"{PreFixUrl}{searchUrl}{id}{SuffixUrl}"; } private static string FormatUrl(string urlMiddlePart) { return $"{PreFixUrl}{urlMiddlePart}{SuffixUrl}"; } } }
mit
C#
c9659b32d82f4ea5f511dec22398cd6fcdb1339b
Fix bug with querying ProductPrices in SampleAPI case study
EMResearch/EMB,EMResearch/EMB,EMResearch/EMB,EMResearch/EMB,EMResearch/EMB,EMResearch/EMB,EMResearch/EMB,EMResearch/EMB,EMResearch/EMB,EMResearch/EMB
dotnet_3/cs/rest/SampleProject/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductPriceProvider.cs
dotnet_3/cs/rest/SampleProject/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductPriceProvider.cs
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using Dapper; using SampleProject.Domain.Products; using SampleProject.Domain.SharedKernel; namespace SampleProject.Application.Orders.PlaceCustomerOrder { public static class ProductPriceProvider { public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection) { var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " + $"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " + $"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " + $"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " + "FROM orders.ProductPrices AS [ProductPrice]"); return productPrices.AsList() .Select(x => new ProductPriceData( new ProductId(x.ProductId), MoneyValue.Of(x.Value, x.Currency))) .ToList(); } private sealed class ProductPriceResponse { public Guid ProductId { get; set; } public decimal Value { get; set; } public string Currency { get; set; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using Dapper; using SampleProject.Domain.Products; using SampleProject.Domain.SharedKernel; namespace SampleProject.Application.Orders.PlaceCustomerOrder { public static class ProductPriceProvider { public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection) { var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " + $"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " + $"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " + $"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " + "FROM orders.v_ProductPrices AS [ProductPrice]"); return productPrices.AsList() .Select(x => new ProductPriceData( new ProductId(x.ProductId), MoneyValue.Of(x.Value, x.Currency))) .ToList(); } private sealed class ProductPriceResponse { public Guid ProductId { get; set; } public decimal Value { get; set; } public string Currency { get; set; } } } }
apache-2.0
C#
23f02d65665525d27122d549f0a622490899a6e5
rename test method
dipakboyed/epibook.github.io.Puzzles
EPIUnitTests/DynamicProgramming/KnapsackProblemUnitTest.cs
EPIUnitTests/DynamicProgramming/KnapsackProblemUnitTest.cs
using EPI.DynamicProgramming; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.DynamicProgramming { [TestClass] public class KnapsackProblemUnitTest { [TestMethod] public void MaximizeKnapsackValue() { KnapsackProblem.Clock[] store = new KnapsackProblem.Clock[] { new KnapsackProblem.Clock() { Price = 65, Weight = 20 }, new KnapsackProblem.Clock() { Price = 35, Weight = 8 }, new KnapsackProblem.Clock() { Price = 245, Weight = 60 }, new KnapsackProblem.Clock() { Price = 195, Weight = 55 }, new KnapsackProblem.Clock() { Price = 65, Weight = 40 }, new KnapsackProblem.Clock() { Price = 150, Weight = 70 }, new KnapsackProblem.Clock() { Price = 275, Weight = 85 }, new KnapsackProblem.Clock() { Price = 155, Weight = 25 }, new KnapsackProblem.Clock() { Price = 120, Weight = 30 }, new KnapsackProblem.Clock() { Price = 320, Weight = 65 }, new KnapsackProblem.Clock() { Price = 75, Weight = 75 }, new KnapsackProblem.Clock() { Price = 40, Weight = 10 }, new KnapsackProblem.Clock() { Price = 200, Weight = 95 }, new KnapsackProblem.Clock() { Price = 100, Weight = 50 }, new KnapsackProblem.Clock() { Price = 220, Weight = 40 }, new KnapsackProblem.Clock() { Price = 99, Weight = 10 } }; KnapsackProblem.Maximize(store, 130).Should().Be(695); } } }
using EPI.DynamicProgramming; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.DynamicProgramming { [TestClass] public class KnapsackProblemUnitTest { [TestMethod] public void TestMethod1() { KnapsackProblem.Clock[] store = new KnapsackProblem.Clock[] { new KnapsackProblem.Clock() { Price = 65, Weight = 20 }, new KnapsackProblem.Clock() { Price = 35, Weight = 8 }, new KnapsackProblem.Clock() { Price = 245, Weight = 60 }, new KnapsackProblem.Clock() { Price = 195, Weight = 55 }, new KnapsackProblem.Clock() { Price = 65, Weight = 40 }, new KnapsackProblem.Clock() { Price = 150, Weight = 70 }, new KnapsackProblem.Clock() { Price = 275, Weight = 85 }, new KnapsackProblem.Clock() { Price = 155, Weight = 25 }, new KnapsackProblem.Clock() { Price = 120, Weight = 30 }, new KnapsackProblem.Clock() { Price = 320, Weight = 65 }, new KnapsackProblem.Clock() { Price = 75, Weight = 75 }, new KnapsackProblem.Clock() { Price = 40, Weight = 10 }, new KnapsackProblem.Clock() { Price = 200, Weight = 95 }, new KnapsackProblem.Clock() { Price = 100, Weight = 50 }, new KnapsackProblem.Clock() { Price = 220, Weight = 40 }, new KnapsackProblem.Clock() { Price = 99, Weight = 10 } }; KnapsackProblem.Maximize(store, 130).Should().Be(695); } } }
mit
C#
d3c236002234228eff30bf5d3cb780be26fa9462
Fix namespace of JsonExceptionHandling
civicsource/webapi-utils,civicsource/http
aspnetcore/JsonExceptionHandling.cs
aspnetcore/JsonExceptionHandling.cs
using System; using System.Net; using System.Text; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Newtonsoft.Json; namespace Archon.AspNetCore { public static class JsonExceptionHandling { public static IApplicationBuilder UseJsonExceptionHandling(this IApplicationBuilder app) { app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { var err = JsonConvert.SerializeObject(BuildError(ex.Error)); await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(err), 0, err.Length).ConfigureAwait(false); } object BuildError(Exception exception) { if (exception == null) return null; return new { exception.Message, exception.StackTrace, InnerException = BuildError(exception.InnerException) }; } }); }); return app; } } }
using System; using System.Net; using System.Text; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Newtonsoft.Json; namespace Archon.Http { public static class JsonExceptionHandling { public static IApplicationBuilder UseJsonExceptionHandling(this IApplicationBuilder app) { app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { var err = JsonConvert.SerializeObject(BuildError(ex.Error)); await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(err), 0, err.Length).ConfigureAwait(false); } object BuildError(Exception exception) { if (exception == null) return null; return new { exception.Message, exception.StackTrace, InnerException = BuildError(exception.InnerException) }; } }); }); return app; } } }
mit
C#
0bb1d6bcf9fdfac3052715a4674385ad9ef5dc52
Remove redundant code
drewnoakes/boing
Boing/PointMass.cs
Boing/PointMass.cs
using System.Diagnostics; namespace Boing { public sealed class PointMass { private Vector2f _force; public float Mass { get; set; } public bool IsPinned { get; set; } public object Tag { get; set; } public Vector2f Position { get; set; } public Vector2f Velocity { get; set; } public PointMass(float mass = 1.0f, Vector2f? position = null) { Mass = mass; Position = position ?? Vector2f.Random(); } public void ApplyForce(Vector2f force) { Debug.Assert(!float.IsNaN(force.X) && !float.IsNaN(force.Y), "!float.IsNaN(force.X) && !float.IsNaN(force.Y)"); Debug.Assert(!float.IsInfinity(force.X) && !float.IsInfinity(force.Y), "!float.IsInfinity(force.X) && !float.IsInfinity(force.Y)"); // Accumulate force _force += force; } public void ApplyImpulse(Vector2f impulse) { // Update velocity Velocity += impulse/Mass; } public void Update(float dt) { // Update velocity Velocity += _force/Mass*dt; // Update position Position += Velocity*dt; Debug.Assert(!float.IsNaN(Position.X) && !float.IsNaN(Position.Y), "!float.IsNaN(Position.X) && !float.IsNaN(Position.Y)"); Debug.Assert(!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y), "!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y)"); // Clear force _force = Vector2f.Zero; } } }
using System.Collections.Generic; using System.Diagnostics; namespace Boing { public sealed class PointMass { private Vector2f _force; public float Mass { get; set; } public bool IsPinned { get; set; } public object Tag { get; set; } public Vector2f Position { get; set; } public Vector2f Velocity { get; set; } public PointMass(float mass = 1.0f, Vector2f? position = null) { Mass = mass; Position = position ?? Vector2f.Random(); } public void ApplyForce(Vector2f force) { Debug.Assert(!float.IsNaN(force.X) && !float.IsNaN(force.Y), "!float.IsNaN(force.X) && !float.IsNaN(force.Y)"); Debug.Assert(!float.IsInfinity(force.X) && !float.IsInfinity(force.Y), "!float.IsInfinity(force.X) && !float.IsInfinity(force.Y)"); // Accumulate force _force += force; } public void ApplyImpulse(Vector2f impulse) { // Update velocity Velocity += impulse/Mass; } public void Update(float dt) { // Update velocity Velocity += _force/Mass*dt; // Update position Position += Velocity*dt; Debug.Assert(!float.IsNaN(Position.X) && !float.IsNaN(Position.Y), "!float.IsNaN(Position.X) && !float.IsNaN(Position.Y)"); Debug.Assert(!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y), "!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y)"); // Clear force _force = Vector2f.Zero; } } }
apache-2.0
C#
06d3a7bf5b45adb6bca6238ca3cfe9331eb9dda6
Add more RFC 7748 test vectors
ektrah/nsec
tests/Rfc/X25519Tests.cs
tests/Rfc/X25519Tests.cs
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Rfc { public static class X25519Tests { public static readonly TheoryData<string, string, string> Rfc7748TestVectors = new TheoryData<string, string, string> { // Section 5.2 { "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552" }, { "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", "e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493", "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957" }, // Section 6.1 { "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742" }, { "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a", "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742" }, }; [Theory] [MemberData(nameof(Rfc7748TestVectors))] public static void Test(string privateKey, string publicKey, string sharedSecret) { var a = new X25519(); var kdf = new HkdfSha256(); using (var k = Key.Import(a, privateKey.DecodeHex(), KeyBlobFormat.RawPrivateKey)) using (var sharedSecretExpected = SharedSecret.Import(sharedSecret.DecodeHex())) using (var sharedSecretActual = a.Agree(k, PublicKey.Import(a, publicKey.DecodeHex(), KeyBlobFormat.RawPublicKey))) { var expected = kdf.Extract(sharedSecretExpected, ReadOnlySpan<byte>.Empty); var actual = kdf.Extract(sharedSecretActual, ReadOnlySpan<byte>.Empty); Assert.Equal(expected, actual); } } } }
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Rfc { public static class X25519Tests { public static readonly TheoryData<string, string, string> Rfc7748TestVectors = new TheoryData<string, string, string> { { "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552" }, { "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", "e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493", "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957" }, }; [Theory] [MemberData(nameof(Rfc7748TestVectors))] public static void Test(string privateKey, string publicKey, string sharedSecret) { var a = new X25519(); var kdf = new HkdfSha256(); using (var k = Key.Import(a, privateKey.DecodeHex(), KeyBlobFormat.RawPrivateKey)) using (var sharedSecretExpected = SharedSecret.Import(sharedSecret.DecodeHex())) using (var sharedSecretActual = a.Agree(k, PublicKey.Import(a, publicKey.DecodeHex(), KeyBlobFormat.RawPublicKey))) { var expected = kdf.Extract(sharedSecretExpected, ReadOnlySpan<byte>.Empty); var actual = kdf.Extract(sharedSecretActual, ReadOnlySpan<byte>.Empty); Assert.Equal(expected, actual); } } } }
mit
C#
13ee16bc7c39a5933c84d67e78dbcbd0fe402650
add try.catch
sebastus/AzureFunctionForSplunk
shared/sendToSplunk.csx
shared/sendToSplunk.csx
#r "Newtonsoft.Json" using System; using System.Dynamic; using System.Net; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; public class SingleHttpClientInstance { private static readonly HttpClient HttpClient; static SingleHttpClientInstance() { HttpClient = new HttpClient(); } public static async Task<HttpResponseMessage> SendToSplunk(HttpRequestMessage req) { HttpResponseMessage response = await HttpClient.SendAsync(req); return response; } } static async Task SendMessagesToSplunk(string[] messages, TraceWriter log) { var converter = new ExpandoObjectConverter(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( delegate { return true; }); var client = new SingleHttpClientInstance(); string newClientContent = ""; foreach (var message in messages) { bool parsedOk = true; dynamic obj = ""; try { obj = JsonConvert.DeserializeObject<ExpandoObject>(message, converter); } catch (Exception e) { parsedOk = false; log.Info($"Error {e} caught while parsing message: {message}"); } if (parsedOk) { foreach (var record in obj.records) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(record); newClientContent += "{\"event\": " + json + "}"; } } } HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://asplunktest.westus.cloudapp.azure.com:8088/services/collector/event"); req.Headers.Accept.Clear(); req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); req.Headers.Add("Authorization", "Splunk 73A24AB7-60DD-4235-BF71-D892AE47F49D"); req.Content = new StringContent(newClientContent, Encoding.UTF8, "application/json"); HttpResponseMessage response = await SingleHttpClientInstance.SendToSplunk(req); }
#r "Newtonsoft.Json" using System; using System.Dynamic; using System.Net; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; public class SingleHttpClientInstance { private static readonly HttpClient HttpClient; static SingleHttpClientInstance() { HttpClient = new HttpClient(); } public static async Task<HttpResponseMessage> SendToSplunk(HttpRequestMessage req) { HttpResponseMessage response = await HttpClient.SendAsync(req); return response; } } static async Task SendMessagesToSplunk(string[] messages, TraceWriter log) { var converter = new ExpandoObjectConverter(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( delegate { return true; }); var client = new SingleHttpClientInstance(); string newClientContent = ""; foreach (var message in messages) { bool parsedOk = true; try { dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(message, converter); } catch (Exception e) { parsedOk = false; log.Info($"Error {e} caught while parsing message: {message}"); } if (parsedOk) { foreach (var record in obj.records) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(record); newClientContent += "{\"event\": " + json + "}"; } } } HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://asplunktest.westus.cloudapp.azure.com:8088/services/collector/event"); req.Headers.Accept.Clear(); req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); req.Headers.Add("Authorization", "Splunk 73A24AB7-60DD-4235-BF71-D892AE47F49D"); req.Content = new StringContent(newClientContent, Encoding.UTF8, "application/json"); HttpResponseMessage response = await SingleHttpClientInstance.SendToSplunk(req); }
mit
C#
852e1eac8b08df7ccbc6430437e9507242767f3d
fix Upgrade_20210924_RemoveParentTokenParentValue spacing
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20210924_RemoveParentTokenParentValue.cs
Signum.Upgrade/Upgrades/Upgrade_20210924_RemoveParentTokenParentValue.cs
using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Signum.Upgrade.Upgrades { class Upgrade_20210924_RemoveParentTokenParentValue : CodeUpgradeBase { public override string Description => "Remove parentToken / parentValue from FindOptions"; public override void Execute(UpgradeContext uctx) { Regex regex = new Regex(@"parentToken\s*:\s*(?<parentToken>[^,]+),(\s|\n)+parentValue\s*:\s*(?<parentValue>[^,}\r\n]+)"); uctx.ForeachCodeFile(@"*.ts, *.tsx", file => { file.Replace(regex, r => $"filterOptions: [{{ token: {r.Groups["parentToken"]}, value: {r.Groups["parentValue"]}}}] "); }); } } }
using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Signum.Upgrade.Upgrades { class Upgrade_20210924_RemoveParentTokenParentValue : CodeUpgradeBase { public override string Description => "Remove parentToken / parentValue from FindOptions"; public override void Execute(UpgradeContext uctx) { Regex regex = new Regex(@"parentToken\s*:\s*(?<parentToken>[^,]+),(\s|\n)+parentValue\s*:\s*(?<parentValue>[^,}\r\n]+)"); uctx.ForeachCodeFile(@"*.ts, *.tsx", file => { file.Replace(regex, r => $"filterOptions: [{{ token: {r.Groups["parentToken"]}, value: {r.Groups["parentValue"]}}}]"); }); } } }
mit
C#
bd8c5dfd11791b74a54a2b131e3b9360b2a92df5
Improve Enum display. Work Item #1985
CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork
trunk/Solutions/CslaGenFork/Metadata/ReportObjectNotFound.cs
trunk/Solutions/CslaGenFork/Metadata/ReportObjectNotFound.cs
using System.ComponentModel; using CslaGenerator.Design; namespace CslaGenerator.Metadata { [TypeConverter(typeof(EnumDescriptionOrCaseConverter))] public enum ReportObjectNotFound { None, [Description("IsLoaded Property")] IsLoadedProperty, ThrowException } }
using System.ComponentModel; using CslaGenerator.Design; namespace CslaGenerator.Metadata { [TypeConverter(typeof(EnumDescriptionOrCaseConverter))] public enum ReportObjectNotFound { None, IsLoadedProperty, ThrowException } }
mit
C#
f2c29c05f30f093b4b0f1ec3098dc17454defac9
Fix CF issue
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
using System; using System.Diagnostics; using NBitcoin.Secp256k1; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { // Each proof of a linear relation consists of multiple knowledge of // representation equations, all sharing a single witness comprised of several // secret scalars. // // Knowledge of representation means that given a curve point P, the prover // knows how to construct P from a set of predetermined generators. This is // commonly referred to as multi-exponentiation but that term implies // multiplicative notation for the group operation. Written additively and // indexing by `i`, each equation is of the form: // // P_i = x_1 * G_{i,1} + x_2 * G_{i,2} + ... + x_n * G_{i,n} // // Note that some of the generators for an equation can be the point at // infinity when a term in the witness does not play a part in the // representation of a specific point. internal class Equation { public Equation(GroupElement publicPoint, GroupElementVector generators) { Guard.NotNullOrEmpty(nameof(generators), generators); PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint); Generators = generators; } // Knowledge of representation asserts // P = x_1*G_1 + x_2*G_2 + ... // so we need a single public input and several generators public GroupElement PublicPoint { get; } public GroupElementVector Generators { get; } // Evaluate the verification equation corresponding to the one in the statement internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses) { // A challenge of 0 does not place any constraint on the witness if (challenge.IsZero) { return false; } // the verification equation (for 1 generator case) is: // sG =? R + eP // where: // - R = kG is the public nonce, k is the secret nonce // - P = xG is the public input, x is the secret // - e is the challenge // - s is the response return responses * Generators == (publicNonce + challenge * PublicPoint); } // Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness internal static ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge) { // blinding terms are required in order to protect the witness (unless the // challenge is 0), so only respond if that is the case foreach (var secretNonce in secretNonces) { CryptoGuard.NotZero(nameof(secretNonce), secretNonce); } // Taking the discrete logarithms of both sides of the verification // equation with respect to G results in a formula for the response s // given k, e and x: // s = k + ex return secretNonces + challenge * witness; } [Conditional("DEBUG")] internal void CheckSolution(ScalarVector witness) { if (PublicPoint != witness * Generators) { throw new ArgumentException($"{nameof(witness)} is not solution of the equation"); } } } }
using System; using System.Diagnostics; using NBitcoin.Secp256k1; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { // Each proof of a linear relation consists of multiple knowledge of // representation equations, all sharing a single witness comprised of several // secret scalars. // // Knowledge of representation means that given a curve point P, the prover // knows how to construct P from a set of predetermined generators. This is // commonly referred to as multi-exponentiation but that term implies // multiplicative notation for the group operation. Written additively and // indexing by `i`, each equation is of the form: // // P_i = x_1 * G_{i,1} + x_2 * G_{i,2} + ... + x_n * G_{i,n} // // Note that some of the generators for an equation can be the point at // infinity when a term in the witness does not play a part in the // representation of a specific point. class Equation { public Equation(GroupElement publicPoint, GroupElementVector generators) { Guard.NotNullOrEmpty(nameof(generators), generators); PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint); Generators = generators; } // Knowledge of representation asserts // P = x_1*G_1 + x_2*G_2 + ... // so we need a single public input and several generators public GroupElement PublicPoint { get; } public GroupElementVector Generators { get; } // Evaluate the verification equation corresponding to the one in the statement internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses) { // A challenge of 0 does not place any constraint on the witness if (challenge.IsZero) { return false; } // the verification equation (for 1 generator case) is: // sG =? R + eP // where: // - R = kG is the public nonce, k is the secret nonce // - P = xG is the public input, x is the secret // - e is the challenge // - s is the response return responses * Generators == (publicNonce + challenge * PublicPoint); } // Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness internal static ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge) { // blinding terms are required in order to protect the witness (unless the // challenge is 0), so only respond if that is the case foreach (var secretNonce in secretNonces) { CryptoGuard.NotZero(nameof(secretNonce), secretNonce); } // Taking the discrete logarithms of both sides of the verification // equation with respect to G results in a formula for the response s // given k, e and x: // s = k + ex return secretNonces + challenge * witness; } [Conditional("DEBUG")] internal void CheckSolution(ScalarVector witness) { if (PublicPoint != witness * Generators) { throw new ArgumentException($"{nameof(witness)} is not solution of the equation"); } } } }
mit
C#
2345e106354dcdc23d89401c40daa066a1d5e40f
Reduce potential value updates when setting localisablestring
ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Localisation/LocalisationManager_LocalisedBindableString.cs
osu.Framework/Localisation/LocalisationManager_LocalisedBindableString.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Configuration; using osu.Framework.IO.Stores; namespace osu.Framework.Localisation { public partial class LocalisationManager { private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString { private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>(); private LocalisableString text; public LocalisedBindableString(IBindable<IResourceStore<string>> storage) { this.storage.BindTo(storage); this.storage.BindValueChanged(_ => updateValue(), true); } private void updateValue() { string newText = text.Text; if (text.ShouldLocalise && storage.Value != null) newText = storage.Value.Get(newText); if (text.Args != null && !string.IsNullOrEmpty(newText)) { try { newText = string.Format(newText, text.Args); } catch (FormatException) { // Prevent crashes if the formatting fails. The string will be in a non-formatted state. } } Value = newText; } LocalisableString ILocalisedBindableString.Original { set { if (text == value) return; text = value; updateValue(); } } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Configuration; using osu.Framework.IO.Stores; namespace osu.Framework.Localisation { public partial class LocalisationManager { private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString { private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>(); private LocalisableString text; public LocalisedBindableString(IBindable<IResourceStore<string>> storage) { this.storage.BindTo(storage); this.storage.BindValueChanged(_ => updateValue(), true); } private void updateValue() { string newText = text.Text; if (text.ShouldLocalise && storage.Value != null) newText = storage.Value.Get(newText); if (text.Args != null && !string.IsNullOrEmpty(newText)) { try { newText = string.Format(newText, text.Args); } catch (FormatException) { // Prevent crashes if the formatting fails. The string will be in a non-formatted state. } } Value = newText; } LocalisableString ILocalisedBindableString.Original { set { text = value; updateValue(); } } } } }
mit
C#
0935ac37775e6e4990fe21243d89c8048d78b358
Create server side API for single multiple answer question
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } /// <summary> /// Adding single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } }
mit
C#
b7e6151d6839d78fa582d334073448feff9f5389
Remove default image
grantcolley/wpfcontrols
DevelopmentInProgress.WPFControls/Converters/UriStringToImageConverter.cs
DevelopmentInProgress.WPFControls/Converters/UriStringToImageConverter.cs
//----------------------------------------------------------------------- // <copyright file="UriStringToImageConverter.cs" company="Development In Progress Ltd"> // Copyright © Development In Progress Ltd 2013. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media.Imaging; namespace DevelopmentInProgress.WPFControls.Converters { /// <summary> /// Converts a Uri string to an image. /// </summary> public sealed class UriStringToImageConverter : IValueConverter { /// <summary> /// Converts the value to the target type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The target type.</param> /// <param name="parameter">The parameter.</param> /// <param name="culture">The culture.</param> /// <returns>The converted type.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || String.IsNullOrEmpty(value.ToString())) { return null; } try { return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute)); } catch { return null; } } /// <summary> /// Converts the value to the target type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The target type.</param> /// <param name="parameter">The parameter.</param> /// <param name="culture">The culture.</param> /// <returns>The converted type.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
//----------------------------------------------------------------------- // <copyright file="UriStringToImageConverter.cs" company="Development In Progress Ltd"> // Copyright © Development In Progress Ltd 2013. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media.Imaging; namespace DevelopmentInProgress.WPFControls.Converters { /// <summary> /// Converts a Uri string to an image. /// </summary> public sealed class UriStringToImageConverter : IValueConverter { /// <summary> /// Converts the value to the target type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The target type.</param> /// <param name="parameter">The parameter.</param> /// <param name="culture">The culture.</param> /// <returns>The converted type.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute)); } catch { return new BitmapImage( new Uri(@"/DevelopmentInProgress.WPFControls;component/Images/Origin.png", UriKind.RelativeOrAbsolute)); } } /// <summary> /// Converts the value to the target type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The target type.</param> /// <param name="parameter">The parameter.</param> /// <param name="culture">The culture.</param> /// <returns>The converted type.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
apache-2.0
C#
dd9cd6fba8330c7c09ff7f618d0e28cbfc222427
fix cli split arguments method
peace2048/h-opc,hylasoft-usa/h-opc,coassoftwaresystems/h-opc,hylasoft-usa/h-opc,peace2048/h-opc,coassoftwaresystems/h-opc
h-opc-cli/CliUtils.cs
h-opc-cli/CliUtils.cs
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Hylasoft.Opc.Cli { internal static class CliUtils { /// <summary> /// Split arguments in a string taking in consideration quotes /// E.g: 'aaa bbb "cc cc"' => ['aaa', 'bbb', 'cc cc'] /// </summary> public static IList<string> SplitArguments(string input) { return Regex.Split(input, @"(?:([^\s""]+)|""([^""]*)"")+") .Where(s => s.Any(c => c != ' ')) .ToList(); } } }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Hylasoft.Opc.Cli { internal static class CliUtils { /// <summary> /// Split arguments in a string taking in consideration quotes /// E.g: 'aaa bbb "cc cc"' => ['aaa', 'bbb', 'cc cc'] /// </summary> public static IList<string> SplitArguments(string input) { return Regex.Split(input, @"(?:([^\s""]+)|""([^""]*)"")+") .Where(s => s.All(c => c == ' ')) .ToList(); } } }
mit
C#
9ce78d80d0455c3201658dfa4486151ffc7c1486
Bump version
beekmanlabs/Storage,beekmanlabs/Storage
BeekmanLabs.Storage/Properties/AssemblyInfo.cs
BeekmanLabs.Storage/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.0.1.*")] [assembly: AssemblyInformationalVersion("0.0.1")] [assembly: AssemblyTitle("BeekmanLabs.Storage")] [assembly: AssemblyCompany("Beekman Labs")] [assembly: AssemblyProduct("BeekmanLabs.Storage")] [assembly: AssemblyCopyright("Copyright © Beekman Labs 2015")] [assembly: ComVisible(false)] [assembly: Guid("f054b802-3240-4884-ae74-d1b7c0f34af8")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyInformationalVersion("0.0.0")] [assembly: AssemblyTitle("BeekmanLabs.Storage")] [assembly: AssemblyCompany("Beekman Labs")] [assembly: AssemblyProduct("BeekmanLabs.Storage")] [assembly: AssemblyCopyright("Copyright © Beekman Labs 2015")] [assembly: ComVisible(false)] [assembly: Guid("f054b802-3240-4884-ae74-d1b7c0f34af8")]
mit
C#
b07828fdd4f9aedeb7f7ab7229e351381d0b569f
Remove EOL whitespace in Kernel32 NativeMethods.
Sharparam/Colore,WolfspiritM/Colore,CoraleStudios/Colore,danpierce1/Colore
Corale.Colore/Native/Kernel32/NativeMethods.cs
Corale.Colore/Native/Kernel32/NativeMethods.cs
// --------------------------------------------------------------------------------------- // <copyright file="NativeMethods.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Native.Kernel32 { using System; using System.Runtime.InteropServices; /// <summary> /// Native methods from <c>kernel32</c> module. /// </summary> internal static class NativeMethods { private const string DllName = "kernel32.dll"; [DllImport(DllName, CharSet = CharSet.Ansi, EntryPoint = "GetProcAddress", ExactSpelling = true, SetLastError = true)] internal static extern IntPtr GetProcAddress(IntPtr module, string procName); [DllImport(DllName, CharSet = CharSet.Ansi, EntryPoint = "LoadLibrary", SetLastError = true)] internal static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string filename); } }
// --------------------------------------------------------------------------------------- // <copyright file="NativeMethods.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any // of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott // do not take responsibility for any harm caused, direct or indirect, to any // Razer peripherals via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore.Native.Kernel32 { using System; using System.Runtime.InteropServices; /// <summary> /// Native methods from <c>kernel32</c> module. /// </summary> internal static class NativeMethods { private const string DllName = "kernel32.dll"; [DllImport(DllName, CharSet = CharSet.Ansi, EntryPoint = "GetProcAddress", ExactSpelling = true, SetLastError = true)] internal static extern IntPtr GetProcAddress(IntPtr module, string procName); [DllImport(DllName, CharSet = CharSet.Ansi, EntryPoint = "LoadLibrary", SetLastError = true)] internal static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string filename); } }
mit
C#
8b7cba25f75ea55924c94d619901026bfcdda673
Add filter property to trending movies request.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Movies/Common/TraktMoviesTrendingRequest.cs
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Movies/Common/TraktMoviesTrendingRequest.cs
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Movies.Common; internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie> { internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/trending{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base.Get; using Objects.Basic; using Objects.Get.Movies.Common; internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie> { internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/trending{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
mit
C#
10e866dc96a9352c9f2481014aa43160a10fbdc1
update video filename
overtools/OWLib,kerzyte/OWLib
DataTool/ToolLogic/Extract/ExtractAbilities.cs
DataTool/ToolLogic/Extract/ExtractAbilities.cs
using System; using System.Collections.Generic; using System.IO; using DataTool.FindLogic; using DataTool.Flag; using OWLib; using STULib.Types; using static DataTool.Helper.IO; using static DataTool.Program; using static DataTool.Helper.STUHelper; namespace DataTool.ToolLogic.Extract { [Tool("extract-abilities", Description = "Extract abilities", TrackTypes = new ushort[] {0x9E}, CustomFlags = typeof(ExtractFlags))] public class ExtractAbilities : ITool { public void IntegrateView(object sender) { throw new NotImplementedException(); } public void Parse(ICLIFlags toolFlags) { SaveAbilities(toolFlags); } public static void SaveAbilities(ICLIFlags toolFlags) { string basePath; if (toolFlags is ExtractFlags flags) { basePath = flags.OutputPath; } else { throw new Exception("no output path"); } foreach (ulong key in TrackedFiles[0x9E]) { STULoadout loadout = GetInstance<STULoadout>(key); if (loadout == null) continue; string name = GetValidFilename(GetString(loadout.Name).TrimEnd().Replace(".", "_")) ?? $"Unknown{GUID.Index(key):X}"; Dictionary<ulong, List<TextureInfo>> textures = new Dictionary<ulong, List<TextureInfo>>(); textures = FindLogic.Texture.FindTextures(textures, loadout.Texture); using (Stream videoStream = OpenFile(loadout.InfoMovie)) { if (videoStream != null) { videoStream.Position = 128; // wrapped in "MOVI" for some reason WriteFile(videoStream, Path.Combine(basePath, name, "InfoMovie.bk2")); } } SaveLogic.Texture.Save(flags, Path.Combine(basePath, name), textures); } } } }
using System; using System.Collections.Generic; using System.IO; using DataTool.FindLogic; using DataTool.Flag; using OWLib; using STULib.Types; using static DataTool.Helper.IO; using static DataTool.Program; using static DataTool.Helper.STUHelper; namespace DataTool.ToolLogic.Extract { [Tool("extract-abilities", Description = "Extract abilities", TrackTypes = new ushort[] {0x9E}, CustomFlags = typeof(ExtractFlags))] public class ExtractAbilities : ITool { public void IntegrateView(object sender) { throw new NotImplementedException(); } public void Parse(ICLIFlags toolFlags) { SaveAbilities(toolFlags); } public static void SaveAbilities(ICLIFlags toolFlags) { string basePath; if (toolFlags is ExtractFlags flags) { basePath = flags.OutputPath; } else { throw new Exception("no output path"); } foreach (ulong key in TrackedFiles[0x9E]) { STULoadout loadout = GetInstance<STULoadout>(key); if (loadout == null) continue; string name = GetValidFilename(GetString(loadout.Name).TrimEnd().Replace(".", "_")) ?? $"Unknown{GUID.Index(key):X}"; Dictionary<ulong, List<TextureInfo>> textures = new Dictionary<ulong, List<TextureInfo>>(); textures = FindLogic.Texture.FindTextures(textures, loadout.Texture); using (Stream videoStream = OpenFile(loadout.InfoMovie)) { if (videoStream != null) { videoStream.Position = 128; // wrapped in "MOVI" for some reason WriteFile(videoStream, Path.Combine(basePath, name, "video.bk2")); } } SaveLogic.Texture.Save(flags, Path.Combine(basePath, name), textures); } } } }
mit
C#
dd4143e8b062c81c59cd79e8d0b3ea40d062b88c
check for null focusedWindow before showing notification
killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MixedRealityToolkit/Utilities/Editor/EditorAssemblyReloadManager.cs
Assets/MixedRealityToolkit/Utilities/Editor/EditorAssemblyReloadManager.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Utilities.Editor { public static class EditorAssemblyReloadManager { private static bool locked = false; /// <summary> /// Locks the Editor's ability to reload assemblies.<para/> /// </summary> /// <remarks> /// This is useful for ensuring async tasks complete in the editor without having to worry if any script /// changes that happen during the running task will cancel it when the editor re-compiles the assemblies. /// </remarks> public static bool LockReloadAssemblies { set { locked = value; if (locked) { EditorApplication.LockReloadAssemblies(); if ((EditorWindow.focusedWindow != null) && !Application.isBatchMode) { EditorWindow.focusedWindow.ShowNotification(new GUIContent("Assembly reloading temporarily paused.")); } } else { EditorApplication.UnlockReloadAssemblies(); EditorApplication.delayCall += () => AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); if ((EditorWindow.focusedWindow != null) && !Application.isBatchMode) { EditorWindow.focusedWindow.ShowNotification(new GUIContent("Assembly reloading resumed.")); } } } get => locked; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Utilities.Editor { public static class EditorAssemblyReloadManager { private static bool locked = false; /// <summary> /// Locks the Editor's ability to reload assemblies.<para/> /// </summary> /// <remarks> /// This is useful for ensuring async tasks complete in the editor without having to worry if any script /// changes that happen during the running task will cancel it when the editor re-compiles the assemblies. /// </remarks> public static bool LockReloadAssemblies { set { locked = value; if (locked) { EditorApplication.LockReloadAssemblies(); if (!Application.isBatchMode) { EditorWindow.focusedWindow.ShowNotification(new GUIContent("Assembly reloading temporarily paused.")); } } else { EditorApplication.UnlockReloadAssemblies(); EditorApplication.delayCall += () => AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); if (!Application.isBatchMode) { EditorWindow.focusedWindow.ShowNotification(new GUIContent("Assembly reloading resumed.")); } } } get => locked; } } }
mit
C#
8b49aa6fede7b93da529b8a93cc758d252c5e436
Make CustomRuntimeFunction blueprint easier to read.
thedevopsmachine/aws-lambda-dotnet,thedevopsmachine/aws-lambda-dotnet,thedevopsmachine/aws-lambda-dotnet,thedevopsmachine/aws-lambda-dotnet
Blueprints/BlueprintDefinitions/Msbuild-NETCore_2_1/CustomRuntimeFunction/template/src/BlueprintBaseName.1/Function.cs
Blueprints/BlueprintDefinitions/Msbuild-NETCore_2_1/CustomRuntimeFunction/template/src/BlueprintBaseName.1/Function.cs
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.Json; using System; using System.Threading.Tasks; namespace BlueprintBaseName._1 { public class Function { /// <summary> /// The main entry point for the custom runtime. /// </summary> /// <param name="args"></param> private static async Task Main(string[] args) { Func<string, ILambdaContext, string> func = FunctionHandler; using(var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer())) using(var bootstrap = new LambdaBootstrap(handlerWrapper)) { await bootstrap.RunAsync(); } } /// <summary> /// A simple function that takes a string and does a ToUpper /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the string input parameter to the desired event type. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public static string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); } } }
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.Json; using System; using System.Threading.Tasks; namespace BlueprintBaseName._1 { public class Function { /// <summary> /// The main entry point for the custom runtime. /// </summary> /// <param name="args"></param> private static async Task Main(string[] args) { using(var handlerWrapper = HandlerWrapper.GetHandlerWrapper((Func<string, ILambdaContext, string>)FunctionHandler, new JsonSerializer())) using(var bootstrap = new LambdaBootstrap(handlerWrapper)) { await bootstrap.RunAsync(); } } /// <summary> /// A simple function that takes a string and does a ToUpper /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the string input parameter to the desired event type. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public static string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); } } }
apache-2.0
C#
d340efb5d6c70c5bf2f79ada34925b5eda52fe6b
Implement conversion on interactor
tomlane/RailDataEngine,tomlane/RailDataEngine
RailDataEngine.Interactor.Implementations/SaveMovementMessageInteractor.cs
RailDataEngine.Interactor.Implementations/SaveMovementMessageInteractor.cs
using System; using RailDataEngine.Domain.Interactor.SaveMovementMessageInteractor; using RailDataEngine.Domain.Services.MovementMessageConversionService; using RailDataEngine.Domain.Services.MovementMessageDeserializationService; namespace RailDataEngine.Interactor.Implementations { public class SaveMovementMessageInteractor : ISaveMovementMessageInteractor { private readonly IMovementMessageDeserializationService _messageDeserializationService; private readonly IMovementMessageConversionService _messageConversionService; public SaveMovementMessageInteractor(IMovementMessageDeserializationService movementMessageDeserializationService, IMovementMessageConversionService movementMessageConversionService) { if (movementMessageDeserializationService == null) throw new ArgumentNullException("movementMessageDeserializationService"); if (movementMessageConversionService == null) throw new ArgumentNullException("movementMessageConversionService"); _messageDeserializationService = movementMessageDeserializationService; _messageConversionService = movementMessageConversionService; } public void SaveMovementMessages(SaveMovementMessageInteractorRequest request) { if (request == null || string.IsNullOrWhiteSpace(request.MessageToSave)) throw new ArgumentNullException("request"); var deserializedMessages = _messageDeserializationService.DeserializeMovementMessages(new MovementMessageDeserializationRequest { MessageToDeserialize = request.MessageToSave }); var convertedMessages = _messageConversionService.ConvertMovementMessages(new MovementMessageConversionRequest { Activations = deserializedMessages.Activations, Cancellations = deserializedMessages.Cancellations, Movements = deserializedMessages.Movements }); } } }
using System; using RailDataEngine.Domain.Interactor.SaveMovementMessageInteractor; using RailDataEngine.Domain.Services.MovementMessageConversionService; using RailDataEngine.Domain.Services.MovementMessageDeserializationService; namespace RailDataEngine.Interactor.Implementations { public class SaveMovementMessageInteractor : ISaveMovementMessageInteractor { public SaveMovementMessageInteractor(IMovementMessageDeserializationService movementMessageDeserializationService, IMovementMessageConversionService movementMessageConversionService) { if (movementMessageDeserializationService == null) throw new ArgumentNullException("movementMessageDeserializationService"); if (movementMessageConversionService == null) throw new ArgumentNullException("movementMessageConversionService"); } public void SaveMovementMessages(SaveMovementMessageInteractorRequest request) { if (request == null || string.IsNullOrWhiteSpace(request.MessageToSave)) throw new ArgumentNullException("request"); throw new System.NotImplementedException(); } } }
mit
C#
9d49947617d9571a0d955db2bb200654e2d97327
Fix log name
NguyenDanPhuong/MangaRipper,GambitKZ/MangaRipper
MangaRipper.Core/MyLogger.cs
MangaRipper.Core/MyLogger.cs
using NLog; using System; namespace MangaRipper.Core { public interface IMyLogger { void Info(string message); void Debug(string message); void Fatal(string message); void Fatal(Exception ex); } public class MyLogger<T> : IMyLogger { private static Logger Logger { get; set; } public MyLogger() { var name = typeof(T).Name; Logger = LogManager.GetLogger(name); } public void Info(string message) { Logger.Info(message); } public void Debug(string message) { Logger.Debug(message); } public void Fatal(string message) { Logger.Fatal(message); } public void Fatal(Exception ex) { Logger.Fatal(ex); } } }
using NLog; using System; namespace MangaRipper.Core { public interface IMyLogger { void Info(string message); void Debug(string message); void Fatal(string message); void Fatal(Exception ex); } public class MyLogger<T> : IMyLogger { private static Logger Logger { get; set; } public MyLogger() { var name = nameof(T); Logger = LogManager.GetLogger(name); } public void Info(string message) { Logger.Info(message); } public void Debug(string message) { Logger.Debug(message); } public void Fatal(string message) { Logger.Fatal(message); } public void Fatal(Exception ex) { Logger.Fatal(ex); } } }
mit
C#
4f97e932629891deb213647016abd195541eb5e8
Add XML documentation to extension method HttpRequestBase.GetOriginalUrl() and make the method public.
schourode/canonicalize
Canonicalize/HttpRequestBaseExtensions.cs
Canonicalize/HttpRequestBaseExtensions.cs
using System; using System.Web; namespace Canonicalize { /// <summary> /// Adds extension methods on <see cref="HttpRequestBase"/>. /// </summary> public static class HttpRequestBaseExtensions { /// <summary> /// Gets the original URL requested by the client, without artifacts from proxies or load balancers. /// In particular HTTP headers Host, X-Forwarded-Host, X-Forwarded-Proto are applied on top of <see cref="HttpRequestBase.Url"/>. /// </summary> /// <param name="request">The request for which the original URL should be computed.</param> /// <returns>The original URL requested by the client.</returns> public static Uri GetOriginalUrl(this HttpRequestBase request) { if (request.Url == null || request.Headers == null) { return request.Url; } var uriBuilder = new UriBuilder(request.Url); var forwardedProtocol = request.Headers["X-Forwarded-Proto"]; if (forwardedProtocol != null) { uriBuilder.Scheme = forwardedProtocol; } var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"]; if (hostHeader != null) { var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader); uriBuilder.Host = parsedHost.Host; uriBuilder.Port = parsedHost.Port; } return uriBuilder.Uri; } } }
using System; using System.Web; namespace Canonicalize { internal static class HttpRequestBaseExtensions { public static Uri GetOriginalUrl(this HttpRequestBase request) { if (request.Url == null || request.Headers == null) { return request.Url; } var uriBuilder = new UriBuilder(request.Url); var forwardedProtocol = request.Headers["X-Forwarded-Proto"]; if (forwardedProtocol != null) { uriBuilder.Scheme = forwardedProtocol; } var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"]; if (hostHeader != null) { var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader); uriBuilder.Host = parsedHost.Host; uriBuilder.Port = parsedHost.Port; } return uriBuilder.Uri; } } }
mit
C#
4e8da0224e3f779d8ea753a09ffdd296aefaba4d
Add routing rules for profile
BCITer/Jabber,BCITer/Jabber,BCITer/Jabber
JabberBCIT/JabberBCIT/App_Start/RouteConfig.cs
JabberBCIT/JabberBCIT/App_Start/RouteConfig.cs
using System.Web.Mvc; using System.Web.Routing; namespace JabberBCIT { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "EditProfile", url: "Profile/Edit/{id}", defaults: new { controller = "Manage", action = "Edit" } ); routes.MapRoute( name: "Profile", url: "Profile/{id}", defaults: new { controller = "Manage", action = "Index"} ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace JabberBCIT { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
mit
C#
72f9da151b1ffe10975816c3c9210e6b2131a3d8
Make Transacript internal
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Wabisabi/RegistrationValidationData.cs
WalletWasabi/Wabisabi/RegistrationValidationData.cs
using System.Collections.Generic; using WalletWasabi.Crypto.ZeroKnowledge; namespace WalletWasabi.Wabisabi { /// <summary> /// Maintains the state needed to validate the credentials once the coordinator /// issues them. /// </summary> public class RegistrationValidationData { internal RegistrationValidationData( Transcript transcript, IEnumerable<Credential> presented, IEnumerable<IssuanceValidationData> requested) { Transcript = transcript; Presented = presented; Requested = requested; } /// <summary> /// The transcript in the correct state that must be used to validate the proofs presented by the coordinator. /// </summary> internal Transcript Transcript { get; } /// <summary> /// The credentials that were presented to the coordinator. /// </summary> public IEnumerable<Credential> Presented { get; } /// <summary> /// The data state that has to be used to validate the issued credentials. /// </summary> public IEnumerable<IssuanceValidationData> Requested { get; } } }
using System.Collections.Generic; using WalletWasabi.Crypto.ZeroKnowledge; namespace WalletWasabi.Wabisabi { /// <summary> /// Maintains the state needed to validate the credentials once the coordinator /// issues them. /// </summary> public class RegistrationValidationData { internal RegistrationValidationData( Transcript transcript, IEnumerable<Credential> presented, IEnumerable<IssuanceValidationData> requested) { Transcript = transcript; Presented = presented; Requested = requested; } /// <summary> /// The transcript in the correct state that must be used to validate the proofs presented by the coordinator. /// </summary> public Transcript Transcript { get; } /// <summary> /// The credentials that were presented to the coordinator. /// </summary> public IEnumerable<Credential> Presented { get; } /// <summary> /// The data state that has to be used to validate the issued credentials. /// </summary> public IEnumerable<IssuanceValidationData> Requested { get; } } }
mit
C#
f53ea8a90f49176b7a1779a45b4f75a078e61f05
Mark ProjectionVersionsHandler as a system projection with ISystemProjection. Apparently we need it
Elders/Cronus,Elders/Cronus
src/Elders.Cronus/Projections/Versioning/Handlers/ProjectionVersionsHandler.cs
src/Elders.Cronus/Projections/Versioning/Handlers/ProjectionVersionsHandler.cs
using System.Runtime.Serialization; using Elders.Cronus.Projections.Snapshotting; namespace Elders.Cronus.Projections.Versioning { [DataContract(Name = "ad755d78-4ecb-4930-837e-160effbfee14")] public class ProjectionVersionsHandler : ProjectionDefinition<ProjectionVersionsHandlerState, ProjectionVersionManagerId>, IAmNotSnapshotable, ISystemProjection, IEventHandler<ProjectionVersionRequested>, IEventHandler<NewProjectionVersionIsNowLive>, IEventHandler<ProjectionVersionRequestCanceled>, IEventHandler<ProjectionVersionRequestTimedout> { public ProjectionVersionsHandler() { Subscribe<ProjectionVersionRequested>(x => x.Id); Subscribe<NewProjectionVersionIsNowLive>(x => x.Id); Subscribe<ProjectionVersionRequestCanceled>(x => x.Id); Subscribe<ProjectionVersionRequestTimedout>(x => x.Id); } public void Handle(ProjectionVersionRequested @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(NewProjectionVersionIsNowLive @event) { State.Id = @event.Id; State.AllVersions.Add(@event.ProjectionVersion); } public void Handle(ProjectionVersionRequestCanceled @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(ProjectionVersionRequestTimedout @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } } public class ProjectionVersionsHandlerState { public ProjectionVersionsHandlerState() { AllVersions = new ProjectionVersions(); } public ProjectionVersionManagerId Id { get; set; } public ProjectionVersion Live { get { return AllVersions.GetLive(); } } public ProjectionVersions AllVersions { get; set; } } }
using System.Runtime.Serialization; using Elders.Cronus.Projections.Snapshotting; namespace Elders.Cronus.Projections.Versioning { [DataContract(Name = "ad755d78-4ecb-4930-837e-160effbfee14")] public class ProjectionVersionsHandler : ProjectionDefinition<ProjectionVersionsHandlerState, ProjectionVersionManagerId>, IAmNotSnapshotable, IEventHandler<ProjectionVersionRequested>, IEventHandler<NewProjectionVersionIsNowLive>, IEventHandler<ProjectionVersionRequestCanceled>, IEventHandler<ProjectionVersionRequestTimedout> { public ProjectionVersionsHandler() { Subscribe<ProjectionVersionRequested>(x => x.Id); Subscribe<NewProjectionVersionIsNowLive>(x => x.Id); Subscribe<ProjectionVersionRequestCanceled>(x => x.Id); Subscribe<ProjectionVersionRequestTimedout>(x => x.Id); } public void Handle(ProjectionVersionRequested @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(NewProjectionVersionIsNowLive @event) { State.Id = @event.Id; State.AllVersions.Add(@event.ProjectionVersion); } public void Handle(ProjectionVersionRequestCanceled @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } public void Handle(ProjectionVersionRequestTimedout @event) { State.Id = @event.Id; State.AllVersions.Add(@event.Version); } } public class ProjectionVersionsHandlerState { public ProjectionVersionsHandlerState() { AllVersions = new ProjectionVersions(); } public ProjectionVersionManagerId Id { get; set; } public ProjectionVersion Live { get { return AllVersions.GetLive(); } } public ProjectionVersions AllVersions { get; set; } } }
apache-2.0
C#
2fac527bd64538a56a1bf5cbd472d4b58342a6b2
Update DecimalDataValidation.cs
asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Data/Processing/FilteringAndValidation/DecimalDataValidation.cs
Examples/CSharp/Data/Processing/FilteringAndValidation/DecimalDataValidation.cs
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Data.Processing.Processing.FilteringAndValidation { public class DecimalDataValidation { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); // Create a workbook object. Workbook workbook = new Workbook(); // Create a worksheet and get the first worksheet. Worksheet ExcelWorkSheet = workbook.Worksheets[0]; // Obtain the existing Validations collection. ValidationCollection validations = ExcelWorkSheet.Validations; // Create a validation object adding to the collection list. Validation validation = validations[validations.Add()]; // Set the validation type. validation.Type = ValidationType.Decimal; // Specify the operator. validation.Operator = OperatorType.Between; // Set the lower and upper limits. validation.Formula1 = Decimal.MinValue.ToString(); validation.Formula2 = Decimal.MaxValue.ToString(); // Set the error message. validation.ErrorMessage = "Please enter a valid integer or decimal number"; // Specify the validation area of cells. CellArea area; area.StartRow = 0; area.EndRow = 9; area.StartColumn = 0; area.EndColumn = 0; // Add the area. validation.AreaList.Add(area); // Save the workbook. workbook.Save(dataDir + "output.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Data.Processing.Processing.FilteringAndValidation { public class DecimalDataValidation { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); // Create a workbook object. Workbook workbook = new Workbook(); // Create a worksheet and get the first worksheet. Worksheet ExcelWorkSheet = workbook.Worksheets[0]; // Obtain the existing Validations collection. ValidationCollection validations = ExcelWorkSheet.Validations; // Create a validation object adding to the collection list. Validation validation = validations[validations.Add()]; // Set the validation type. validation.Type = ValidationType.Decimal; // Specify the operator. validation.Operator = OperatorType.Between; // Set the lower and upper limits. validation.Formula1 = Decimal.MinValue.ToString(); validation.Formula2 = Decimal.MaxValue.ToString(); // Set the error message. validation.ErrorMessage = "Please enter a valid integer or decimal number"; // Specify the validation area of cells. CellArea area; area.StartRow = 0; area.EndRow = 9; area.StartColumn = 0; area.EndColumn = 0; // Add the area. validation.AreaList.Add(area); // Save the workbook. workbook.Save(dataDir + "output.out.xls"); } } }
mit
C#
cabd01b78c7130cc69fbfd97016a501fe2a59e37
Add provider name and provider type into LocationInfo, part 2
ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp
source/Htc.Vita.Core/Diagnostics/LocationManager.DataType.cs
source/Htc.Vita.Core/Diagnostics/LocationManager.DataType.cs
namespace Htc.Vita.Core.Diagnostics { public partial class LocationManager { /// <summary> /// Class LocationInfo. /// </summary> public class LocationInfo { /// <summary> /// Gets or sets the country code alpha2. /// </summary> /// <value>The country code alpha2.</value> public string CountryCodeAlpha2 { get; set; } /// <summary> /// Gets or sets the provider name. /// </summary> /// <value>The provider name.</value> public string ProviderName { get; set; } /// <summary> /// Gets or sets the provider type. /// </summary> /// <value>The provider type.</value> public LocationProviderType ProviderType { get; set; } = LocationProviderType.Unknown; } /// <summary> /// Enum LocationProviderType /// </summary> public enum LocationProviderType { /// <summary> /// Unknown /// </summary> Unknown, /// <summary> /// Provided by operating system /// </summary> OperatingSystem, /// <summary> /// Provided by network /// </summary> Network, /// <summary> /// Provided by user /// </summary> User, /// <summary> /// The external application /// </summary> ExternalApplication } } }
namespace Htc.Vita.Core.Diagnostics { public partial class LocationManager { /// <summary> /// Class LocationInfo. /// </summary> public class LocationInfo { /// <summary> /// Gets or sets the country code alpha2. /// </summary> /// <value>The country code alpha2.</value> public string CountryCodeAlpha2 { get; set; } /// <summary> /// Gets or sets the provider name. /// </summary> /// <value>The provider name.</value> public string ProviderName { get; set; } /// <summary> /// Gets or sets the provider type. /// </summary> /// <value>The provider type.</value> public LocationProviderType ProviderType { get; set; } = LocationProviderType.Unknown; } /// <summary> /// Enum LocationProviderType /// </summary> public enum LocationProviderType { /// <summary> /// Unknown /// </summary> Unknown, /// <summary> /// Provided by operating system /// </summary> OperatingSystem, /// <summary> /// Provided by network /// </summary> Network, /// <summary> /// Provided by user /// </summary> User } } }
mit
C#
15560b2852e373f2c1b1b71e456bc8957f42a34a
Clean comments in DistanseMatrixResponseModel
senioroman4uk/PathFinder
PathFinder.Trips.WebApi/Models/DistanseMatrixResponseModel.cs
PathFinder.Trips.WebApi/Models/DistanseMatrixResponseModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PathFinder.Trips.WebApi.Models { public class DistanseMatrixResponseModel { public List<Row> Rows { get; set; } public string Status { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PathFinder.Trips.WebApi.Models { public class DistanseMatrixResponseModel { // public List<string> destination_addresses { get; set; } // public List<string> origin_addresses { get; set; } public List<Row> Rows { get; set; } public string Status { get; set; } } }
mit
C#
5179635b2dc855a1873e94da8512476c3bebf255
add shorthand method for config retrieval
NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,smoogipooo/osu,ppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu
osu.Game.Rulesets.Mania/Skinning/LegacyManiaColumnElement.cs
osu.Game.Rulesets.Mania/Skinning/LegacyManiaColumnElement.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.UI; using osu.Game.Skinning; namespace osu.Game.Rulesets.Mania.Skinning { /// <summary> /// A <see cref="CompositeDrawable"/> which is placed somewhere within a <see cref="Column"/>. /// </summary> public class LegacyManiaColumnElement : CompositeDrawable { [Resolved(CanBeNull = true)] [CanBeNull] protected ManiaStage Stage { get; private set; } [Resolved] protected Column Column { get; private set; } /// <summary> /// The column index to use for texture lookups, in the case of no user-provided configuration. /// </summary> protected int FallbackColumnIndex { get; private set; } [BackgroundDependencyLoader] private void load() { if (Stage == null) FallbackColumnIndex = Column.Index % 2 + 1; else { int dist = Math.Min(Column.Index, Stage.Columns.Count - Column.Index - 1); FallbackColumnIndex = dist % 2 + 1; } } protected IBindable<T> GetManiaSkinConfig<T>(ISkinSource skin, LegacyManiaSkinConfigurationLookups lookup) => skin.GetConfig<LegacyManiaSkinConfigurationLookup, T>( new LegacyManiaSkinConfigurationLookup(Stage?.Columns.Count ?? 4, lookup, Column.Index)); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Skinning { /// <summary> /// A <see cref="CompositeDrawable"/> which is placed somewhere within a <see cref="Column"/>. /// </summary> public class LegacyManiaColumnElement : CompositeDrawable { [Resolved(CanBeNull = true)] [CanBeNull] protected ManiaStage Stage { get; private set; } [Resolved] protected Column Column { get; private set; } /// <summary> /// The column index to use for texture lookups, in the case of no user-provided configuration. /// </summary> protected int FallbackColumnIndex { get; private set; } [BackgroundDependencyLoader] private void load() { if (Stage == null) FallbackColumnIndex = Column.Index % 2 + 1; else { int dist = Math.Min(Column.Index, Stage.Columns.Count - Column.Index - 1); FallbackColumnIndex = dist % 2 + 1; } } } }
mit
C#
df4604fbc733ee8fbb0860f40705bae681d67a6f
Update version number to 2014.1
fringebits/QuantityTypes,donid/QuantityTypes,objorke/QuantityTypes,joseph-bs/QuantityTypes,BadBabyJames/QunityTypes
Source/GlobalAssemblyInfo.cs
Source/GlobalAssemblyInfo.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Units for .NET"> // Copyright © Units for .NET. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Units for .NET")] [assembly: AssemblyCopyright("Copyright © Units for .NET 2012-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2014.1.1.*")] [assembly: AssemblyFileVersion("2014.1.1.0")]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Units for .NET"> // Copyright © Units for .NET. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Units for .NET")] [assembly: AssemblyCopyright("Copyright © Units for .NET 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2013.1.1.*")] [assembly: AssemblyFileVersion("2013.1.1.0")]
mit
C#
ed2dc101bb56debd0d4effc65fb1abbd3cc2f078
Fix MessageBox behaviour
lances101/Wox,Wox-launcher/Wox,lances101/Wox,qianlifeng/Wox,qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox
Wox.Plugin.SystemPlugins/WebSearch/WebSearchesSetting.xaml.cs
Wox.Plugin.SystemPlugins/WebSearch/WebSearchesSetting.xaml.cs
using System.Windows; using System.Windows.Controls; using Wox.Infrastructure.Storage.UserSettings; namespace Wox.Plugin.SystemPlugins { /// <summary> /// Interaction logic for WebSearchesSetting.xaml /// </summary> public partial class WebSearchesSetting : UserControl { public WebSearchesSetting() { InitializeComponent(); Loaded += Setting_Loaded; } private void Setting_Loaded(object sender, RoutedEventArgs e) { webSearchView.ItemsSource = UserSettingStorage.Instance.WebSearches; } public void ReloadWebSearchView() { webSearchView.Items.Refresh(); } private void btnAddWebSearch_OnClick(object sender, RoutedEventArgs e) { WebSearchSetting webSearch = new WebSearchSetting(this); webSearch.ShowDialog(); } private void btnDeleteWebSearch_OnClick(object sender, RoutedEventArgs e) { WebSearch seletedWebSearch = webSearchView.SelectedItem as WebSearch; if (seletedWebSearch != null) { if (MessageBox.Show("Are your sure to delete " + seletedWebSearch.Title, "Delete WebSearch", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { UserSettingStorage.Instance.WebSearches.Remove(seletedWebSearch); webSearchView.Items.Refresh(); } } else { MessageBox.Show("Please select a web search"); } } private void btnEditWebSearch_OnClick(object sender, RoutedEventArgs e) { WebSearch seletedWebSearch = webSearchView.SelectedItem as WebSearch; if (seletedWebSearch != null) { WebSearchSetting webSearch = new WebSearchSetting(this); webSearch.UpdateItem(seletedWebSearch); webSearch.ShowDialog(); } else { MessageBox.Show("Please select a web search"); } } } }
using System.Windows; using System.Windows.Controls; using Wox.Infrastructure.Storage.UserSettings; namespace Wox.Plugin.SystemPlugins { /// <summary> /// Interaction logic for WebSearchesSetting.xaml /// </summary> public partial class WebSearchesSetting : UserControl { public WebSearchesSetting() { InitializeComponent(); Loaded += Setting_Loaded; } private void Setting_Loaded(object sender, RoutedEventArgs e) { webSearchView.ItemsSource = UserSettingStorage.Instance.WebSearches; } public void ReloadWebSearchView() { webSearchView.Items.Refresh(); } private void btnAddWebSearch_OnClick(object sender, RoutedEventArgs e) { WebSearchSetting webSearch = new WebSearchSetting(this); webSearch.ShowDialog(); } private void btnDeleteWebSearch_OnClick(object sender, RoutedEventArgs e) { WebSearch seletedWebSearch = webSearchView.SelectedItem as WebSearch; if (seletedWebSearch != null && MessageBox.Show("Are your sure to delete " + seletedWebSearch.Title, "Delete WebSearch", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { UserSettingStorage.Instance.WebSearches.Remove(seletedWebSearch); webSearchView.Items.Refresh(); } else { MessageBox.Show("Please select a web search"); } } private void btnEditWebSearch_OnClick(object sender, RoutedEventArgs e) { WebSearch seletedWebSearch = webSearchView.SelectedItem as WebSearch; if (seletedWebSearch != null) { WebSearchSetting webSearch = new WebSearchSetting(this); webSearch.UpdateItem(seletedWebSearch); webSearch.ShowDialog(); } else { MessageBox.Show("Please select a web search"); } } } }
mit
C#
876d9063612e04d38b4367f47f388aae45ebf055
Fix part of #8 (not properly escaping the pound character)
AvetisG/TubeToTune,kirbyfan64/TubeToTune,AvetisG/TubeToTune,kirbyfan64/TubeToTune,AvetisG/TubeToTune
TubeToTune/Helpers/FileNameGenerationHelper.cs
TubeToTune/Helpers/FileNameGenerationHelper.cs
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace TubeToTune.Helpers { public class FileNameGenerationHelper { public static string RemoveIllegalPathCharacters(string path) { string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + "#"; var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch))); return r.Replace(path, "").Replace("&", "and"); } public static string GenerateFilename() { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); var result = new string( Enumerable.Repeat(chars, 13) .Select(s => s[random.Next(s.Length)]) .ToArray()); return result + ".zip"; } } }
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace TubeToTune.Helpers { public class FileNameGenerationHelper { public static string RemoveIllegalPathCharacters(string path) { string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch))); return r.Replace(path, "").Replace("&", "and"); } public static string GenerateFilename() { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); var result = new string( Enumerable.Repeat(chars, 13) .Select(s => s[random.Next(s.Length)]) .ToArray()); return result + ".zip"; } } }
mit
C#
805045a6eb6bad07bf52e4c5d582df2652ef156e
bump v2.3.1.40
Gizeta/KanColleCacher
KanColleCacher/Properties/AssemblyInfo.cs
KanColleCacher/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using d_f_32.KanColleCacher; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle(AssemblyInfo.Title)] [assembly: AssemblyDescription(AssemblyInfo.Description)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(AssemblyInfo.Name)] [assembly: AssemblyCopyright(AssemblyInfo.Copyright)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID //[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")] [assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion(AssemblyInfo.Version)] [assembly: AssemblyFileVersion(AssemblyInfo.Version)] namespace d_f_32.KanColleCacher { public static class AssemblyInfo { public const string Name = "KanColleCacher"; public const string Version = "2.3.1.40"; public const string Author = "d.f.32"; public const string Copyright = "©2014 - d.f.32"; #if DEBUG public const string Title = "提督很忙!缓存工具 (DEBUG)"; #else public const string Title = "提督很忙!缓存工具"; #endif public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)"; } }
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using d_f_32.KanColleCacher; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle(AssemblyInfo.Title)] [assembly: AssemblyDescription(AssemblyInfo.Description)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(AssemblyInfo.Name)] [assembly: AssemblyCopyright(AssemblyInfo.Copyright)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID //[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")] [assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion(AssemblyInfo.Version)] [assembly: AssemblyFileVersion(AssemblyInfo.Version)] namespace d_f_32.KanColleCacher { public static class AssemblyInfo { public const string Name = "KanColleCacher"; public const string Version = "2.3.0.38"; public const string Author = "d.f.32"; public const string Copyright = "©2014 - d.f.32"; #if DEBUG public const string Title = "提督很忙!缓存工具 (DEBUG)"; #else public const string Title = "提督很忙!缓存工具"; #endif public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)"; } }
mit
C#
d8c850633399923cd0ca0ed38ea4d0e72db78672
add task attributes
exercism/xcsharp,exercism/xcsharp
exercises/concept/lucians-luscious-lasagna/LuciansLusciousLasagnaTests.cs
exercises/concept/lucians-luscious-lasagna/LuciansLusciousLasagnaTests.cs
using Xunit; using Exercism.Tests; public class LasagnaTests { [Fact] [Task(1)] public void Expected_minutes_in_oven() { Assert.Equal(40, new Lasagna().ExpectedMinutesInOven()); } [Fact(Skip = "Remove this Skip property to run this test")] [Task(2)] public void Remaining_minutes_in_oven() { Assert.Equal(15, new Lasagna().RemainingMinutesInOven(25)); } [Fact(Skip = "Remove this Skip property to run this test")] [Task(3)] public void Preparation_time_in_minutes_for_one_layer() { Assert.Equal(2, new Lasagna().PreparationTimeInMinutes(1)); } [Fact(Skip = "Remove this Skip property to run this test")] [Task(3)] public void Preparation_time_in_minutes_for_multiple_layers() { Assert.Equal(8, new Lasagna().PreparationTimeInMinutes(4)); } [Fact(Skip = "Remove this Skip property to run this test")] [Task(4)] public void Elapsed_time_in_minutes_for_one_layer() { Assert.Equal(32, new Lasagna().ElapsedTimeInMinutes(1, 30)); } [Fact(Skip = "Remove this Skip property to run this test")] [Task(4)] public void Elapsed_time_in_minutes_for_multiple_layers() { Assert.Equal(16, new Lasagna().ElapsedTimeInMinutes(4, 8)); } }
using Xunit; using Exercism.Tests; public class LasagnaTests { [Fact] public void Expected_minutes_in_oven() { Assert.Equal(40, new Lasagna().ExpectedMinutesInOven()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Remaining_minutes_in_oven() { Assert.Equal(15, new Lasagna().RemainingMinutesInOven(25)); } [Fact(Skip = "Remove this Skip property to run this test")] public void Preparation_time_in_minutes_for_one_layer() { Assert.Equal(2, new Lasagna().PreparationTimeInMinutes(1)); } [Fact(Skip = "Remove this Skip property to run this test")] public void Preparation_time_in_minutes_for_multiple_layers() { Assert.Equal(8, new Lasagna().PreparationTimeInMinutes(4)); } [Fact(Skip = "Remove this Skip property to run this test")] public void Elapsed_time_in_minutes_for_one_layer() { Assert.Equal(32, new Lasagna().ElapsedTimeInMinutes(1, 30)); } [Fact(Skip = "Remove this Skip property to run this test")] public void Elapsed_time_in_minutes_for_multiple_layers() { Assert.Equal(16, new Lasagna().ElapsedTimeInMinutes(4, 8)); } }
mit
C#
27b48140b5edfc44afb1f74f5cfe022ab4bac631
Use DateTimeOffset.FromUnixTimeSeconds on netstandard2.0
khellang/Nzb
src/Nzb/EpochUtility.cs
src/Nzb/EpochUtility.cs
using System; namespace Nzb { internal static class EpochUtility { #if NETSTANDARD1_0 private static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero); #endif public static DateTimeOffset ToUnixEpoch(this long timestamp) { #if NETSTANDARD1_0 return UnixEpoch.AddSeconds(timestamp).ToLocalTime(); #else return DateTimeOffset.FromUnixTimeSeconds(timestamp); #endif } } }
using System; namespace Nzb { internal static class EpochUtility { private static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero); public static DateTimeOffset ToUnixEpoch(this long timestamp) => UnixEpoch.AddSeconds(timestamp).ToLocalTime(); } }
mit
C#
7b9cdb306c0ecc4127267fcf541839b81de21b98
Rename test PageGenerator_GenerateContentPage_Should.SetTheContentTitleAsTitleOfThePage to PageGenerator_GenerateContentPage_Should.ReplaceATitlePlaceholderWithTheTitle.
bsstahl/PPTail,bsstahl/PPTail
PrehensilePonyTail/PPTail.Generator.T4Html.Test/PageGenerator_GenerateContentPage_Should.cs
PrehensilePonyTail/PPTail.Generator.T4Html.Test/PageGenerator_GenerateContentPage_Should.cs
using PPTail.Entities; using PPTail.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace PPTail.Generator.T4Html.Test { public class PageGenerator_GenerateContentPage_Should { [Fact] public void ReplaceATitlePlaceholderWithTheTitle() { var pageData = (null as ContentItem).Create(); string template = "*******************************{Title}*******************************"; var target = (null as IPageGenerator).Create(template, string.Empty); var actual = target.GenerateContentPage(pageData); Console.WriteLine(actual); Assert.Contains(pageData.Title, actual); } } }
using PPTail.Entities; using PPTail.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace PPTail.Generator.T4Html.Test { public class PageGenerator_GenerateContentPage_Should { [Fact] public void SetTheContentTitleAsTitleOfThePage() { var pageData = (null as ContentItem).Create(); string template = "*******************************{Title}*******************************"; var target = (null as IPageGenerator).Create(template, string.Empty); var actual = target.GenerateContentPage(pageData); Console.WriteLine(actual); Assert.Contains(pageData.Title, actual); } } }
mit
C#
7238112b317a1ccee3cd60bc1ccfdc3e414f5e41
Remove now-unused auth url endpoints
magoswiat/octokit.net,Sarmad93/octokit.net,shiftkey/octokit.net,gdziadkiewicz/octokit.net,geek0r/octokit.net,rlugojr/octokit.net,shiftkey-tester/octokit.net,adamralph/octokit.net,Sarmad93/octokit.net,octokit-net-test-org/octokit.net,shiftkey/octokit.net,TattsGroup/octokit.net,gabrielweyer/octokit.net,khellang/octokit.net,editor-tools/octokit.net,fake-organization/octokit.net,devkhan/octokit.net,khellang/octokit.net,SamTheDev/octokit.net,daukantas/octokit.net,hahmed/octokit.net,octokit-net-test-org/octokit.net,TattsGroup/octokit.net,eriawan/octokit.net,alfhenrik/octokit.net,naveensrinivasan/octokit.net,brramos/octokit.net,shana/octokit.net,dampir/octokit.net,hitesh97/octokit.net,takumikub/octokit.net,M-Zuber/octokit.net,thedillonb/octokit.net,octokit/octokit.net,devkhan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,octokit/octokit.net,editor-tools/octokit.net,shiftkey-tester/octokit.net,mminns/octokit.net,ivandrofly/octokit.net,chunkychode/octokit.net,SmithAndr/octokit.net,thedillonb/octokit.net,shana/octokit.net,gabrielweyer/octokit.net,M-Zuber/octokit.net,dampir/octokit.net,rlugojr/octokit.net,ivandrofly/octokit.net,mminns/octokit.net,chunkychode/octokit.net,cH40z-Lord/octokit.net,hahmed/octokit.net,alfhenrik/octokit.net,gdziadkiewicz/octokit.net,nsnnnnrn/octokit.net,bslliw/octokit.net,nsrnnnnn/octokit.net,eriawan/octokit.net,SmithAndr/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,SamTheDev/octokit.net
Octokit/Helpers/ApiUrls.Authorizations.cs
Octokit/Helpers/ApiUrls.Authorizations.cs
using System; namespace Octokit { public static partial class ApiUrls { static readonly Uri _currentUserAuthorizationsEndpoint = new Uri("authorizations", UriKind.Relative); /// <summary> /// Returns the <see cref="Uri"/> that returns all of the authorizations for the currently logged in user. /// </summary> public static Uri Authorizations() { return _currentUserAuthorizationsEndpoint; } /// <summary> /// Returns the <see cref="Uri"/> that returns all authorizations for a given user /// </summary> /// <param name="id">The user Id to search for</param> public static Uri Authorizations(int id) { return "authorizations/{0}".FormatUri(id); } /// <summary> /// Returns the <see cref="Uri"/> that returns all authorizations for a given client /// </summary> /// <param name="clientId"> /// The 20 character OAuth app client key for which to create the token. /// </param> public static Uri AuthorizationsForClient(string clientId) { return "authorizations/clients/{0}".FormatUri(clientId); } public static Uri ApplicationAuthorization(string clientId) { return "applications/{0}/tokens".FormatUri(clientId); } public static Uri ApplicationAuthorization(string clientId, string accessToken) { return "applications/{0}/tokens/{1}".FormatUri(clientId, accessToken); } } }
using System; namespace Octokit { public static partial class ApiUrls { static readonly Uri _currentUserAuthorizationsEndpoint = new Uri("authorizations", UriKind.Relative); /// <summary> /// Returns the <see cref="Uri"/> that returns all of the authorizations for the currently logged in user. /// </summary> public static Uri Authorizations() { return _currentUserAuthorizationsEndpoint; } /// <summary> /// Returns the <see cref="Uri"/> that returns all authorizations for a given user /// </summary> /// <param name="id">The user Id to search for</param> public static Uri Authorizations(int id) { return "authorizations/{0}".FormatUri(id); } /// <summary> /// Returns the <see cref="Uri"/> that returns all authorizations for a given client /// </summary> /// <param name="clientId"> /// The 20 character OAuth app client key for which to create the token. /// </param> public static Uri AuthorizationsForClient(string clientId) { return "authorizations/clients/{0}".FormatUri(clientId); } /// <summary> /// Returns the <see cref="Uri"/> that authorizations for a given client and fingerprint /// </summary> /// <param name="clientId"> /// The 20 character OAuth app client key for /// which to create the token.</param> /// <param name="fingerprint"> /// A unique string to distinguish an authorization from others created /// for the same client and user. /// </param> public static Uri AuthorizationsForClient(string clientId, string fingerprint) { return "authorizations/clients/{0}/{1}".FormatUri(clientId, fingerprint); } public static Uri ApplicationAuthorization(string clientId) { return "applications/{0}/tokens".FormatUri(clientId); } public static Uri ApplicationAuthorization(string clientId, string accessToken) { return "applications/{0}/tokens/{1}".FormatUri(clientId, accessToken); } } }
mit
C#
dbeb57dcea4d26bb695a4e57d3fcb69377e2311e
Add tests for sameness in DateTimeFormatInfo
dhoehna/corefx,Priya91/corefx-1,rjxby/corefx,manu-silicon/corefx,kkurni/corefx,gkhanna79/corefx,nbarbettini/corefx,shmao/corefx,SGuyGe/corefx,seanshpark/corefx,dotnet-bot/corefx,zhenlan/corefx,tijoytom/corefx,dhoehna/corefx,mmitche/corefx,alexperovich/corefx,axelheer/corefx,kkurni/corefx,YoupHulsebos/corefx,ellismg/corefx,mmitche/corefx,tijoytom/corefx,SGuyGe/corefx,shmao/corefx,richlander/corefx,Jiayili1/corefx,weltkante/corefx,ptoonen/corefx,weltkante/corefx,axelheer/corefx,ellismg/corefx,fgreinacher/corefx,ravimeda/corefx,parjong/corefx,mmitche/corefx,twsouthwick/corefx,dhoehna/corefx,jlin177/corefx,shimingsg/corefx,nbarbettini/corefx,shahid-pk/corefx,elijah6/corefx,richlander/corefx,marksmeltzer/corefx,fgreinacher/corefx,JosephTremoulet/corefx,seanshpark/corefx,ptoonen/corefx,zhenlan/corefx,alphonsekurian/corefx,gkhanna79/corefx,cydhaselton/corefx,tijoytom/corefx,billwert/corefx,nbarbettini/corefx,shmao/corefx,pallavit/corefx,YoupHulsebos/corefx,weltkante/corefx,ravimeda/corefx,manu-silicon/corefx,Priya91/corefx-1,YoupHulsebos/corefx,rahku/corefx,jhendrixMSFT/corefx,DnlHarvey/corefx,nbarbettini/corefx,fgreinacher/corefx,lggomez/corefx,stone-li/corefx,jlin177/corefx,iamjasonp/corefx,krk/corefx,krytarowski/corefx,jhendrixMSFT/corefx,richlander/corefx,ViktorHofer/corefx,jlin177/corefx,SGuyGe/corefx,yizhang82/corefx,cartermp/corefx,elijah6/corefx,cydhaselton/corefx,stephenmichaelf/corefx,Priya91/corefx-1,marksmeltzer/corefx,ericstj/corefx,dhoehna/corefx,dotnet-bot/corefx,manu-silicon/corefx,alexperovich/corefx,dotnet-bot/corefx,ericstj/corefx,rahku/corefx,BrennanConroy/corefx,BrennanConroy/corefx,BrennanConroy/corefx,iamjasonp/corefx,alphonsekurian/corefx,alphonsekurian/corefx,rjxby/corefx,adamralph/corefx,khdang/corefx,ViktorHofer/corefx,lggomez/corefx,dhoehna/corefx,manu-silicon/corefx,JosephTremoulet/corefx,lggomez/corefx,adamralph/corefx,YoupHulsebos/corefx,jhendrixMSFT/corefx,zhenlan/corefx,Chrisboh/corefx,yizhang82/corefx,tstringer/corefx,Ermiar/corefx,gkhanna79/corefx,rahku/corefx,ellismg/corefx,cydhaselton/corefx,pallavit/corefx,alexperovich/corefx,Jiayili1/corefx,khdang/corefx,rjxby/corefx,stephenmichaelf/corefx,twsouthwick/corefx,zhenlan/corefx,pallavit/corefx,jhendrixMSFT/corefx,alphonsekurian/corefx,ptoonen/corefx,dotnet-bot/corefx,jcme/corefx,rahku/corefx,krk/corefx,nchikanov/corefx,jcme/corefx,mazong1123/corefx,YoupHulsebos/corefx,stephenmichaelf/corefx,ptoonen/corefx,parjong/corefx,the-dwyer/corefx,cydhaselton/corefx,weltkante/corefx,twsouthwick/corefx,yizhang82/corefx,Ermiar/corefx,elijah6/corefx,alphonsekurian/corefx,tijoytom/corefx,iamjasonp/corefx,cydhaselton/corefx,kkurni/corefx,krytarowski/corefx,rahku/corefx,ViktorHofer/corefx,wtgodbe/corefx,iamjasonp/corefx,wtgodbe/corefx,stephenmichaelf/corefx,SGuyGe/corefx,tijoytom/corefx,nbarbettini/corefx,krk/corefx,ellismg/corefx,alexperovich/corefx,MaggieTsang/corefx,shahid-pk/corefx,seanshpark/corefx,dsplaisted/corefx,marksmeltzer/corefx,stone-li/corefx,kkurni/corefx,twsouthwick/corefx,alexperovich/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,krk/corefx,krytarowski/corefx,parjong/corefx,Ermiar/corefx,mmitche/corefx,marksmeltzer/corefx,stone-li/corefx,elijah6/corefx,shahid-pk/corefx,mmitche/corefx,rjxby/corefx,ravimeda/corefx,jlin177/corefx,shimingsg/corefx,cartermp/corefx,the-dwyer/corefx,shahid-pk/corefx,Priya91/corefx-1,richlander/corefx,pallavit/corefx,the-dwyer/corefx,manu-silicon/corefx,jlin177/corefx,alphonsekurian/corefx,stone-li/corefx,Petermarcu/corefx,shimingsg/corefx,billwert/corefx,shahid-pk/corefx,gkhanna79/corefx,tstringer/corefx,ptoonen/corefx,Chrisboh/corefx,krk/corefx,adamralph/corefx,cartermp/corefx,rubo/corefx,weltkante/corefx,lggomez/corefx,JosephTremoulet/corefx,elijah6/corefx,rjxby/corefx,tstringer/corefx,richlander/corefx,billwert/corefx,richlander/corefx,rahku/corefx,ViktorHofer/corefx,DnlHarvey/corefx,dotnet-bot/corefx,ViktorHofer/corefx,cartermp/corefx,billwert/corefx,ptoonen/corefx,tstringer/corefx,cartermp/corefx,DnlHarvey/corefx,ravimeda/corefx,stephenmichaelf/corefx,Chrisboh/corefx,tstringer/corefx,mazong1123/corefx,ViktorHofer/corefx,krk/corefx,Petermarcu/corefx,Priya91/corefx-1,krytarowski/corefx,axelheer/corefx,MaggieTsang/corefx,nchikanov/corefx,parjong/corefx,elijah6/corefx,shmao/corefx,jcme/corefx,marksmeltzer/corefx,seanshpark/corefx,billwert/corefx,iamjasonp/corefx,lggomez/corefx,krk/corefx,MaggieTsang/corefx,iamjasonp/corefx,stone-li/corefx,ericstj/corefx,rubo/corefx,shmao/corefx,elijah6/corefx,nchikanov/corefx,yizhang82/corefx,yizhang82/corefx,MaggieTsang/corefx,zhenlan/corefx,billwert/corefx,alphonsekurian/corefx,SGuyGe/corefx,Petermarcu/corefx,lggomez/corefx,JosephTremoulet/corefx,dhoehna/corefx,wtgodbe/corefx,cydhaselton/corefx,ravimeda/corefx,kkurni/corefx,nbarbettini/corefx,marksmeltzer/corefx,Jiayili1/corefx,krytarowski/corefx,weltkante/corefx,the-dwyer/corefx,Petermarcu/corefx,parjong/corefx,tstringer/corefx,ravimeda/corefx,ViktorHofer/corefx,jhendrixMSFT/corefx,tijoytom/corefx,mazong1123/corefx,shmao/corefx,rjxby/corefx,ericstj/corefx,wtgodbe/corefx,JosephTremoulet/corefx,rubo/corefx,iamjasonp/corefx,mazong1123/corefx,krytarowski/corefx,dotnet-bot/corefx,fgreinacher/corefx,mazong1123/corefx,Ermiar/corefx,ericstj/corefx,rahku/corefx,jlin177/corefx,DnlHarvey/corefx,kkurni/corefx,the-dwyer/corefx,wtgodbe/corefx,jhendrixMSFT/corefx,mmitche/corefx,zhenlan/corefx,jcme/corefx,stone-li/corefx,Ermiar/corefx,parjong/corefx,MaggieTsang/corefx,JosephTremoulet/corefx,shimingsg/corefx,Chrisboh/corefx,stone-li/corefx,Jiayili1/corefx,parjong/corefx,seanshpark/corefx,ellismg/corefx,ravimeda/corefx,marksmeltzer/corefx,JosephTremoulet/corefx,lggomez/corefx,yizhang82/corefx,Petermarcu/corefx,Jiayili1/corefx,twsouthwick/corefx,nchikanov/corefx,shimingsg/corefx,pallavit/corefx,axelheer/corefx,twsouthwick/corefx,krytarowski/corefx,zhenlan/corefx,shimingsg/corefx,ericstj/corefx,nchikanov/corefx,wtgodbe/corefx,dhoehna/corefx,mazong1123/corefx,seanshpark/corefx,ellismg/corefx,dotnet-bot/corefx,khdang/corefx,jcme/corefx,ptoonen/corefx,gkhanna79/corefx,mmitche/corefx,jlin177/corefx,Petermarcu/corefx,YoupHulsebos/corefx,jcme/corefx,dsplaisted/corefx,nchikanov/corefx,cydhaselton/corefx,manu-silicon/corefx,dsplaisted/corefx,stephenmichaelf/corefx,SGuyGe/corefx,shmao/corefx,axelheer/corefx,alexperovich/corefx,seanshpark/corefx,Jiayili1/corefx,gkhanna79/corefx,pallavit/corefx,shimingsg/corefx,the-dwyer/corefx,cartermp/corefx,richlander/corefx,Priya91/corefx-1,ericstj/corefx,axelheer/corefx,khdang/corefx,DnlHarvey/corefx,shahid-pk/corefx,rjxby/corefx,twsouthwick/corefx,rubo/corefx,weltkante/corefx,nbarbettini/corefx,Ermiar/corefx,billwert/corefx,YoupHulsebos/corefx,khdang/corefx,rubo/corefx,yizhang82/corefx,wtgodbe/corefx,MaggieTsang/corefx,Chrisboh/corefx,Ermiar/corefx,Petermarcu/corefx,jhendrixMSFT/corefx,MaggieTsang/corefx,nchikanov/corefx,Jiayili1/corefx,mazong1123/corefx,gkhanna79/corefx,tijoytom/corefx,Chrisboh/corefx,khdang/corefx,manu-silicon/corefx,alexperovich/corefx,the-dwyer/corefx,DnlHarvey/corefx
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoReadOnly.cs
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoReadOnly.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class DateTimeFormatInfoReadOnly { public static IEnumerable<object[]> ReadOnly_TestData() { yield return new object[] { DateTimeFormatInfo.InvariantInfo, true }; yield return new object[] { DateTimeFormatInfo.ReadOnly(new DateTimeFormatInfo()), true }; yield return new object[] { new DateTimeFormatInfo(), false }; yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false }; } [Theory] [MemberData(nameof(ReadOnly_TestData))] public void ReadOnly(DateTimeFormatInfo format, bool originalFormatIsReadOnly) { Assert.Equal(originalFormatIsReadOnly, format.IsReadOnly); DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format); if (originalFormatIsReadOnly) { Assert.Same(format, readOnlyFormat); } else { Assert.NotSame(format, readOnlyFormat); } Assert.True(readOnlyFormat.IsReadOnly); } [Fact] public void ReadOnly_Null_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class DateTimeFormatInfoReadOnly { public static IEnumerable<object[]> ReadOnly_TestData() { yield return new object[] { DateTimeFormatInfo.InvariantInfo, true }; yield return new object[] { new DateTimeFormatInfo(), false }; yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false }; } [Theory] [MemberData(nameof(ReadOnly_TestData))] public void ReadOnly(DateTimeFormatInfo format, bool expected) { Assert.Equal(expected, format.IsReadOnly); DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format); Assert.True(readOnlyFormat.IsReadOnly); } [Fact] public void ReadOnly_Null_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null } } }
mit
C#
81b8f9df915770eb210b04526a739f39366d453b
Fix flaky histogram aggregation (#4111)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Tests/Tests/Aggregations/Bucket/Histogram/HistogramAggregationUsageTests.cs
src/Tests/Tests/Aggregations/Bucket/Histogram/HistogramAggregationUsageTests.cs
using System; using FluentAssertions; using Nest; using Tests.Core.Extensions; using Tests.Core.ManagedElasticsearch.Clusters; using Tests.Domain; using Tests.Framework.EndpointTests.TestState; using static Nest.Infer; namespace Tests.Aggregations.Bucket.Histogram { public class HistogramAggregationUsageTests : AggregationUsageTestBase { public HistogramAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override object AggregationJson => new { commits = new { histogram = new { field = "numberOfCommits", interval = 100.0, min_doc_count = 1, order = new { _key = "desc" }, offset = 1.1 } } }; protected override Func<AggregationContainerDescriptor<Project>, IAggregationContainer> FluentAggs => a => a .Histogram("commits", h => h .Field(p => p.NumberOfCommits) .Interval(100) .MinimumDocumentCount(1) .Order(HistogramOrder.KeyDescending) .Offset(1.1) ); protected override AggregationDictionary InitializerAggs => new HistogramAggregation("commits") { Field = Field<Project>(p => p.NumberOfCommits), Interval = 100, MinimumDocumentCount = 1, Order = HistogramOrder.KeyDescending, Offset = 1.1 }; protected override void ExpectResponse(ISearchResponse<Project> response) { response.ShouldBeValid(); var commits = response.Aggregations.Histogram("commits"); commits.Should().NotBeNull(); commits.Buckets.Should().NotBeNull(); commits.Buckets.Count.Should().BeGreaterThan(0); foreach (var item in commits.Buckets) item.DocCount.Should().BeGreaterThan(0); } } }
using System; using FluentAssertions; using Nest; using Tests.Core.Extensions; using Tests.Core.ManagedElasticsearch.Clusters; using Tests.Domain; using Tests.Framework.EndpointTests.TestState; using static Nest.Infer; namespace Tests.Aggregations.Bucket.Histogram { public class HistogramAggregationUsageTests : AggregationUsageTestBase { public HistogramAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override object AggregationJson => new { commits = new { histogram = new { field = "numberOfCommits", interval = 100.0, missing = 0.0, order = new { _key = "desc" }, offset = 1.1 } } }; protected override Func<AggregationContainerDescriptor<Project>, IAggregationContainer> FluentAggs => a => a .Histogram("commits", h => h .Field(p => p.NumberOfCommits) .Interval(100) .Missing(0) .Order(HistogramOrder.KeyDescending) .Offset(1.1) ); protected override AggregationDictionary InitializerAggs => new HistogramAggregation("commits") { Field = Field<Project>(p => p.NumberOfCommits), Interval = 100, Missing = 0, Order = HistogramOrder.KeyDescending, Offset = 1.1 }; protected override void ExpectResponse(ISearchResponse<Project> response) { response.ShouldBeValid(); var commits = response.Aggregations.Histogram("commits"); commits.Should().NotBeNull(); commits.Buckets.Should().NotBeNull(); commits.Buckets.Count.Should().BeGreaterThan(0); foreach (var item in commits.Buckets) item.DocCount.Should().BeGreaterThan(0); } } }
apache-2.0
C#
e2f9392f47377bf7c0a2084de2162435434e512d
Build version 2.3.0
locana/locana
Locana/Properties/AssemblyInfo.cs
Locana/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; 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("Locana")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Locana")] [assembly: AssemblyCopyright("Copyright © kazyx 2013-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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.3.0.0")] [assembly: AssemblyFileVersion("2.3.0.0")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")]
using System.Reflection; using System.Resources; 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("Locana")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Locana")] [assembly: AssemblyCopyright("Copyright © kazyx 2013-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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.2.0")] [assembly: AssemblyFileVersion("2.2.2.0")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")]
mit
C#
20ef9ff630476e6a5d875a05386552ba33ad5761
clean up and simplify logic
nats-io/csnats
NATS.Client/Srv.cs
NATS.Client/Srv.cs
// Copyright 2015-2018 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace NATS.Client { // Tracks individual backend servers. internal class Srv { private const string defaultScheme = "nats://"; private const int defaultPort = 4222; private const int noPortSpecified = -1; internal Uri url = null; internal bool didConnect = false; internal int reconnects = 0; internal DateTime lastAttempt = DateTime.Now; internal bool isImplicit = false; // never create a srv object without a url. private Srv() { } internal Srv(string urlString) { Uri uri; if (!Uri.TryCreate(urlString, UriKind.Absolute, out uri) && !Uri.TryCreate(defaultScheme + urlString, UriKind.Absolute, out uri)) throw new UriFormatException(); var builder = new UriBuilder(uri); builder.Port = builder.Port == noPortSpecified ? defaultPort : builder.Port; url = builder.Uri; } internal Srv(string urlString, bool isUrlImplicit) : this(urlString) { isImplicit = isUrlImplicit; } internal void updateLastAttempt() { lastAttempt = DateTime.Now; } internal TimeSpan TimeSinceLastAttempt { get { return (DateTime.Now - lastAttempt); } } } }
// Copyright 2015-2018 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace NATS.Client { // Tracks individual backend servers. internal class Srv { internal Uri url = null; internal bool didConnect = false; internal int reconnects = 0; internal DateTime lastAttempt = DateTime.Now; internal bool isImplicit = false; // never create a srv object without a url. private Srv() { } internal Srv(string urlString) { try { url = new Uri(urlString); } catch (UriFormatException e) { var baseUrl = new Uri("nats://localhost"); try { url = new Uri(baseUrl, "//" + urlString); } catch (Exception e) { throw new ArgumentException("Bad server URL: " + urlString, e); } } catch (Exception e) { throw new ArgumentException("Bad server URL: " + urlString, e); } if (url.Port == -1) { url.Port = 4222; } } internal Srv(string urlString, bool isUrlImplicit) : this(urlString) { isImplicit = isUrlImplicit; } internal void updateLastAttempt() { lastAttempt = DateTime.Now; } internal TimeSpan TimeSinceLastAttempt { get { return (DateTime.Now - lastAttempt); } } } }
mit
C#
b045c00aa3818d2ab64ef94667f458a72ff12458
introduce IAssemblyBaseDirectoryProvider
isukces/isukces.code
isukces.code/Features/AutoCode/+Interfaces/ICsClassFactory.cs
isukces.code/Features/AutoCode/+Interfaces/ICsClassFactory.cs
using System; using System.IO; using System.Reflection; namespace isukces.code.AutoCode { public interface IAutoCodeGenerator { void Generate(Type type, IAutoCodeGeneratorContext context); } public interface IAssemblyAutoCodeGenerator { void AssemblyStart(Assembly assembly, IAutoCodeGeneratorContext context); void AssemblyEnd(Assembly assembly, IAutoCodeGeneratorContext context); } public interface IAssemblyBaseDirectoryProvider { DirectoryInfo GetBaseDirectory(Assembly assembly); } }
using System; using System.Reflection; namespace isukces.code.AutoCode { public interface IAutoCodeGenerator { void Generate(Type type, IAutoCodeGeneratorContext context); } public interface IAssemblyAutoCodeGenerator { void AssemblyStart(Assembly assembly, IAutoCodeGeneratorContext context); void AssemblyEnd(Assembly assembly, IAutoCodeGeneratorContext context); } }
mit
C#
06506ad31cb3bdfd18d1fc4a1cd015124403b1dd
Fix running test multiple times in same .NET runtime instance
caiguihou/myprj_02,shadowmint/fullserializer,karlgluck/fullserializer,jagt/fullserializer,shadowmint/fullserializer,jacobdufault/fullserializer,darress/fullserializer,jagt/fullserializer,Ksubaka/fullserializer,shadowmint/fullserializer,Ksubaka/fullserializer,lazlo-bonin/fullserializer,jacobdufault/fullserializer,zodsoft/fullserializer,Ksubaka/fullserializer,jacobdufault/fullserializer,jagt/fullserializer,nuverian/fullserializer
Testing/Editor/SpecifiedConverterTests.cs
Testing/Editor/SpecifiedConverterTests.cs
using System; using FullSerializer.Internal; using NUnit.Framework; using System.Collections.Generic; namespace FullSerializer.Tests { [fsObject(Converter = typeof(MyConverter))] public class MyModel { } public class MyConverter : fsConverter { public static bool DidSerialize = false; public static bool DidDeserialize = false; public override bool CanProcess(Type type) { throw new NotSupportedException(); } public override object CreateInstance(fsData data, Type storageType) { return new MyModel(); } public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) { DidSerialize = true; serialized = new fsData(); return fsFailure.Success; } public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) { DidDeserialize = true; return fsFailure.Success; } } public class SpecifiedConverterTests { [Test] public void VerifyConversion() { MyConverter.DidDeserialize = false; MyConverter.DidSerialize = false; var serializer = new fsSerializer(); fsData result; serializer.TrySerialize(new MyModel(), out result); Assert.IsTrue(MyConverter.DidSerialize); Assert.IsFalse(MyConverter.DidDeserialize); MyConverter.DidSerialize = false; object resultObj = null; serializer.TryDeserialize(result, typeof (MyModel), ref resultObj); Assert.IsFalse(MyConverter.DidSerialize); Assert.IsTrue(MyConverter.DidDeserialize); } } }
using System; using FullSerializer.Internal; using NUnit.Framework; using System.Collections.Generic; namespace FullSerializer.Tests { [fsObject(Converter = typeof(MyConverter))] public class MyModel { } public class MyConverter : fsConverter { public static bool DidSerialize = false; public static bool DidDeserialize = false; public override bool CanProcess(Type type) { throw new NotSupportedException(); } public override object CreateInstance(fsData data, Type storageType) { return new MyModel(); } public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) { DidSerialize = true; serialized = new fsData(); return fsFailure.Success; } public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) { DidDeserialize = true; return fsFailure.Success; } } public class SpecifiedConverterTests { [Test] public void VerifyConversion() { var serializer = new fsSerializer(); fsData result; serializer.TrySerialize(new MyModel(), out result); Assert.IsTrue(MyConverter.DidSerialize); Assert.IsFalse(MyConverter.DidDeserialize); MyConverter.DidSerialize = false; object resultObj = null; serializer.TryDeserialize(result, typeof (MyModel), ref resultObj); Assert.IsFalse(MyConverter.DidSerialize); Assert.IsTrue(MyConverter.DidDeserialize); } } }
mit
C#
e70eac45b8ae8cf5b4e8c75496005c7198387ee3
Fix 401 malformed WWW-Authenticate (#4649)
MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4
src/IdentityServer4/src/Endpoints/Results/ProtectedResourceErrorResult.cs
src/IdentityServer4/src/Endpoints/Results/ProtectedResourceErrorResult.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Threading.Tasks; using IdentityServer4.Extensions; using Microsoft.Extensions.Primitives; using IdentityServer4.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; using IdentityModel; namespace IdentityServer4.Endpoints.Results { internal class ProtectedResourceErrorResult : IEndpointResult { public string Error; public string ErrorDescription; public ProtectedResourceErrorResult(string error, string errorDescription = null) { Error = error; ErrorDescription = errorDescription; } public Task ExecuteAsync(HttpContext context) { context.Response.StatusCode = 401; context.Response.SetNoCache(); if (Constants.ProtectedResourceErrorStatusCodes.ContainsKey(Error)) { context.Response.StatusCode = Constants.ProtectedResourceErrorStatusCodes[Error]; } if (Error == OidcConstants.ProtectedResourceErrors.ExpiredToken) { Error = OidcConstants.ProtectedResourceErrors.InvalidToken; ErrorDescription = "The access token expired"; } var errorString = string.Format($"error=\"{Error}\""); if (ErrorDescription.IsMissing()) { context.Response.Headers.Add(HeaderNames.WWWAuthenticate, new StringValues(new[] { "Bearer realm=\"IdentityServer\"", errorString })); } else { var errorDescriptionString = string.Format($"error_description=\"{ErrorDescription}\""); context.Response.Headers.Add(HeaderNames.WWWAuthenticate, new StringValues(new[] { "Bearer realm=\"IdentityServer\"", errorString, errorDescriptionString })); } return Task.CompletedTask; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Threading.Tasks; using IdentityServer4.Extensions; using Microsoft.Extensions.Primitives; using IdentityServer4.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; using IdentityModel; namespace IdentityServer4.Endpoints.Results { internal class ProtectedResourceErrorResult : IEndpointResult { public string Error; public string ErrorDescription; public ProtectedResourceErrorResult(string error, string errorDescription = null) { Error = error; ErrorDescription = errorDescription; } public Task ExecuteAsync(HttpContext context) { context.Response.StatusCode = 401; context.Response.SetNoCache(); if (Constants.ProtectedResourceErrorStatusCodes.ContainsKey(Error)) { context.Response.StatusCode = Constants.ProtectedResourceErrorStatusCodes[Error]; } if (Error == OidcConstants.ProtectedResourceErrors.ExpiredToken) { Error = OidcConstants.ProtectedResourceErrors.InvalidToken; ErrorDescription = "The access token expired"; } var errorString = string.Format($"error=\"{Error}\""); if (ErrorDescription.IsMissing()) { context.Response.Headers.Add(HeaderNames.WWWAuthenticate, new StringValues(new[] { "Bearer", errorString })); } else { var errorDescriptionString = string.Format($"error_description=\"{ErrorDescription}\""); context.Response.Headers.Add(HeaderNames.WWWAuthenticate, new StringValues(new[] { "Bearer", errorString, errorDescriptionString })); } return Task.CompletedTask; } } }
apache-2.0
C#