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
f148cbd633f079ffccab110a85d69b0351679bb2
Remove unused members from AssertException.
fixie/fixie
src/Fixie.Tests/Assertions/AssertException.cs
src/Fixie.Tests/Assertions/AssertException.cs
namespace Fixie.Tests.Assertions { using System; using System.Collections.Generic; using static System.Environment; public class AssertException : Exception { public static string FilterStackTraceAssemblyPrefix = typeof(AssertException).Namespace + "."; public AssertException(string message) : base(message) { } public override string? StackTrace => FilterStackTrace(base.StackTrace); static string? FilterStackTrace(string? stackTrace) { if (stackTrace == null) return null; var results = new List<string>(); foreach (var line in Lines(stackTrace)) { var trimmedLine = line.TrimStart(); if (!trimmedLine.StartsWith("at " + FilterStackTraceAssemblyPrefix)) results.Add(line); } return string.Join(NewLine, results.ToArray()); } static string[] Lines(string input) { return input.Split(new[] {NewLine}, StringSplitOptions.None); } } }
namespace Fixie.Tests.Assertions { using System; using System.Collections.Generic; using System.Text; using static System.Environment; public class AssertException : Exception { public static string FilterStackTraceAssemblyPrefix = typeof(AssertException).Namespace + "."; public AssertException(string message) : base(message) { } public AssertException(object? expected, object? actual) : base(ExpectationMessage(expected, actual)) { } static string ExpectationMessage(object? expected, object? actual) { var message = new StringBuilder(); message.AppendLine($"Expected: {expected?.ToString() ?? "null"}"); message.Append($"Actual: {actual?.ToString() ?? "null"}"); return message.ToString(); } public override string? StackTrace => FilterStackTrace(base.StackTrace); static string? FilterStackTrace(string? stackTrace) { if (stackTrace == null) return null; var results = new List<string>(); foreach (var line in Lines(stackTrace)) { var trimmedLine = line.TrimStart(); if (!trimmedLine.StartsWith("at " + FilterStackTraceAssemblyPrefix)) results.Add(line); } return string.Join(NewLine, results.ToArray()); } static string[] Lines(string input) { return input.Split(new[] {NewLine}, StringSplitOptions.None); } } }
mit
C#
1baf1124bac1a62e0e971818f99936b18c9121ed
Fix more tests
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/UnitTest/SyndicationItemExtensionsTest.cs
src/UnitTest/SyndicationItemExtensionsTest.cs
using Firehose.Web.Extensions; using System; using System.ServiceModel.Syndication; using Xunit; namespace UnitTest { public class SyndicationItemExtensionsTest { [Fact] public void FilterPowerShellTitleTest() { var item = new SyndicationItem("some blog post about powershell android stuff", "whatever", new Uri("http://derp.org")); var ok = item.ApplyDefaultFilter(); Assert.True(ok); item = new SyndicationItem("some blog post about native android stuff", "whatever", new Uri("http://derp.org")); ok = item.ApplyDefaultFilter(); Assert.False(ok); } [Fact] public void FilterPowerShellCategoryTest() { var item = new SyndicationItem(); item.Categories.Add(new SyndicationCategory("android")); item.Categories.Add(new SyndicationCategory("ios")); item.Categories.Add(new SyndicationCategory("powershell")); var ok = item.ApplyDefaultFilter(); Assert.True(ok); item.Categories.RemoveAt(2); ok = item.ApplyDefaultFilter(); Assert.False(ok); } [Fact] public void FitlerPowerShellTitleAndCategoryTest() { var item = new SyndicationItem("some blog post about powershell android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("powershell")); var ok = item.ApplyDefaultFilter(); Assert.True(ok); item = new SyndicationItem("some blog post about java android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("java")); ok = item.ApplyDefaultFilter(); Assert.False(ok); item = new SyndicationItem("some blog post about java android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("powershell")); ok = item.ApplyDefaultFilter(); Assert.True(ok); item = new SyndicationItem("some blog post about powershell android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("java")); ok = item.ApplyDefaultFilter(); Assert.True(ok); } } }
using Firehose.Web.Extensions; using System; using System.ServiceModel.Syndication; using Xunit; namespace UnitTest { public class SyndicationItemExtensionsTest { [Fact] public void FilterXamarinTitleTest() { var item = new SyndicationItem("some blog post about xamarin android stuff", "whatever", new Uri("http://derp.org")); var ok = item.ApplyDefaultFilter(); Assert.True(ok); item = new SyndicationItem("some blog post about native android stuff", "whatever", new Uri("http://derp.org")); ok = item.ApplyDefaultFilter(); Assert.False(ok); } [Fact] public void FilterXamarinCategoryTest() { var item = new SyndicationItem(); item.Categories.Add(new SyndicationCategory("android")); item.Categories.Add(new SyndicationCategory("ios")); item.Categories.Add(new SyndicationCategory("xamarin")); var ok = item.ApplyDefaultFilter(); Assert.True(ok); item.Categories.RemoveAt(2); ok = item.ApplyDefaultFilter(); Assert.False(ok); } [Fact] public void FitlerXamarinTitleAndCategoryTest() { var item = new SyndicationItem("some blog post about xamarin android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("xamarin")); var ok = item.ApplyDefaultFilter(); Assert.True(ok); item = new SyndicationItem("some blog post about java android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("java")); ok = item.ApplyDefaultFilter(); Assert.False(ok); item = new SyndicationItem("some blog post about java android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("xamarin")); ok = item.ApplyDefaultFilter(); Assert.True(ok); item = new SyndicationItem("some blog post about xamarin android stuff", "whatever", new Uri("http://derp.org")); item.Categories.Add(new SyndicationCategory("java")); ok = item.ApplyDefaultFilter(); Assert.True(ok); } } }
mit
C#
07c3113d7c3cb92c6cf3bcf94f11ddc0385973b2
Make edge IEquatable
DasAllFolks/SharpGraphs
Graph/IEdge.cs
Graph/IEdge.cs
using System; namespace Graph { /// <summary> /// Default interface for a graph edge, whether directed or undirected. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> public interface IEdge<V> : IEquatable<IEdge<V>> where V : struct, IEquatable<V> { } }
namespace Graph { /// <summary> /// Default interface for a graph edge, whether directed or undirected. /// </summary> /// <typeparam name="T"> /// The type used to create vertex (node) labels. /// </typeparam> public interface IEdge<T> { } }
apache-2.0
C#
07d48bc8396f9914ebd8539879cdc7632681c629
Rename some methods.
Mattias1/builderbuilder
IdGenerator.cs
IdGenerator.cs
using System; using System.Collections.Generic; namespace Something.Something.TestHelpers { public class IdGenerator { public enum Type { Unspecified }; private static IdGenerator idGenerator; private Dictionary<Type, int> currentIds; private object lockObj = new object(); private static IdGenerator Get => idGenerator ?? (idGenerator = new IdGenerator()); public static int Next() => Next(Type.Unspecified); public static int Next(Type type) => Get.CalculateNext(type); public static Guid NextGuid() => NextGuid(Type.Unspecified); public static Guid NextGuid(Type type) => Get.CalculateNextGuid(type); private IdGenerator() { var types = (Type[])Enum.GetValues(typeof(Type)); currentIds = new Dictionary<Type, int>(types.Length); foreach (Type type in types) { currentIds[type] = 0; } } public int CalculateNext(Type type) { lock (lockObj) { currentIds[type]++; return currentIds[type]; } } public Guid CalculateNextGuid(Type type) { lock (lockObj) { currentIds[type]++; return new Guid(currentIds[type], 0, 0, new byte[8]); } } } }
using System; using System.Collections.Generic; namespace Something.Something.TestHelpers { public class IdGenerator { public enum Type { Unspecified }; private static IdGenerator idGenerator; private Dictionary<Type, int> currentIds; private object lockObj = new object(); private static IdGenerator Get => idGenerator ?? (idGenerator = new IdGenerator()); public static int Next() => Next(Type.Unspecified); public static int Next(Type type) => Get.Next(type); public static Guid NextGuid() => NextGuid(Type.Unspecified); public static Guid NextGuid(Type type) => Get.NextGuid(type); private IdGenerator() { var types = (Type[])Enum.GetValues(typeof(Type)); currentIds = new Dictionary<Type, int>(types.Length); foreach (Type type in types) { currentIds[type] = 0; } } public int Next(Type type) { lock (lockObj) { currentIds[type]++; return currentIds[type]; } } public Guid NextGuid(Type type) { lock (lockObj) { currentIds[type]++; return new Guid(currentIds[type], 0, 0, new byte[8]); } } } }
mit
C#
e92c836e5ac4d75f85ed8be6158cd3d12ed6370f
Add Selector events
erebuswolf/LockstepFramework,yanyiyun/LockstepFramework,SnpM/Lockstep-Framework
Core/Game/Player/Utility/Selector.cs
Core/Game/Player/Utility/Selector.cs
using UnityEngine; using System; namespace Lockstep { public static class Selector { public static event Action onChange; public static event Action onAdd; public static event Action onRemove; private static LSAgent _mainAgent; static Selector () { onAdd += Change; onRemove += Change; } private static void Change () { if (onChange != null) onChange(); } public static LSAgent MainSelectedAgent {get {return _mainAgent;} private set{ _mainAgent = value; } } private static FastSorter<LSAgent> SelectedAgents; public static void Initialize (){ } public static void Add(LSAgent agent) { agent.Controller.AddToSelection (agent); agent.IsSelected = true; if (MainSelectedAgent == null) MainSelectedAgent = agent; onAdd (); } public static void Remove(LSAgent agent) { agent.Controller.RemoveFromSelection (agent); agent.IsSelected = false; if (agent == MainSelectedAgent) { agent = SelectedAgents.Count > 0 ? SelectedAgents.PopMax () : null; } onRemove (); } public static void Clear() { for (int i = 0; i < PlayerManager.AgentControllerCount; i++) { FastBucket<LSAgent> selectedAgents = PlayerManager.AgentControllers[i].SelectedAgents; for (int j = 0; j < selectedAgents.PeakCount; j++) { if (selectedAgents.arrayAllocation[j]) { selectedAgents[j].IsSelected = false; } } selectedAgents.FastClear (); } MainSelectedAgent = null; } } }
using UnityEngine; namespace Lockstep { public static class Selector { private static LSAgent _mainAgent; public static LSAgent MainSelectedAgent {get {return _mainAgent;} private set{ _mainAgent = value; } } private static FastSorter<LSAgent> SelectedAgents; public static void Initialize (){ } public static void Add(LSAgent agent) { agent.Controller.AddToSelection (agent); agent.IsSelected = true; if (MainSelectedAgent == null) MainSelectedAgent = agent; } public static void Remove(LSAgent agent) { agent.Controller.RemoveFromSelection (agent); agent.IsSelected = false; if (agent == MainSelectedAgent) { agent = SelectedAgents.Count > 0 ? SelectedAgents.PopMax () : null; } } public static void Clear() { for (int i = 0; i < PlayerManager.AgentControllerCount; i++) { FastBucket<LSAgent> selectedAgents = PlayerManager.AgentControllers[i].SelectedAgents; for (int j = 0; j < selectedAgents.PeakCount; j++) { if (selectedAgents.arrayAllocation[j]) { selectedAgents[j].IsSelected = false; } } selectedAgents.FastClear (); } MainSelectedAgent = null; } } }
mit
C#
50b58cd6a658164d153c7b5284e3d6c9c73691a7
Add keyboard shortcut to open dev tools (Ctrl+Shift+I)
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
Core/Handling/KeyboardHandlerBase.cs
Core/Handling/KeyboardHandlerBase.cs
using System.Windows.Forms; using CefSharp; using TweetDuck.Core.Controls; using TweetDuck.Core.Other; using TweetDuck.Core.Utils; namespace TweetDuck.Core.Handling{ class KeyboardHandlerBase : IKeyboardHandler{ protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){ if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I){ if (BrowserUtils.HasDevTools){ browser.ShowDevTools(); } else{ browserControl.AsControl().InvokeSafe(() => { string extraMessage; if (Program.IsPortable){ extraMessage = "Please download the portable installer, select the folder with your current installation of TweetDuck Portable, and tick 'Install dev tools' during the installation process."; } else{ extraMessage = "Please download the installer, and tick 'Install dev tools' during the installation process. The installer will automatically find and update your current installation of TweetDuck."; } FormMessage.Information("Dev Tools", "You do not have dev tools installed. "+extraMessage, FormMessage.OK); }); } return true; } return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){ if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){ return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers); } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){ return false; } } }
using System.Windows.Forms; using CefSharp; namespace TweetDuck.Core.Handling{ class KeyboardHandlerBase : IKeyboardHandler{ protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){ return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){ if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){ return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers); } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){ return false; } } }
mit
C#
807a336e0119f35fdeba97c1305e161bf64f607e
update description
gaochundong/Cowboy.WebSockets
Cowboy.WebSockets/SolutionVersion.cs
Cowboy.WebSockets/SolutionVersion.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyDescription("Cowboy.WebSockets is a C# based library for building WebSocket services.")] [assembly: AssemblyCompany("Dennis Gao")] [assembly: AssemblyProduct("Cowboy.WebSockets")] [assembly: AssemblyCopyright("Copyright © 2015-2016 Dennis Gao")] [assembly: AssemblyTrademark("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.1.0")] [assembly: AssemblyFileVersion("1.3.1.0")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyDescription("Cowboy.WebSockets is a library for building WebSocket based services.")] [assembly: AssemblyCompany("Dennis Gao")] [assembly: AssemblyProduct("Cowboy.WebSockets")] [assembly: AssemblyCopyright("Copyright © 2015-2016 Dennis Gao")] [assembly: AssemblyTrademark("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.1.0")] [assembly: AssemblyFileVersion("1.3.1.0")] [assembly: ComVisible(false)]
mit
C#
55b75e90400884ecd82d6eabe43e71fceea5b66e
Update AssemblyInfo to 3.3 version
WaltChen/NDatabase,WaltChen/NDatabase
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System; 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("NDatabase")] [assembly: AssemblyDescription("C# Lightweight Object Database")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NDatabase")] [assembly: AssemblyProduct("NDatabase")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("NDatabase")] [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("480da8c2-ad2e-4aac-aacd-36a8cfa5581f")] [assembly: CLSCompliant(true)] // 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("3.3.0.*")] [assembly: AssemblyFileVersion("3.3.0.0")] [assembly: AssemblyInformationalVersion("3.3.0-stable")] [assembly: InternalsVisibleTo("NDatabase.UnitTests")] [assembly: InternalsVisibleTo("NDatabase.Old.UnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
using System; 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("NDatabase")] [assembly: AssemblyDescription("C# Lightweight Object Database")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NDatabase")] [assembly: AssemblyProduct("NDatabase")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("NDatabase")] [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("480da8c2-ad2e-4aac-aacd-36a8cfa5581f")] [assembly: CLSCompliant(true)] // 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("3.2.1.*")] [assembly: AssemblyFileVersion("3.2.1.0")] [assembly: AssemblyInformationalVersion("3.2.1-stable")] [assembly: InternalsVisibleTo("NDatabase.UnitTests")] [assembly: InternalsVisibleTo("NDatabase.Old.UnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
apache-2.0
C#
ca872618168cb95af5272a61574a9fcc17bcfe79
Add debugger display to ClrDataAddress (#437)
Microsoft/clrmd,Microsoft/clrmd,cshung/clrmd,cshung/clrmd
src/Microsoft.Diagnostics.Runtime/src/DacInterface/ClrDataAddress.cs
src/Microsoft.Diagnostics.Runtime/src/DacInterface/ClrDataAddress.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.Diagnostics.Runtime.DacInterface { /// <summary> /// A representation of CLR's CLRDATA_ADDRESS, which is a signed 64bit integer. /// Unfortuantely this can cause issues when inspecting 32bit processes, since /// if the highest bit is set the value will be sign-extended. This struct is /// meant to /// </summary> [DebuggerDisplay("{AsUInt64()}")] public struct ClrDataAddress { /// <summary> /// Raw value of this address. May be sign-extended if inspecting a 32bit process. /// </summary> public long Value { get; } /// <summary> /// Creates an instance of ClrDataAddress. /// </summary> /// <param name="value"></param> public ClrDataAddress(long value) => Value = value; /// <summary> /// Returns the value of this address and un-sign extends the value if appropriate. /// </summary> /// <param name="cda">The address to convert.</param> public static implicit operator ulong(ClrDataAddress cda) => cda.AsUInt64(); /// <summary> /// Returns the value of this address and un-sign extends the value if appropriate. /// </summary> /// <returns>The value of this address and un-sign extends the value if appropriate.</returns> private ulong AsUInt64() => IntPtr.Size == 4 ? (uint)Value : (ulong)Value; } }
// 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; namespace Microsoft.Diagnostics.Runtime.DacInterface { /// <summary> /// A representation of CLR's CLRDATA_ADDRESS, which is a signed 64bit integer. /// Unfortuantely this can cause issues when inspecting 32bit processes, since /// if the highest bit is set the value will be sign-extended. This struct is /// meant to /// </summary> public struct ClrDataAddress { /// <summary> /// Raw value of this address. May be sign-extended if inspecting a 32bit process. /// </summary> public long Value { get; } /// <summary> /// Creates an instance of ClrDataAddress. /// </summary> /// <param name="value"></param> public ClrDataAddress(long value) { Value = value; } /// <summary> /// Returns the value of this address and un-sign extends the value if appropriate. /// </summary> /// <param name="cda">The address to convert.</param> public static implicit operator ulong(ClrDataAddress cda) => cda.AsUInt64(); /// <summary> /// Returns the value of this address and un-sign extends the value if appropriate. /// </summary> /// <returns>The value of this address and un-sign extends the value if appropriate.</returns> private ulong AsUInt64() { if (IntPtr.Size == 4) return (uint)Value; return (ulong)Value; } } }
mit
C#
17dc5dcee0a3d43a683007d07c78adc022ba57e9
Add a Container enum (#1583)
superyyrrzz/docfx,dotnet/docfx,hellosnow/docfx,hellosnow/docfx,dotnet/docfx,DuncanmaMSFT/docfx,pascalberger/docfx,928PJY/docfx,superyyrrzz/docfx,hellosnow/docfx,superyyrrzz/docfx,928PJY/docfx,928PJY/docfx,pascalberger/docfx,pascalberger/docfx,DuncanmaMSFT/docfx,dotnet/docfx
src/Microsoft.DocAsCode.DataContracts.ManagedReference/MemberType.cs
src/Microsoft.DocAsCode.DataContracts.ManagedReference/MemberType.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.DataContracts.ManagedReference { using System; [Serializable] public enum MemberType { Default, Toc, Assembly, Namespace, Class, Interface, Struct, Delegate, Enum, Field, Property, Event, Constructor, Method, Operator, Container } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.DataContracts.ManagedReference { using System; [Serializable] public enum MemberType { Default, Toc, Assembly, Namespace, Class, Interface, Struct, Delegate, Enum, Field, Property, Event, Constructor, Method, Operator, } }
mit
C#
8a4f68a6e3b9c7f4d327efd21376feaf3181a550
Set non-zero timeout for DNX restore to complete.
mrward/monodevelop-dnx-addin
src/MonoDevelop.Dnx/Omnisharp/MonoDevelop/OmniSharpOptionsWrapper.cs
src/MonoDevelop.Dnx/Omnisharp/MonoDevelop/OmniSharpOptionsWrapper.cs
// // OmnisSharpOptionsWrapper.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using Microsoft.Framework.OptionsModel; using OmniSharp.Options; namespace MonoDevelop.Dnx.Omnisharp { public class OmniSharpOptionsWrapper : IOptions<OmniSharpOptions> { readonly OmniSharpOptions options; public OmniSharpOptionsWrapper () { options = new OmniSharpOptions (); options.Dnx.Projects = "**/project.json"; options.Dnx.EnablePackageRestore = true; options.Dnx.PackageRestoreTimeout = 180; } public OmniSharpOptions GetNamedOptions (string name) { throw new NotImplementedException (); } public OmniSharpOptions Options { get { return options; } } } }
// // OmnisSharpOptionsWrapper.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using Microsoft.Framework.OptionsModel; using OmniSharp.Options; namespace MonoDevelop.Dnx.Omnisharp { public class OmniSharpOptionsWrapper : IOptions<OmniSharpOptions> { readonly OmniSharpOptions options; public OmniSharpOptionsWrapper () { options = new OmniSharpOptions (); options.Dnx.Projects = "**/project.json"; options.Dnx.EnablePackageRestore = true; } public OmniSharpOptions GetNamedOptions (string name) { throw new NotImplementedException (); } public OmniSharpOptions Options { get { return options; } } } }
mit
C#
1b780e242e02c4d28ac8691794fc3661c897a736
Fix pages slug to not be case sensitive when used in url
dburriss/Orchard,Cphusion/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,stormleoxia/Orchard,luchaoshuai/Orchard,grapto/Orchard.CloudBust,AndreVolksdorf/Orchard,planetClaire/Orchard-LETS,omidnasri/Orchard,openbizgit/Orchard,patricmutwiri/Orchard,neTp9c/Orchard,Cphusion/Orchard,NIKASoftwareDevs/Orchard,arminkarimi/Orchard,yersans/Orchard,mgrowan/Orchard,Sylapse/Orchard.HttpAuthSample,sfmskywalker/Orchard,sfmskywalker/Orchard,huoxudong125/Orchard,qt1/Orchard,MetSystem/Orchard,neTp9c/Orchard,Codinlab/Orchard,tobydodds/folklife,qt1/orchard4ibn,LaserSrl/Orchard,hannan-azam/Orchard,abhishekluv/Orchard,jerryshi2007/Orchard,NIKASoftwareDevs/Orchard,Morgma/valleyviewknolls,RoyalVeterinaryCollege/Orchard,AndreVolksdorf/Orchard,armanforghani/Orchard,ehe888/Orchard,harmony7/Orchard,Fogolan/OrchardForWork,gcsuk/Orchard,dcinzona/Orchard-Harvest-Website,Cphusion/Orchard,Dolphinsimon/Orchard,fassetar/Orchard,jagraz/Orchard,mvarblow/Orchard,jerryshi2007/Orchard,luchaoshuai/Orchard,emretiryaki/Orchard,grapto/Orchard.CloudBust,SouleDesigns/SouleDesigns.Orchard,RoyalVeterinaryCollege/Orchard,hannan-azam/Orchard,huoxudong125/Orchard,escofieldnaxos/Orchard,Codinlab/Orchard,Cphusion/Orchard,TalaveraTechnologySolutions/Orchard,grapto/Orchard.CloudBust,caoxk/orchard,emretiryaki/Orchard,hhland/Orchard,austinsc/Orchard,johnnyqian/Orchard,enspiral-dev-academy/Orchard,kouweizhong/Orchard,jaraco/orchard,hbulzy/Orchard,salarvand/orchard,SeyDutch/Airbrush,yersans/Orchard,hannan-azam/Orchard,jagraz/Orchard,infofromca/Orchard,TaiAivaras/Orchard,jerryshi2007/Orchard,austinsc/Orchard,Dolphinsimon/Orchard,vairam-svs/Orchard,luchaoshuai/Orchard,hhland/Orchard,jtkech/Orchard,sebastienros/msc,jersiovic/Orchard,ericschultz/outercurve-orchard,johnnyqian/Orchard,jagraz/Orchard,Fogolan/OrchardForWork,andyshao/Orchard,RoyalVeterinaryCollege/Orchard,ericschultz/outercurve-orchard,fassetar/Orchard,jtkech/Orchard,brownjordaninternational/OrchardCMS,stormleoxia/Orchard,harmony7/Orchard,phillipsj/Orchard,vard0/orchard.tan,dcinzona/Orchard,marcoaoteixeira/Orchard,andyshao/Orchard,planetClaire/Orchard-LETS,openbizgit/Orchard,andyshao/Orchard,openbizgit/Orchard,kouweizhong/Orchard,KeithRaven/Orchard,Serlead/Orchard,jaraco/orchard,gcsuk/Orchard,m2cms/Orchard,IDeliverable/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,caoxk/orchard,spraiin/Orchard,jaraco/orchard,AndreVolksdorf/Orchard,ericschultz/outercurve-orchard,OrchardCMS/Orchard-Harvest-Website,arminkarimi/Orchard,Praggie/Orchard,DonnotRain/Orchard,planetClaire/Orchard-LETS,angelapper/Orchard,yonglehou/Orchard,smartnet-developers/Orchard,jchenga/Orchard,RoyalVeterinaryCollege/Orchard,aaronamm/Orchard,mgrowan/Orchard,caoxk/orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,mvarblow/Orchard,yonglehou/Orchard,dcinzona/Orchard,AEdmunds/beautiful-springtime,AdvantageCS/Orchard,ehe888/Orchard,OrchardCMS/Orchard-Harvest-Website,salarvand/Portal,kouweizhong/Orchard,RoyalVeterinaryCollege/Orchard,sfmskywalker/Orchard,dcinzona/Orchard-Harvest-Website,infofromca/Orchard,yersans/Orchard,SouleDesigns/SouleDesigns.Orchard,jtkech/Orchard,patricmutwiri/Orchard,Serlead/Orchard,angelapper/Orchard,vard0/orchard.tan,Inner89/Orchard,omidnasri/Orchard,TalaveraTechnologySolutions/Orchard,m2cms/Orchard,bigfont/orchard-cms-modules-and-themes,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,yonglehou/Orchard,jtkech/Orchard,stormleoxia/Orchard,JRKelso/Orchard,AndreVolksdorf/Orchard,openbizgit/Orchard,Serlead/Orchard,ehe888/Orchard,hbulzy/Orchard,Morgma/valleyviewknolls,JRKelso/Orchard,dozoft/Orchard,rtpHarry/Orchard,escofieldnaxos/Orchard,xkproject/Orchard,qt1/Orchard,bigfont/orchard-cms-modules-and-themes,geertdoornbos/Orchard,omidnasri/Orchard,ehe888/Orchard,qt1/orchard4ibn,mvarblow/Orchard,Lombiq/Orchard,OrchardCMS/Orchard,armanforghani/Orchard,jerryshi2007/Orchard,hannan-azam/Orchard,salarvand/Portal,andyshao/Orchard,oxwanawxo/Orchard,caoxk/orchard,xkproject/Orchard,ericschultz/outercurve-orchard,johnnyqian/Orchard,abhishekluv/Orchard,Anton-Am/Orchard,hhland/Orchard,hbulzy/Orchard,Dolphinsimon/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,cooclsee/Orchard,arminkarimi/Orchard,Praggie/Orchard,stormleoxia/Orchard,xiaobudian/Orchard,vairam-svs/Orchard,planetClaire/Orchard-LETS,sebastienros/msc,Lombiq/Orchard,yersans/Orchard,Serlead/Orchard,armanforghani/Orchard,asabbott/chicagodevnet-website,sebastienros/msc,armanforghani/Orchard,escofieldnaxos/Orchard,SzymonSel/Orchard,Inner89/Orchard,dcinzona/Orchard-Harvest-Website,dcinzona/Orchard-Harvest-Website,geertdoornbos/Orchard,gcsuk/Orchard,aaronamm/Orchard,johnnyqian/Orchard,sebastienros/msc,cooclsee/Orchard,m2cms/Orchard,OrchardCMS/Orchard-Harvest-Website,yonglehou/Orchard,hbulzy/Orchard,xiaobudian/Orchard,smartnet-developers/Orchard,harmony7/Orchard,austinsc/Orchard,marcoaoteixeira/Orchard,mgrowan/Orchard,Sylapse/Orchard.HttpAuthSample,fortunearterial/Orchard,sebastienros/msc,Praggie/Orchard,escofieldnaxos/Orchard,TaiAivaras/Orchard,Anton-Am/Orchard,alejandroaldana/Orchard,KeithRaven/Orchard,Codinlab/Orchard,angelapper/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,harmony7/Orchard,jersiovic/Orchard,enspiral-dev-academy/Orchard,SeyDutch/Airbrush,kgacova/Orchard,SzymonSel/Orchard,yersans/Orchard,austinsc/Orchard,Codinlab/Orchard,AEdmunds/beautiful-springtime,Dolphinsimon/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,asabbott/chicagodevnet-website,SouleDesigns/SouleDesigns.Orchard,cryogen/orchard,omidnasri/Orchard,xkproject/Orchard,bigfont/orchard-cms-modules-and-themes,TalaveraTechnologySolutions/Orchard,bedegaming-aleksej/Orchard,luchaoshuai/Orchard,AEdmunds/beautiful-springtime,enspiral-dev-academy/Orchard,Sylapse/Orchard.HttpAuthSample,Lombiq/Orchard,OrchardCMS/Orchard-Harvest-Website,emretiryaki/Orchard,geertdoornbos/Orchard,DonnotRain/Orchard,JRKelso/Orchard,jimasp/Orchard,qt1/orchard4ibn,Fogolan/OrchardForWork,SeyDutch/Airbrush,Ermesx/Orchard,spraiin/Orchard,phillipsj/Orchard,tobydodds/folklife,gcsuk/Orchard,enspiral-dev-academy/Orchard,abhishekluv/Orchard,kgacova/Orchard,LaserSrl/Orchard,xkproject/Orchard,fassetar/Orchard,jchenga/Orchard,grapto/Orchard.CloudBust,huoxudong125/Orchard,MpDzik/Orchard,dburriss/Orchard,LaserSrl/Orchard,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-continuous-integration-demo,omidnasri/Orchard,phillipsj/Orchard,li0803/Orchard,emretiryaki/Orchard,sfmskywalker/Orchard,SouleDesigns/SouleDesigns.Orchard,bedegaming-aleksej/Orchard,li0803/Orchard,tobydodds/folklife,omidnasri/Orchard,infofromca/Orchard,rtpHarry/Orchard,IDeliverable/Orchard,AdvantageCS/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,AdvantageCS/Orchard,vard0/orchard.tan,NIKASoftwareDevs/Orchard,KeithRaven/Orchard,angelapper/Orchard,Serlead/Orchard,AdvantageCS/Orchard,spraiin/Orchard,phillipsj/Orchard,qt1/Orchard,dburriss/Orchard,qt1/orchard4ibn,neTp9c/Orchard,rtpHarry/Orchard,TaiAivaras/Orchard,Lombiq/Orchard,MpDzik/Orchard,phillipsj/Orchard,AndreVolksdorf/Orchard,Praggie/Orchard,Fogolan/OrchardForWork,huoxudong125/Orchard,IDeliverable/Orchard,jimasp/Orchard,bigfont/orchard-continuous-integration-demo,MpDzik/Orchard,cryogen/orchard,jimasp/Orchard,yonglehou/Orchard,oxwanawxo/Orchard,DonnotRain/Orchard,sfmskywalker/Orchard,harmony7/Orchard,IDeliverable/Orchard,MpDzik/Orchard,patricmutwiri/Orchard,Lombiq/Orchard,kouweizhong/Orchard,infofromca/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,KeithRaven/Orchard,hannan-azam/Orchard,qt1/Orchard,cryogen/orchard,oxwanawxo/Orchard,asabbott/chicagodevnet-website,huoxudong125/Orchard,tobydodds/folklife,fortunearterial/Orchard,abhishekluv/Orchard,SeyDutch/Airbrush,qt1/Orchard,OrchardCMS/Orchard-Harvest-Website,cooclsee/Orchard,li0803/Orchard,salarvand/Portal,ehe888/Orchard,jaraco/orchard,Sylapse/Orchard.HttpAuthSample,kgacova/Orchard,brownjordaninternational/OrchardCMS,bigfont/orchard-continuous-integration-demo,mvarblow/Orchard,hhland/Orchard,vairam-svs/Orchard,MpDzik/Orchard,sfmskywalker/Orchard,DonnotRain/Orchard,jchenga/Orchard,enspiral-dev-academy/Orchard,dozoft/Orchard,salarvand/Portal,IDeliverable/Orchard,omidnasri/Orchard,aaronamm/Orchard,Morgma/valleyviewknolls,vard0/orchard.tan,brownjordaninternational/OrchardCMS,oxwanawxo/Orchard,Anton-Am/Orchard,SzymonSel/Orchard,jchenga/Orchard,neTp9c/Orchard,cooclsee/Orchard,NIKASoftwareDevs/Orchard,xkproject/Orchard,kouweizhong/Orchard,geertdoornbos/Orchard,TalaveraTechnologySolutions/Orchard,alejandroaldana/Orchard,Ermesx/Orchard,stormleoxia/Orchard,SouleDesigns/SouleDesigns.Orchard,jagraz/Orchard,jchenga/Orchard,austinsc/Orchard,smartnet-developers/Orchard,patricmutwiri/Orchard,AdvantageCS/Orchard,armanforghani/Orchard,m2cms/Orchard,oxwanawxo/Orchard,kgacova/Orchard,salarvand/orchard,Inner89/Orchard,jagraz/Orchard,dozoft/Orchard,marcoaoteixeira/Orchard,vairam-svs/Orchard,emretiryaki/Orchard,fortunearterial/Orchard,Ermesx/Orchard,hhland/Orchard,dburriss/Orchard,patricmutwiri/Orchard,dcinzona/Orchard,TalaveraTechnologySolutions/Orchard,Sylapse/Orchard.HttpAuthSample,escofieldnaxos/Orchard,dcinzona/Orchard,jimasp/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,OrchardCMS/Orchard,OrchardCMS/Orchard,rtpHarry/Orchard,fassetar/Orchard,TalaveraTechnologySolutions/Orchard,TaiAivaras/Orchard,planetClaire/Orchard-LETS,fortunearterial/Orchard,Inner89/Orchard,bigfont/orchard-cms-modules-and-themes,Morgma/valleyviewknolls,spraiin/Orchard,cooclsee/Orchard,hbulzy/Orchard,salarvand/Portal,jtkech/Orchard,JRKelso/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,TalaveraTechnologySolutions/Orchard,NIKASoftwareDevs/Orchard,MetSystem/Orchard,grapto/Orchard.CloudBust,dburriss/Orchard,omidnasri/Orchard,Anton-Am/Orchard,bigfont/orchard-continuous-integration-demo,andyshao/Orchard,kgacova/Orchard,smartnet-developers/Orchard,jersiovic/Orchard,m2cms/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,MetSystem/Orchard,asabbott/chicagodevnet-website,aaronamm/Orchard,dcinzona/Orchard,cryogen/orchard,bedegaming-aleksej/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,salarvand/orchard,vard0/orchard.tan,OrchardCMS/Orchard,luchaoshuai/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,SzymonSel/Orchard,Praggie/Orchard,arminkarimi/Orchard,mgrowan/Orchard,LaserSrl/Orchard,alejandroaldana/Orchard,DonnotRain/Orchard,alejandroaldana/Orchard,MetSystem/Orchard,tobydodds/folklife,OrchardCMS/Orchard-Harvest-Website,Codinlab/Orchard,omidnasri/Orchard,qt1/orchard4ibn,gcsuk/Orchard,li0803/Orchard,Ermesx/Orchard,dcinzona/Orchard-Harvest-Website,infofromca/Orchard,JRKelso/Orchard,Fogolan/OrchardForWork,neTp9c/Orchard,openbizgit/Orchard,marcoaoteixeira/Orchard,marcoaoteixeira/Orchard,dcinzona/Orchard-Harvest-Website,vairam-svs/Orchard,jersiovic/Orchard,TalaveraTechnologySolutions/Orchard,Cphusion/Orchard,TaiAivaras/Orchard,Dolphinsimon/Orchard,aaronamm/Orchard,johnnyqian/Orchard,Morgma/valleyviewknolls,sfmskywalker/Orchard,MpDzik/Orchard,sfmskywalker/Orchard,Inner89/Orchard,brownjordaninternational/OrchardCMS,OrchardCMS/Orchard,grapto/Orchard.CloudBust,SzymonSel/Orchard,MetSystem/Orchard,AEdmunds/beautiful-springtime,dmitry-urenev/extended-orchard-cms-v10.1,jimasp/Orchard,fortunearterial/Orchard,angelapper/Orchard,alejandroaldana/Orchard,Ermesx/Orchard,bedegaming-aleksej/Orchard,SeyDutch/Airbrush,abhishekluv/Orchard,mgrowan/Orchard,abhishekluv/Orchard,salarvand/orchard,LaserSrl/Orchard,brownjordaninternational/OrchardCMS,arminkarimi/Orchard,Anton-Am/Orchard,xiaobudian/Orchard,smartnet-developers/Orchard,dozoft/Orchard,xiaobudian/Orchard,KeithRaven/Orchard,salarvand/orchard,dozoft/Orchard,tobydodds/folklife,bedegaming-aleksej/Orchard,li0803/Orchard,rtpHarry/Orchard,jersiovic/Orchard,jerryshi2007/Orchard,mvarblow/Orchard,xiaobudian/Orchard,fassetar/Orchard,qt1/orchard4ibn,geertdoornbos/Orchard,vard0/orchard.tan,spraiin/Orchard
src/Orchard.Web/Packages/Orchard.Pages/Controllers/PageController.cs
src/Orchard.Web/Packages/Orchard.Pages/Controllers/PageController.cs
using System; using System.Web.Mvc; using Orchard.Localization; using Orchard.ContentManagement; using Orchard.Mvc.Results; using Orchard.Pages.Services; using Orchard.Pages.ViewModels; using Orchard.Security; namespace Orchard.Pages.Controllers { [ValidateInput(false)] public class PageController : Controller { private readonly IPageService _pageService; private readonly ISlugConstraint _slugConstraint; public PageController(IOrchardServices services, IPageService pageService, ISlugConstraint slugConstraint) { Services = services; _pageService = pageService; _slugConstraint = slugConstraint; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } private Localizer T { get; set; } public ActionResult Item(string slug) { if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page"))) return new HttpUnauthorizedResult(); var correctedSlug = _slugConstraint.LookupPublishedSlug(slug); if (correctedSlug == null) return new NotFoundResult(); var page = _pageService.Get(correctedSlug); if (page == null) return new NotFoundResult(); var model = new PageViewModel { Page = Services.ContentManager.BuildDisplayModel(page, "Detail") }; return View(model); } } }
using System; using System.Web.Mvc; using Orchard.Localization; using Orchard.ContentManagement; using Orchard.Pages.Services; using Orchard.Pages.ViewModels; using Orchard.Security; namespace Orchard.Pages.Controllers { [ValidateInput(false)] public class PageController : Controller, IUpdateModel { private readonly IPageService _pageService; private readonly ISlugConstraint _slugConstraint; public PageController( IOrchardServices services, IPageService pageService, ISlugConstraint slugConstraint) { Services = services; _pageService = pageService; _slugConstraint = slugConstraint; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } private Localizer T { get; set; } public ActionResult Item(string slug) { if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page"))) return new HttpUnauthorizedResult(); if (slug == null) { throw new ArgumentNullException("slug"); } //var correctedSlug = _slugConstraint.LookupPublishedSlug(pageSlug); var page = _pageService.Get(slug); var model = new PageViewModel { Page = Services.ContentManager.BuildDisplayModel(page, "Detail") }; return View(model); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
bsd-3-clause
C#
8df122382f1af3b15ab3f926a4a6728b052886c6
Correct Painless script syntax
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Tests/Tests/QueryDsl/Specialized/Script/ScriptQueryUsageTests.cs
src/Tests/Tests/QueryDsl/Specialized/Script/ScriptQueryUsageTests.cs
using System.Collections.Generic; using Nest; using Tests.Core.ManagedElasticsearch.Clusters; using Tests.Domain; using Tests.Framework.Integration; namespace Tests.QueryDsl.Specialized.Script { /** * A query allowing to define {ref_current}/modules-scripting.html[scripts] as queries. * * See the Elasticsearch documentation on {ref_current}/query-dsl-script-query.html[script query] for more details. */ public class ScriptQueryUsageTests : QueryDslUsageTestsBase { private static readonly string _templateString = "doc['numberOfCommits'].value > params.param1"; public ScriptQueryUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override ConditionlessWhen ConditionlessWhen => new ConditionlessWhen<IScriptQuery>(a => a.Script) { q => { q.Script = null; }, q => { q.Script = new InlineScript(null); }, q => { q.Script = new InlineScript(""); }, q => { q.Script = new IndexedScript(null); }, q => { q.Script = new IndexedScript(""); } }; protected override QueryContainer QueryInitializer => new ScriptQuery { Name = "named_query", Boost = 1.1, Script = new InlineScript(_templateString) { Params = new Dictionary<string, object> { { "param1", 50 } } }, }; protected override object QueryJson => new { script = new { _name = "named_query", boost = 1.1, script = new { source = "doc['numberOfCommits'].value > params.param1", @params = new { param1 = 50 } } } }; protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> q) => q .Script(sn => sn .Name("named_query") .Boost(1.1) .Script(s => s .Source(_templateString) .Params(p => p.Add("param1", 50)) ) ); } }
using System.Collections.Generic; using Nest; using Tests.Core.ManagedElasticsearch.Clusters; using Tests.Domain; using Tests.Framework.Integration; namespace Tests.QueryDsl.Specialized.Script { /** * A query allowing to define {ref_current}/modules-scripting.html[scripts] as queries. * * See the Elasticsearch documentation on {ref_current}/query-dsl-script-query.html[script query] for more details. */ public class ScriptQueryUsageTests : QueryDslUsageTestsBase { private static readonly string _templateString = "doc['numberOfCommits'].value > param1"; public ScriptQueryUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override ConditionlessWhen ConditionlessWhen => new ConditionlessWhen<IScriptQuery>(a => a.Script) { q => { q.Script = null; }, q => { q.Script = new InlineScript(null); }, q => { q.Script = new InlineScript(""); }, q => { q.Script = new IndexedScript(null); }, q => { q.Script = new IndexedScript(""); } }; protected override QueryContainer QueryInitializer => new ScriptQuery { Name = "named_query", Boost = 1.1, Script = new InlineScript(_templateString) { Params = new Dictionary<string, object> { { "param1", 50 } } }, }; protected override object QueryJson => new { script = new { _name = "named_query", boost = 1.1, script = new { source = "doc['numberOfCommits'].value > param1", @params = new { param1 = 50 } } } }; protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> q) => q .Script(sn => sn .Name("named_query") .Boost(1.1) .Script(s => s .Source(_templateString) .Params(p => p.Add("param1", 50)) ) ); } }
apache-2.0
C#
e6b449fe0b602a76a7d61efb5bff0a609fb241cd
Fix case of zero rate calculating a zero true gameplay rate
ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
osu.Game/Screens/Play/GameplayClockExtensions.cs
osu.Game/Screens/Play/GameplayClockExtensions.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Screens.Play { public static class GameplayClockExtensions { /// <summary> /// The rate of gameplay when playback is at 100%. /// This excludes any seeking / user adjustments. /// </summary> public static double GetTrueGameplayRate(this IGameplayClock clock) { // To handle rewind, we still want to maintain the same direction as the underlying clock. double rate = clock.Rate == 0 ? 1 : Math.Sign(clock.Rate); return rate * clock.GameplayAdjustments.AggregateFrequency.Value * clock.GameplayAdjustments.AggregateTempo.Value; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; namespace osu.Game.Screens.Play { public static class GameplayClockExtensions { /// <summary> /// The rate of gameplay when playback is at 100%. /// This excludes any seeking / user adjustments. /// </summary> public static double GetTrueGameplayRate(this IGameplayClock clock) { // To handle rewind, we still want to maintain the same direction as the underlying clock. double rate = Math.Sign(clock.Rate); return rate * clock.GameplayAdjustments.AggregateFrequency.Value * clock.GameplayAdjustments.AggregateTempo.Value; } } }
mit
C#
50be0f78824a9cb1e730ccebbfff9ac8758d0051
Update RandomImpl.cs
jp2masa/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos
source/Cosmos.System2_Plugs/System/RandomImpl.cs
source/Cosmos.System2_Plugs/System/RandomImpl.cs
using System; using Cosmos.IL2CPU.API.Attribs; using Cosmos.HAL; namespace Cosmos.System_Plugs.System { //System.Private.CoreLib, Other methods [Plug(TargetName = "System.Random, System.Private.CoreLib")] public class CoreLibRandomImpl { public static void Cctor() {} public static int GenerateGlobalSeed(Random aThis) => 21; } [Plug(Target = typeof(Random))] public class RandomImpl { public static void Ctor(Random aThis) { //empty } public static void Ctor(Random aThis, int seed) { //empty ATM } public static int Next(Random aThis, int maxValue) { return (int)(GetUniform() * maxValue); } public static int Next(Random aThis) { return (int)(GetUniform() * int.MaxValue); } public static int Next(Random aThis, int minValue, int maxValue) { uint diff = (uint)(maxValue - minValue); if (diff <= 1) return minValue; return (int)((uint)(GetUniform() * diff) + minValue); } public static void NextBytes(Random aThis, byte[] buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(GetUniform() * (byte.MaxValue + 1)); } } public static double NextDouble(Random aThis) { return GetUniform(); } static double GetUniform() { uint seed = (uint)RTC.Second; uint m_w = (uint)(seed >> 16); uint m_z = (uint)(seed % 4294967296); m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); uint u = (m_z << 16) + m_w; double uniform = (u + 1.0) * 2.328306435454494e-10; return uniform; } } }
using System; using Cosmos.IL2CPU.API.Attribs; using Cosmos.HAL; namespace Cosmos.System_Plugs.System { [Plug(Target = typeof(Random))] public class RandomImpl { public static void Ctor(Random aThis) { //empty } public static void Ctor(Random aThis, int seed) { //empty ATM } public static int Next(Random aThis, int maxValue) { return (int)(GetUniform() * maxValue); } public static int Next(Random aThis) { return (int)(GetUniform() * int.MaxValue); } public static int Next(Random aThis, int minValue, int maxValue) { uint diff = (uint)(maxValue - minValue); if (diff <= 1) return minValue; return (int)((uint)(GetUniform() * diff) + minValue); } public static void NextBytes(Random aThis, byte[] buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(GetUniform() * (byte.MaxValue + 1)); } } public static double NextDouble(Random aThis) { return GetUniform(); } static double GetUniform() { uint seed = (uint)RTC.Second; uint m_w = (uint)(seed >> 16); uint m_z = (uint)(seed % 4294967296); m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); uint u = (m_z << 16) + m_w; double uniform = (u + 1.0) * 2.328306435454494e-10; return uniform; } } }
bsd-3-clause
C#
9bd2b862d7793c569f6f747ddbd183b9683680a6
Fix sample.
msgpack/msgpack-cli,msgpack/msgpack-cli
samples/Samples/Sample10_ByteArrayBased.cs
samples/Samples/Sample10_ByteArrayBased.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; using MsgPack; using MsgPack.Serialization; using NUnit.Framework; // For running checking namespace Samples { /// <summary> /// A sample code to describe byte array based behavior. /// </summary> [TestFixture] public class Sample10_ByteArrayBased { /// <summary> /// Uses byte array for serialization and deserialization. /// </summary> [Test] public void SimpleBufferCase() { // Assumes that we know maximum serialized data size, so just use it! var buffer = new byte[ 1024 * 64 ]; var context = new SerializationContext(); var serializer = context.GetSerializer<PhotoEntry>(); var obj = new PhotoEntry { Id = 123, Title = "My photo", Date = DateTime.Now, Image = new byte[] { 1, 2, 3, 4 }, Comment = "This is test object to be serialize/deserialize using MsgPack." }; // Note that the packer automatically increse buffer. using ( var bytePacker = Packer.Create( buffer, true, PackerCompatibilityOptions.None ) ) { serializer.PackTo( bytePacker, obj ); // Note: You can get actual bytes with GetResultBytes(), but it causes array copy. // You can avoid copying using original buffer (when you prohibits buffer allocation on Packer.Create) or GetFinalBuffers() instead. Console.WriteLine( "Serialized: {0}", BitConverter.ToString( buffer, 0, ( int )bytePacker.BytesUsed ) ); using ( var byteUnpacker = Unpacker.Create( buffer ) ) { var deserialized = serializer.UnpackFrom( byteUnpacker ); } } } } public class MyArrayBufferManager { public IList<ArraySegment<byte>> Buffers { get; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; using MsgPack; using MsgPack.Serialization; using NUnit.Framework; // For running checking namespace Samples { /// <summary> /// A sample code to describe byte array based behavior. /// </summary> [TestFixture] public class Sample10_ByteArrayBased { /// <summary> /// Uses byte array for serialization and deserialization. /// </summary> [Test] public void SimpleBufferCase() { // Assumes that we know maximum serialized data size, so just use it! var buffer = new byte[ 1024 * 64 ]; var context = new SerializationContext(); var serializer = context.GetSerializer<PhotoEntry>(); var obj = new PhotoEntry { Id = 123, Title = "My photo", Date = DateTime.Now, Image = new byte[] { 1, 2, 3, 4 }, Comment = "This is test object to be serialize/deserialize using MsgPack." }; // Note that the packer automatically increse buffer. using ( var bytePacker = Packer.Create( buffer ) ) { serializer.PackTo( bytePacker, obj ); // Note: You can get actual bytes with GetResultBytes(), but it causes array copy. // You can avoid copying using original buffer (when you prohibits buffer allocation on Packer.Create) or GetFinalBuffers() instead. Console.WriteLine( "Serialized: {0}", BitConverter.ToString( buffer, 0, ( int )bytePacker.BytesUsed ) ); using ( var byteUnpacker = Unpacker.Create( buffer ) ) { var deserialized = serializer.UnpackFrom( byteUnpacker ); } } } } public class MyArrayBufferManager { public IList<ArraySegment<byte>> Buffers { get; } } }
apache-2.0
C#
75a89076c285f59d74e8dc0e7dbce534564a989b
Set metadata
masaedw/LineSharp
LineSharp/Properties/AssemblyInfo.cs
LineSharp/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("LineSharp")] [assembly: AssemblyDescription("A LINE Messaging API binding library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Masayuki Muto")] [assembly: AssemblyProduct("LineSharp")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("0a2c415b-a00f-4e04-83a2-2b1bbe72b73d")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("LineSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LineSharp")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("0a2c415b-a00f-4e04-83a2-2b1bbe72b73d")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
f451a24cba190c3e302c285f57e02a0503a594ab
Allow to use input event arguments in the event handlers
k-t/SharpHaven
MonoHaven.Client/Input/InputEvent.cs
MonoHaven.Client/Input/InputEvent.cs
using System; using OpenTK.Input; namespace MonoHaven.Input { public abstract class InputEvent : EventArgs { private readonly KeyModifiers mods; protected InputEvent() { mods = GetCurrentKeyModifiers(); } public bool Handled { get; set; } public KeyModifiers Modifiers { get { return mods; } } private static KeyModifiers GetCurrentKeyModifiers() { var mods = (KeyModifiers)0; var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Key.LShift) || keyboardState.IsKeyDown(Key.RShift)) mods |= KeyModifiers.Shift; if (keyboardState.IsKeyDown(Key.LAlt) || keyboardState.IsKeyDown(Key.RAlt)) mods |= KeyModifiers.Alt; if (keyboardState.IsKeyDown(Key.ControlLeft) || keyboardState.IsKeyDown(Key.ControlRight)) mods |= KeyModifiers.Control; return mods; } } }
using OpenTK.Input; namespace MonoHaven.Input { public abstract class InputEvent { private readonly KeyModifiers mods; protected InputEvent() { mods = GetCurrentKeyModifiers(); } public bool Handled { get; set; } public KeyModifiers Modifiers { get { return mods; } } private static KeyModifiers GetCurrentKeyModifiers() { var mods = (KeyModifiers)0; var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Key.LShift) || keyboardState.IsKeyDown(Key.RShift)) mods |= KeyModifiers.Shift; if (keyboardState.IsKeyDown(Key.LAlt) || keyboardState.IsKeyDown(Key.RAlt)) mods |= KeyModifiers.Alt; if (keyboardState.IsKeyDown(Key.ControlLeft) || keyboardState.IsKeyDown(Key.ControlRight)) mods |= KeyModifiers.Control; return mods; } } }
mit
C#
05101f0e0e1c2198fe323ab7967a5b673853db48
Improve exception handling of AsyncLock.
chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet
Source/MQTTnet/Internal/AsyncLock.cs
Source/MQTTnet/Internal/AsyncLock.cs
using System; using System.Threading; using System.Threading.Tasks; namespace MQTTnet.Internal { // From Stephen Toub (https://blogs.msdn.microsoft.com/pfxteam/2012/02/12/building-async-coordination-primitives-part-6-asynclock/) public sealed class AsyncLock : IDisposable { readonly object _syncRoot = new object(); readonly Task<IDisposable> _releaser; SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); public AsyncLock() { _releaser = Task.FromResult((IDisposable)new Releaser(this)); } public Task<IDisposable> WaitAsync() { return WaitAsync(CancellationToken.None); } public Task<IDisposable> WaitAsync(CancellationToken cancellationToken) { var task = _semaphore.WaitAsync(cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return _releaser; } return task.ContinueWith( (_, state) => (IDisposable)state, _releaser.Result, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } public void Dispose() { lock (_syncRoot) { _semaphore?.Dispose(); _semaphore = null; } } internal void Release() { lock (_syncRoot) { _semaphore?.Release(); } } sealed class Releaser : IDisposable { readonly AsyncLock _lock; internal Releaser(AsyncLock @lock) { _lock = @lock; } public void Dispose() { _lock.Release(); } } } }
using System; using System.Threading; using System.Threading.Tasks; namespace MQTTnet.Internal { // From Stephen Toub (https://blogs.msdn.microsoft.com/pfxteam/2012/02/12/building-async-coordination-primitives-part-6-asynclock/) public sealed class AsyncLock : IDisposable { readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); readonly Task<IDisposable> _releaser; public AsyncLock() { _releaser = Task.FromResult((IDisposable)new Releaser(this)); } public Task<IDisposable> WaitAsync() { return WaitAsync(CancellationToken.None); } public Task<IDisposable> WaitAsync(CancellationToken cancellationToken) { var task = _semaphore.WaitAsync(cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return _releaser; } return task.ContinueWith( (_, state) => (IDisposable)state, _releaser.Result, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } public void Dispose() { _semaphore?.Dispose(); } class Releaser : IDisposable { readonly AsyncLock _toRelease; internal Releaser(AsyncLock toRelease) { _toRelease = toRelease; } public void Dispose() { _toRelease._semaphore.Release(); } } } }
mit
C#
ae4c3ce08fb5672238ba392b0a84e6a2a4e43ff7
bump to latest version
bholmes/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents
Android/AndroidThings/build.cake
Android/AndroidThings/build.cake
#addin nuget:?package=Cake.Xamarin.Build #addin nuget:?package=Cake.Xamarin var TARGET = Argument ("t", Argument ("target", "Default")); var NUGET_VERSION = "0.6.1-devpreview"; var JAR_VERSION = "0.6.1-devpreview"; var JAR_URL = string.Format ("https://bintray.com/google/androidthings/download_file?file_path=com%2Fgoogle%2Fandroid%2Fthings%2Fandroidthings%2F{0}%2Fandroidthings-{0}.jar", JAR_VERSION); var DOCS_URL = string.Format ("https://bintray.com/google/androidthings/download_file?file_path=com%2Fgoogle%2Fandroid%2Fthings%2Fandroidthings%2F{0}%2Fandroidthings-{0}-javadoc.jar", JAR_VERSION); var JAR_DEST = "./externals/androidthings.jar"; var buildSpec = new BuildSpec () { Libs = new [] { new DefaultSolutionBuilder { SolutionPath = "./Android.Things.sln", OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/bin/Release/Xamarin.Android.Things.dll", } } } }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.Android.Things.nuspec", Version = NUGET_VERSION }, }, }; Task ("externals") .Does (() => { if (!DirectoryExists ("./externals/")) CreateDirectory ("./externals"); if (!FileExists (JAR_DEST)) DownloadFile (JAR_URL, JAR_DEST); if (!FileExists ("./externals/docs.zip")) { DownloadFile (DOCS_URL, "./externals/docs.zip"); Unzip ("./externals/docs.zip", "./externals/docs"); } }); Task ("clean").IsDependentOn ("clean-base").Does (() => { if (DirectoryExists ("./externals")) DeleteDirectory ("./externals", true); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
#addin nuget:?package=Cake.Xamarin.Build #addin nuget:?package=Cake.Xamarin var TARGET = Argument ("t", Argument ("target", "Default")); var NUGET_VERSION = "0.6-devpreview"; var JAR_VERSION = "0.6-devpreview"; var JAR_URL = string.Format ("https://bintray.com/google/androidthings/download_file?file_path=com%2Fgoogle%2Fandroid%2Fthings%2Fandroidthings%2F{0}%2Fandroidthings-{0}.jar", JAR_VERSION); var DOCS_URL = string.Format ("https://bintray.com/google/androidthings/download_file?file_path=com%2Fgoogle%2Fandroid%2Fthings%2Fandroidthings%2F{0}%2Fandroidthings-{0}-javadoc.jar", JAR_VERSION); var JAR_DEST = "./externals/androidthings.jar"; var buildSpec = new BuildSpec () { Libs = new [] { new DefaultSolutionBuilder { SolutionPath = "./Android.Things.sln", OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/bin/Release/Xamarin.Android.Things.dll", } } } }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.Android.Things.nuspec", Version = NUGET_VERSION }, }, }; Task ("externals") .Does (() => { if (!DirectoryExists ("./externals/")) CreateDirectory ("./externals"); if (!FileExists (JAR_DEST)) DownloadFile (JAR_URL, JAR_DEST); if (!FileExists ("./externals/docs.zip")) { DownloadFile (DOCS_URL, "./externals/docs.zip"); Unzip ("./externals/docs.zip", "./externals/docs"); } }); Task ("clean").IsDependentOn ("clean-base").Does (() => { if (DirectoryExists ("./externals")) DeleteDirectory ("./externals", true); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
mit
C#
e1e6365ddd15f0c6561872ff4c069938df76b244
Add Thread name to TaskUtil.Start
jwollen/SharpDX,davidlee80/SharpDX-1,sharpdx/SharpDX,TechPriest/SharpDX,TigerKO/SharpDX,dazerdude/SharpDX,shoelzer/SharpDX,TechPriest/SharpDX,weltkante/SharpDX,manu-silicon/SharpDX,waltdestler/SharpDX,shoelzer/SharpDX,Ixonos-USA/SharpDX,andrewst/SharpDX,Ixonos-USA/SharpDX,fmarrabal/SharpDX,mrvux/SharpDX,fmarrabal/SharpDX,VirusFree/SharpDX,wyrover/SharpDX,RobyDX/SharpDX,dazerdude/SharpDX,jwollen/SharpDX,andrewst/SharpDX,jwollen/SharpDX,andrewst/SharpDX,wyrover/SharpDX,TigerKO/SharpDX,jwollen/SharpDX,TigerKO/SharpDX,waltdestler/SharpDX,davidlee80/SharpDX-1,PavelBrokhman/SharpDX,TigerKO/SharpDX,wyrover/SharpDX,fmarrabal/SharpDX,PavelBrokhman/SharpDX,sharpdx/SharpDX,RobyDX/SharpDX,weltkante/SharpDX,manu-silicon/SharpDX,VirusFree/SharpDX,TechPriest/SharpDX,davidlee80/SharpDX-1,VirusFree/SharpDX,Ixonos-USA/SharpDX,davidlee80/SharpDX-1,fmarrabal/SharpDX,waltdestler/SharpDX,mrvux/SharpDX,TechPriest/SharpDX,weltkante/SharpDX,dazerdude/SharpDX,PavelBrokhman/SharpDX,mrvux/SharpDX,shoelzer/SharpDX,Ixonos-USA/SharpDX,RobyDX/SharpDX,waltdestler/SharpDX,VirusFree/SharpDX,shoelzer/SharpDX,manu-silicon/SharpDX,PavelBrokhman/SharpDX,RobyDX/SharpDX,weltkante/SharpDX,manu-silicon/SharpDX,wyrover/SharpDX,shoelzer/SharpDX,dazerdude/SharpDX,sharpdx/SharpDX
Source/SharpDX/Threading/TaskUtil.cs
Source/SharpDX/Threading/TaskUtil.cs
// Copyright (c) 2010-2013 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.Threading; namespace SharpDX.Threading { /// <summary> /// Task utility for threading. /// </summary> public class TaskUtil { /// <summary> /// Runs the specified action in a thread. /// </summary> /// <param name="action">The action.</param> /// <param name="taskName">Name of the task.</param> public static void Run(VoidAction action, string taskName = "SharpDXTask") { #if W8CORE System.Threading.Tasks.Task.Factory.StartNew(() => action(), System.Threading.Tasks.TaskCreationOptions.LongRunning); #else var thread = new System.Threading.Thread(() => action()) { IsBackground = true, Name = taskName }; thread.Start(); #endif } } }
// Copyright (c) 2010-2013 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.Threading; namespace SharpDX.Threading { /// <summary> /// Task utility for threading. /// </summary> public class TaskUtil { /// <summary> /// Runs the specified action in a thread. /// </summary> /// <param name="action">The action.</param> public static void Run(VoidAction action) { #if W8CORE System.Threading.Tasks.Task.Factory.StartNew(() => action(), System.Threading.Tasks.TaskCreationOptions.LongRunning); #else var thread = new System.Threading.Thread(() => action()) { IsBackground = true }; thread.Start(); #endif } } }
mit
C#
34df4be5d9788f35943fd3b63032a9742c617717
Update EnumUtils.GetDescription to better format string representation of enum value #43
Saritasa/SaritasaTools,krasninja/SaritasaTools,krasninja/SaritasaTools
src/Saritasa.Tools.Common/Utils/EnumUtils.cs
src/Saritasa.Tools.Common/Utils/EnumUtils.cs
// Copyright (c) 2015-2017, Saritasa. All rights reserved. // Licensed under the BSD license. See LICENSE file in the project root for full license information. using System; #if NET40 || NET452 || NET461 using System.Collections.Generic; using System.ComponentModel; using System.Text.RegularExpressions; #endif using System.Linq; using System.Reflection; namespace Saritasa.Tools.Common.Utils { /// <summary> /// Enum utils. /// </summary> public static class EnumUtils { #if NET40 || NET452 || NET461 /// <summary> /// Gets a description of enum value. If <see cref="DescriptionAttribute"/> is specified for it, its value will be returned. /// </summary> /// <param name="target">Enum value.</param> /// <returns>Description of the value.</returns> public static string GetDescription(Enum target) { var descAttribute = GetAttribute<DescriptionAttribute>(target); if (descAttribute != null) { return descAttribute.Description; } var value = target.ToString(); // Split the value with spaces if it is intercapped. return Regex.Replace(value, @"((?<=[a-z])([A-Z])|(?<=[A-Z])([A-Z][a-z]))", " $1", RegexOptions.Compiled); } #endif /// <summary> /// Gets the custom attribute of enum value. /// </summary> /// <param name="target">Enum.</param> /// <typeparam name="TAttribute">Attribute type.</typeparam> /// <returns>Attribute or null if not found.</returns> public static TAttribute GetAttribute<TAttribute>(Enum target) where TAttribute : Attribute { #if NET40 || NET452 || NET461 if (!target.GetType().IsEnum) { throw new ArgumentOutOfRangeException(nameof(target), Properties.Strings.ArgumentMustBeEnum); } #endif #if NET40 || NET452 || NET461 FieldInfo fieldInfo = target.GetType().GetField(target.ToString()); #else FieldInfo fieldInfo = target.GetType().GetTypeInfo().GetDeclaredField(target.ToString()); #endif if (fieldInfo == null) { return null; } #if NETSTANDARD1_2 var attributes = fieldInfo.GetCustomAttributes<TAttribute>(false); #else var attributes = (IEnumerable<TAttribute>)fieldInfo.GetCustomAttributes(typeof(TAttribute), false); #endif return attributes.FirstOrDefault(); } } }
// Copyright (c) 2015-2017, Saritasa. All rights reserved. // Licensed under the BSD license. See LICENSE file in the project root for full license information. using System; #if NET40 || NET452 || NET461 using System.Collections.Generic; using System.ComponentModel; #endif using System.Linq; using System.Reflection; namespace Saritasa.Tools.Common.Utils { /// <summary> /// Enum utils. /// </summary> public static class EnumUtils { #if NET40 || NET452 || NET461 /// <summary> /// Gets the value of Description attribute. /// </summary> /// <param name="target">Enum.</param> /// <returns>Description text.</returns> public static string GetDescription(Enum target) { var descAttribute = GetAttribute<DescriptionAttribute>(target); if (descAttribute == null) { return target.ToString(); } return descAttribute.Description; } #endif /// <summary> /// Gets the custom attribute of enum value. /// </summary> /// <param name="target">Enum.</param> /// <typeparam name="TAttribute">Attribute type.</typeparam> /// <returns>Attribute or null if not found.</returns> public static TAttribute GetAttribute<TAttribute>(Enum target) where TAttribute : Attribute { #if NET40 || NET452 || NET461 if (!target.GetType().IsEnum) { throw new ArgumentOutOfRangeException(nameof(target), Properties.Strings.ArgumentMustBeEnum); } #endif #if NET40 || NET452 || NET461 FieldInfo fieldInfo = target.GetType().GetField(target.ToString()); #else FieldInfo fieldInfo = target.GetType().GetTypeInfo().GetDeclaredField(target.ToString()); #endif if (fieldInfo == null) { return null; } #if NETSTANDARD1_2 var attributes = fieldInfo.GetCustomAttributes<TAttribute>(false); #else var attributes = (IEnumerable<TAttribute>)fieldInfo.GetCustomAttributes(typeof(TAttribute), false); #endif return attributes.FirstOrDefault(); } } }
bsd-2-clause
C#
8dc52e57628e96385897a683e185f7562cf095c9
Modify MusicNote to be immutable
MattJamesChampion/FretEngine
FretEngine/MusicLogic/MusicNote.cs
FretEngine/MusicLogic/MusicNote.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FretEngine.Common.DataTypes; namespace FretEngine.MusicLogic { public class MusicNote { public readonly AbstractMusicNote Value; public readonly int Octave; public MusicNote(AbstractMusicNote value, int octave = 4) { Value = value; Octave = octave; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FretEngine.Common.DataTypes; namespace FretEngine.MusicLogic { public class MusicNote { public AbstractMusicNote Value; public int Octave; public MusicNote(AbstractMusicNote value, int octave = 4) { Value = value; Octave = octave; } } }
mit
C#
fc4a7d4febdfa5a79a3f4ad48e48ed0d73ab730e
Remove unused field.
qed-/BosunReporter.NET,lockwobr/BosunReporter.NET,bretcope/BosunReporter.NET
BosunReporter/BosunCounter.cs
BosunReporter/BosunCounter.cs
using System.Collections.Generic; using System.Threading; namespace BosunReporter { public abstract class BosunCounter : BosunMetric { public long Value; public override string MetricType { get { return "counter"; } } protected override IEnumerable<string> GetSerializedMetrics(string unixTimestamp) { yield return ToJson("", Value.ToString("D"), unixTimestamp); } protected BosunCounter(long value = 0) { Value = value; } public void Increment(long amount = 1) { Interlocked.Add(ref Value, amount); } } }
using System.Collections.Generic; using System.Threading; namespace BosunReporter { public abstract class BosunCounter : BosunMetric { public long Value; private readonly object _tagsLock = new object(); public override string MetricType { get { return "counter"; } } protected override IEnumerable<string> GetSerializedMetrics(string unixTimestamp) { yield return ToJson("", Value.ToString("D"), unixTimestamp); } protected BosunCounter(long value = 0) { Value = value; } public void Increment(long amount = 1) { Interlocked.Add(ref Value, amount); } } }
mit
C#
cafffde339fce3f4442102daebd8caed6e82339b
Change test application initialization procedure. It essentially the same as before, but MVC test tooling expect Program to have CreateWebHostBuilder. I referer to ability to seamlessly use WebApplicationFactory I understand that story for testing Electron application will be not easy as it is, but this is allow better defaults for testing web applications which can be run in hybrid mode.
ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET
ElectronNET.WebApp/Program.cs
ElectronNET.WebApp/Program.cs
using ElectronNET.API; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace ElectronNET.WebApp { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseElectron(args) .UseStartup<Startup>(); } } }
using ElectronNET.API; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace ElectronNET.WebApp { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseElectron(args) .UseStartup<Startup>() .Build(); } } }
mit
C#
a0fb75522ba8443bc73d48af977578cd27c7698b
Add FirstSeen to the ToString for the Email class
maxmind/minfraud-api-dotnet
MaxMind.MinFraud/Response/Email.cs
MaxMind.MinFraud/Response/Email.cs
using MaxMind.MinFraud.Util; using Newtonsoft.Json; using System; namespace MaxMind.MinFraud.Response { /// <summary> /// This object contains information about the email address passed in the request. /// </summary> public sealed class Email { /// <summary> /// The date the email address was first seen by MaxMind. /// </summary> [JsonProperty("first_seen")] [JsonConverter(typeof(DateConverter))] public DateTimeOffset? FirstSeen { get; internal set; } /// <summary> /// This property incidates whether the email is from a disposable /// email provider. The value will be <c>null</c> if no email address /// or email domain was passed as an input. /// </summary> [JsonProperty("is_disposable")] public bool? IsDisposable { get; internal set; } /// <summary> /// This property is true if MaxMind believes that this email is hosted by a free /// email provider such as Gmail or Yahoo! Mail. /// </summary> [JsonProperty("is_free")] public bool? IsFree { get; internal set; } /// <summary> /// This property is true if MaxMind believes that this email is likely to be used /// for fraud. Note that this is also factored into the overall risk_score in the /// response as well. /// </summary> [JsonProperty("is_high_risk")] public bool? IsHighRisk { get; internal set; } /// <summary> /// Returns a string that represents the current object. /// </summary> public override string ToString() { return $"FirstSeen: {FirstSeen}, IsDisposable: {IsDisposable}, IsFree: {IsFree}, IsHighRiskFree: {IsHighRisk}"; } } }
using MaxMind.MinFraud.Util; using Newtonsoft.Json; using System; namespace MaxMind.MinFraud.Response { /// <summary> /// This object contains information about the email address passed in the request. /// </summary> public sealed class Email { /// <summary> /// The date the email address was first seen by MaxMind. /// </summary> [JsonProperty("first_seen")] [JsonConverter(typeof(DateConverter))] public DateTimeOffset? FirstSeen { get; internal set; } /// <summary> /// This property incidates whether the email is from a disposable /// email provider. The value will be <c>null</c> if no email address /// or email domain was passed as an input. /// </summary> [JsonProperty("is_disposable")] public bool? IsDisposable { get; internal set; } /// <summary> /// This property is true if MaxMind believes that this email is hosted by a free /// email provider such as Gmail or Yahoo! Mail. /// </summary> [JsonProperty("is_free")] public bool? IsFree { get; internal set; } /// <summary> /// This property is true if MaxMind believes that this email is likely to be used /// for fraud. Note that this is also factored into the overall risk_score in the /// response as well. /// </summary> [JsonProperty("is_high_risk")] public bool? IsHighRisk { get; internal set; } /// <summary> /// Returns a string that represents the current object. /// </summary> public override string ToString() { return $"IsDisposable: {IsDisposable}, IsFree: {IsFree}, IsHighRiskFree: {IsHighRisk}"; } } }
apache-2.0
C#
5cca9bb8c5ac810d16d188648a36de5d2d5d2bad
Fix ElementInfo Null Reference Exception
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder
Pathfinder/Util/XML/ElementInfo.cs
Pathfinder/Util/XML/ElementInfo.cs
using System; using System.Collections.Generic; using System.Xml; namespace Pathfinder.Util.XML { public class ElementInfo : IEquatable<ElementInfo> { public ElementInfo Parent { get; internal set; } public string Name { get; internal set; } public string Value { get; internal set; } public int Depth { get; internal set; } public IDictionary<string, string> Attributes { get; internal set; } public List<ElementInfo> Children { get; internal set; } internal int LocalNodeId { get; set; } public override bool Equals(object obj) => obj is ElementInfo ei && Equals(ei); public bool Equals(ElementInfo other) => Name == other?.Name && Value == other?.Value && Depth == other?.Depth && Parent.LocalNodeId == other?.Parent?.LocalNodeId && LocalNodeId == other?.LocalNodeId; public bool RepresentsNode(XmlReader reader) => (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.EndElement) && Name == reader.Name && (reader.NodeType == XmlNodeType.EndElement && Depth == reader.Depth) || (reader.NodeType == XmlNodeType.Element && Depth == reader.Depth && Attributes.Count == reader.AttributeCount); public override int GetHashCode() { var hashCode = 1922712106; hashCode = hashCode * -1521134295 + Parent.LocalNodeId.GetHashCode(); hashCode = hashCode * -1521134295 + LocalNodeId.GetHashCode(); hashCode = hashCode * -1521134295 + Depth.GetHashCode(); hashCode = hashCode * -1521134295 + Name.GetHashCode(); hashCode = hashCode * -1521134295 + Value.GetHashCode(); return hashCode; } internal void ConcatValue(string value) => Value += value; public static bool operator ==(ElementInfo lhs, ElementInfo rhs) => (lhs != null ? lhs.Equals(rhs) : (rhs == null)); public static bool operator !=(ElementInfo lhs, ElementInfo rhs) => !(lhs == rhs); } }
using System; using System.Collections.Generic; using System.Xml; namespace Pathfinder.Util.XML { public class ElementInfo : IEquatable<ElementInfo> { public ElementInfo Parent { get; internal set; } public string Name { get; internal set; } public string Value { get; internal set; } public int Depth { get; internal set; } public IDictionary<string, string> Attributes { get; internal set; } public List<ElementInfo> Children { get; internal set; } internal int LocalNodeId { get; set; } public override bool Equals(object obj) => obj is ElementInfo ei && Equals(ei); public bool Equals(ElementInfo other) => Name == other.Name && Value == other.Value && Depth == other.Depth && Parent.LocalNodeId == other.Parent.LocalNodeId && LocalNodeId == other.LocalNodeId; public bool RepresentsNode(XmlReader reader) => (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.EndElement) && Name == reader.Name && (reader.NodeType == XmlNodeType.EndElement && Depth == reader.Depth) || (reader.NodeType == XmlNodeType.Element && Depth == reader.Depth && Attributes.Count == reader.AttributeCount); public override int GetHashCode() { var hashCode = 1922712106; hashCode = hashCode * -1521134295 + Parent.LocalNodeId.GetHashCode(); hashCode = hashCode * -1521134295 + LocalNodeId.GetHashCode(); hashCode = hashCode * -1521134295 + Depth.GetHashCode(); hashCode = hashCode * -1521134295 + Name.GetHashCode(); hashCode = hashCode * -1521134295 + Value.GetHashCode(); return hashCode; } internal void ConcatValue(string value) => Value += value; public static bool operator ==(ElementInfo lhs, ElementInfo rhs) => lhs.Equals(rhs); public static bool operator !=(ElementInfo lhs, ElementInfo rhs) => !(lhs == rhs); } }
mit
C#
9995bd0a1ef3ecedb214f05d3945ebe28fdae431
fix tests
jjnguy/LRU.Net
LRU.Net/LRU.Net.Tests/UnitTest1.cs
LRU.Net/LRU.Net.Tests/UnitTest1.cs
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LRU.Net.Tests { [TestClass] public class UnitTest1 { private static LruCache<string, string> GetInitializedCache(int max, params string[] entries) { var cache = new LruCache<string, string>(max); foreach (var entry in entries) { cache.Add(entry, entry); } return cache; } [TestMethod] public void TestMethod1() { var cache = GetInitializedCache(3, "one", "two", "tee", "for"); ExceptionAssert.Throws(()=> cache.Get("one")); } [TestMethod] public void TestMethod2() { var cache = GetInitializedCache(3, "one", "two", "tee"); var one = cache.Get("one"); cache.Add("for", "for"); ExceptionAssert.Throws(()=> cache.Get("two")); } [TestMethod] public void StressTestMethod() { var numberOfEntires = 100000; var entries = Enumerable.Range(0, numberOfEntires).Select(i => i.ToString()).ToArray(); var cache = GetInitializedCache(numberOfEntires / 10, entries); Assert.IsFalse(cache.Contains("1")); } } public static class ExceptionAssert { public static void Throws(Action code) { try { code(); Assert.Fail("Should have thrown an exception"); } catch (Exception e) { // yay! } } } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LRU.Net.Tests { [TestClass] public class UnitTest1 { private static LruCache<string, string> GetInitializedCache(int max, params string[] entries) { var cache = new LruCache<string, string>(max); foreach (var entry in entries) { cache.Add(entry, entry); } return cache; } [TestMethod] public void TestMethod1() { var cache = GetInitializedCache(3, "one", "two", "tee", "for"); Assert.IsNull(cache.Get("one")); } [TestMethod] public void TestMethod2() { var cache = GetInitializedCache(3, "one", "two", "tee"); var one = cache.Get("one"); cache.Add("for", "for"); Assert.IsNull(cache.Get("two")); } [TestMethod] public void StressTestMethod() { var numberOfEntires = 1000000; var entries = Enumerable.Range(0, numberOfEntires).Select(i => i.ToString()).ToArray(); var cache = GetInitializedCache(numberOfEntires / 10, entries); Assert.IsFalse(cache.Contains("1")); } } }
mit
C#
6fe5711165071858e9a173c93021556a28d33d53
Make t
dirkrombauts/SpecLogLogoReplacer
UI/ViewModel/SpecLogTransformer.cs
UI/ViewModel/SpecLogTransformer.cs
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO.Abstractions; namespace SpecLogLogoReplacer.UI.ViewModel { public class SpecLogTransformer : ISpecLogTransformer { private readonly IFileSystem fileSystem; public SpecLogTransformer() : this (new FileSystem()) { } public SpecLogTransformer(IFileSystem fileSystem) { this.fileSystem = fileSystem; } public void Transform(string pathToSpecLogFile, string pathToLogo) { if (pathToSpecLogFile == null) { throw new ArgumentNullException("pathToSpecLogFile"); } var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile); Image newLogo; using (var stream = this.fileSystem.File.OpenRead(pathToLogo)) { newLogo = Image.FromStream(stream); } var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo, ImageFormat.Png); this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile); } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO.Abstractions; namespace SpecLogLogoReplacer.UI.ViewModel { public class SpecLogTransformer : ISpecLogTransformer { private readonly IFileSystem fileSystem; public SpecLogTransformer() : this (new FileSystem()) { } public SpecLogTransformer(IFileSystem fileSystem) { this.fileSystem = fileSystem; } public void Transform(string pathToSpecLogFile, string pathToLogo) { var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile); Image newLogo; using (var stream = this.fileSystem.File.OpenRead(pathToLogo)) { newLogo = Image.FromStream(stream); } var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo, ImageFormat.Png); this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile); } } }
isc
C#
4f60ccd60efa201e1f9724f1bbb3e75a25a7267d
Add Rotate/Translate extension methods to IVertexSource
jlewin/agg-sharp,larsbrubaker/agg-sharp,MatterHackers/agg-sharp
agg/VertexSource/ApplyTransform.cs
agg/VertexSource/ApplyTransform.cs
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using MatterHackers.VectorMath; using System.Collections.Generic; using MatterHackers.Agg.Transform; using MatterHackers.VectorMath; namespace MatterHackers.Agg.VertexSource { public enum AngleType { Degrees, Radians } public static class ExtensionMethods { public static IVertexSource Rotate(this IVertexSource source, double angle, AngleType angleType = AngleType.Radians) { if (angleType == AngleType.Degrees) { angle = MathHelper.DegreesToRadians(angle); } return new VertexSourceApplyTransform(source, Affine.NewRotation(angle)); } public static IVertexSource Translate(this IVertexSource source, Vector2 vector2) { return source.Translate(vector2.x, vector2.y); } public static IVertexSource Translate(this IVertexSource source, double x, double y) { return new VertexSourceApplyTransform(source, Affine.NewTranslation(x, y)); } } // in the original agg this was conv_transform public class VertexSourceApplyTransform : IVertexSourceProxy { private Transform.ITransform transformToApply; public IVertexSource VertexSource { get; set; } public VertexSourceApplyTransform(Transform.ITransform newTransformeToApply) : this(null, newTransformeToApply) { } public VertexSourceApplyTransform(IVertexSource vertexSource, Transform.ITransform newTransformeToApply) { VertexSource = vertexSource; transformToApply = newTransformeToApply; } public void attach(IVertexSource vertexSource) { VertexSource = vertexSource; } public IEnumerable<VertexData> Vertices() { foreach (VertexData vertexData in VertexSource.Vertices()) { VertexData transformedVertex = vertexData; if (ShapePath.is_vertex(transformedVertex.command)) { transformToApply.transform(ref transformedVertex.position.x, ref transformedVertex.position.y); } yield return transformedVertex; } } public void rewind(int path_id) { VertexSource.rewind(path_id); } public ShapePath.FlagsAndCommand vertex(out double x, out double y) { ShapePath.FlagsAndCommand cmd = VertexSource.vertex(out x, out y); if (ShapePath.is_vertex(cmd)) { transformToApply.transform(ref x, ref y); } return cmd; } public void SetTransformToApply(Transform.ITransform newTransformeToApply) { transformToApply = newTransformeToApply; } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System.Collections.Generic; namespace MatterHackers.Agg.VertexSource { // in the original agg this was conv_transform public class VertexSourceApplyTransform : IVertexSourceProxy { private Transform.ITransform transformToApply; public IVertexSource VertexSource { get; set; } public VertexSourceApplyTransform(Transform.ITransform newTransformeToApply) : this(null, newTransformeToApply) { } public VertexSourceApplyTransform(IVertexSource vertexSource, Transform.ITransform newTransformeToApply) { VertexSource = vertexSource; transformToApply = newTransformeToApply; } public void attach(IVertexSource vertexSource) { VertexSource = vertexSource; } public IEnumerable<VertexData> Vertices() { foreach (VertexData vertexData in VertexSource.Vertices()) { VertexData transformedVertex = vertexData; if (ShapePath.is_vertex(transformedVertex.command)) { transformToApply.transform(ref transformedVertex.position.x, ref transformedVertex.position.y); } yield return transformedVertex; } } public void rewind(int path_id) { VertexSource.rewind(path_id); } public ShapePath.FlagsAndCommand vertex(out double x, out double y) { ShapePath.FlagsAndCommand cmd = VertexSource.vertex(out x, out y); if (ShapePath.is_vertex(cmd)) { transformToApply.transform(ref x, ref y); } return cmd; } public void SetTransformToApply(Transform.ITransform newTransformeToApply) { transformToApply = newTransformeToApply; } } }
bsd-2-clause
C#
75bbe017562b7e216c7e2e58f7a347161706371d
Fix float parsing in VolumeMessage.
Sharparam/Foobar2kLib
Sharparam.Foobar2kLib/Messages/VolumeMessage.cs
Sharparam.Foobar2kLib/Messages/VolumeMessage.cs
// <copyright file="VolumeMessage.cs" company="Adam Hellberg"> // Copyright © 2013 by Adam Hellberg. // // 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. // </copyright> using System.Globalization; using Sharparam.Foobar2kLib.Networking; namespace Sharparam.Foobar2kLib.Messages { public class VolumeMessage : Message { public readonly float Value; internal VolumeMessage(string content) : base(MessageType.Volume, content) { Value = float.Parse(content, CultureInfo.InvariantCulture); } } }
// <copyright file="VolumeMessage.cs" company="Adam Hellberg"> // Copyright © 2013 by Adam Hellberg. // // 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. // </copyright> using Sharparam.Foobar2kLib.Networking; namespace Sharparam.Foobar2kLib.Messages { public class VolumeMessage : Message { public readonly float Value; internal VolumeMessage(string content) : base(MessageType.Volume, content) { Value = float.Parse(content); } } }
mit
C#
a56bb9f2e9cefc0b518346b60371e8e49232a7e1
Add missing authorization scopes read_analytics, read_users and write_users
addsb/ShopifySharp,clement911/ShopifySharp,nozzlegear/ShopifySharp,Yitzchok/ShopifySharp
ShopifySharp/Enums/ShopifyAuthorizationScope.cs
ShopifySharp/Enums/ShopifyAuthorizationScope.cs
using Newtonsoft.Json; using ShopifySharp.Converters; using System.Runtime.Serialization; namespace ShopifySharp.Enums { [JsonConverter(typeof(NullableEnumConverter<ShopifyAuthorizationScope>))] public enum ShopifyAuthorizationScope { [EnumMember(Value = "read_content")] ReadContent, [EnumMember(Value = "write_content")] WriteContent, [EnumMember(Value = "read_themes")] ReadThemes, [EnumMember(Value = "write_themes")] WriteThemes, [EnumMember(Value = "read_products")] ReadProducts, [EnumMember(Value = "write_products")] WriteProducts, [EnumMember(Value = "read_customers")] ReadCustomers, [EnumMember(Value = "write_customers")] WriteCustomers, [EnumMember(Value = "read_orders")] ReadOrders, [EnumMember(Value = "write_orders")] WriteOrders, [EnumMember(Value = "read_script_tags")] ReadScriptTags, [EnumMember(Value = "write_script_tags")] WriteScriptTags, [EnumMember(Value = "read_fulfillments")] ReadFulfillments, [EnumMember(Value = "write_fulfillments")] WriteFulfillments, [EnumMember(Value = "read_shipping")] ReadShipping, [EnumMember(Value = "write_shipping")] WriteShipping, [EnumMember(Value = "read_analytics")] ReadAnalytics, [EnumMember(Value = "read_users")] ReadUsers, [EnumMember(Value = "write_users")] WriteUsers } }
using Newtonsoft.Json; using ShopifySharp.Converters; using System.Runtime.Serialization; namespace ShopifySharp.Enums { [JsonConverter(typeof(NullableEnumConverter<ShopifyAuthorizationScope>))] public enum ShopifyAuthorizationScope { [EnumMember(Value = "read_content")] ReadContent, [EnumMember(Value = "write_content")] WriteContent, [EnumMember(Value = "read_themes")] ReadThemes, [EnumMember(Value = "write_themes")] WriteThemes, [EnumMember(Value = "read_products")] ReadProducts, [EnumMember(Value = "write_products")] WriteProducts, [EnumMember(Value = "read_customers")] ReadCustomers, [EnumMember(Value = "write_customers")] WriteCustomers, [EnumMember(Value = "read_orders")] ReadOrders, [EnumMember(Value = "write_orders")] WriteOrders, [EnumMember(Value = "read_script_tags")] ReadScriptTags, [EnumMember(Value = "write_script_tags")] WriteScriptTags, [EnumMember(Value = "read_fulfillments")] ReadFulfillments, [EnumMember(Value = "write_fulfillments")] WriteFulfillments, [EnumMember(Value = "read_shipping")] ReadShipping, [EnumMember(Value = "write_shipping")] WriteShipping } }
mit
C#
145d81e7273c4928a851137ec240d05bf6d76fc1
rectify the type in the comment.
jwChung/Experimentalism,jwChung/Experimentalism
src/Experiment.AutoFixture/AutoFixtureFactory.cs
src/Experiment.AutoFixture/AutoFixtureFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Jwc.Experiment; using Ploeh.AutoFixture; using Ploeh.AutoFixture.Kernel; using Ploeh.AutoFixture.Xunit; namespace Jwc.Experiment { /// <summary> /// Represents a fixture factory to create an instance of /// <see cref="ITestFixture"/>. /// </summary> public class AutoFixtureFactory : ITestFixtureFactory { private static readonly ITestFixtureFactory _instance = new AutoFixtureFactory(); private AutoFixtureFactory() { } /// <summary> /// Gets the singleton instance of <see cref="AutoFixtureFactory"/>. /// </summary> public static ITestFixtureFactory Instance { get { return _instance; } } /// <summary> /// Creates an instance of <see cref="Fixture" />. /// </summary> /// <param name="testMethod">The test method</param> /// <returns> /// The created fixture. /// </returns> public ITestFixture Create(MethodInfo testMethod) { if (testMethod == null) { throw new ArgumentNullException("testMethod"); } var fixture = testMethod.GetParameters() .SelectMany(SelectCustomizations) .Aggregate(CreateFixture(), (f, c) => f.Customize(c)); return new AutoFixtureAdapter(new SpecimenContext(fixture)); } private static IEnumerable<ICustomization> SelectCustomizations(ParameterInfo parameter) { return parameter.GetCustomAttributes(typeof(CustomizeAttribute), false) .Cast<CustomizeAttribute>() .Select(a => a.GetCustomization(parameter)); } private static IFixture CreateFixture() { return new Fixture(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Jwc.Experiment; using Ploeh.AutoFixture; using Ploeh.AutoFixture.Kernel; using Ploeh.AutoFixture.Xunit; namespace Jwc.Experiment { /// <summary> /// Represents a fixture factory to create an instance of /// <see cref="Fixture"/>. /// </summary> public class AutoFixtureFactory : ITestFixtureFactory { private static readonly ITestFixtureFactory _instance = new AutoFixtureFactory(); private AutoFixtureFactory() { } /// <summary> /// Gets the singleton instance of <see cref="AutoFixtureFactory"/>. /// </summary> public static ITestFixtureFactory Instance { get { return _instance; } } /// <summary> /// Creates an instance of <see cref="Fixture" />. /// </summary> /// <param name="testMethod">The test method</param> /// <returns> /// The created fixture. /// </returns> public ITestFixture Create(MethodInfo testMethod) { if (testMethod == null) { throw new ArgumentNullException("testMethod"); } var fixture = testMethod.GetParameters() .SelectMany(SelectCustomizations) .Aggregate(CreateFixture(), (f, c) => f.Customize(c)); return new AutoFixtureAdapter(new SpecimenContext(fixture)); } private static IEnumerable<ICustomization> SelectCustomizations(ParameterInfo parameter) { return parameter.GetCustomAttributes(typeof(CustomizeAttribute), false) .Cast<CustomizeAttribute>() .Select(a => a.GetCustomization(parameter)); } private static IFixture CreateFixture() { return new Fixture(); } } }
mit
C#
ecf75c2a6654b865706a59056a84b56cfcf44a9a
add cli client
bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core
src/Core/IdentityServer/StaticClients.cs
src/Core/IdentityServer/StaticClients.cs
using IdentityServer4.Models; using System.Collections.Generic; using System.Linq; namespace Bit.Core.IdentityServer { public class StaticClients { public static IDictionary<string, Client> GetApiClients() { return new List<Client> { new ApiClient("mobile", 90, 1), new ApiClient("web", 1, 1), new ApiClient("browser", 30, 1), new ApiClient("desktop", 30, 1), new ApiClient("cli", 30, 1), new ApiClient("connector", 30, 24) }.ToDictionary(c => c.ClientId); } public class ApiClient : Client { public ApiClient( string id, int refreshTokenSlidingDays, int accessTokenLifetimeHours, string[] scopes = null) { ClientId = id; RequireClientSecret = false; AllowedGrantTypes = GrantTypes.ResourceOwnerPassword; RefreshTokenExpiration = TokenExpiration.Sliding; RefreshTokenUsage = TokenUsage.ReUse; SlidingRefreshTokenLifetime = 86400 * refreshTokenSlidingDays; AbsoluteRefreshTokenLifetime = 0; // forever UpdateAccessTokenClaimsOnRefresh = true; AccessTokenLifetime = 3600 * accessTokenLifetimeHours; AllowOfflineAccess = true; if(scopes == null) { scopes = new string[] { "api" }; } AllowedScopes = scopes; } } } }
using IdentityServer4.Models; using System.Collections.Generic; using System.Linq; namespace Bit.Core.IdentityServer { public class StaticClients { public static IDictionary<string, Client> GetApiClients() { return new List<Client> { new ApiClient("mobile", 90, 1), new ApiClient("web", 1, 1), new ApiClient("browser", 30, 1), new ApiClient("desktop", 30, 1), new ApiClient("connector", 30, 24) }.ToDictionary(c => c.ClientId); } public class ApiClient : Client { public ApiClient( string id, int refreshTokenSlidingDays, int accessTokenLifetimeHours, string[] scopes = null) { ClientId = id; RequireClientSecret = false; AllowedGrantTypes = GrantTypes.ResourceOwnerPassword; RefreshTokenExpiration = TokenExpiration.Sliding; RefreshTokenUsage = TokenUsage.ReUse; SlidingRefreshTokenLifetime = 86400 * refreshTokenSlidingDays; AbsoluteRefreshTokenLifetime = 0; // forever UpdateAccessTokenClaimsOnRefresh = true; AccessTokenLifetime = 3600 * accessTokenLifetimeHours; AllowOfflineAccess = true; if(scopes == null) { scopes = new string[] { "api" }; } AllowedScopes = scopes; } } } }
agpl-3.0
C#
27c631ac4de1fc4fc82dee2d844c03486ce0b988
fix exit command to exit the mobile number verification process
mahedee/gen-bot-hrm,mahedee/gen-bot-hrm,mahedee/gen-bot-hrm
src/HRMBot/Dialogs/MobileNumberDialog.cs
src/HRMBot/Dialogs/MobileNumberDialog.cs
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; namespace HRMBot.Dialogs { [Serializable] public class MobileNumberDialog : IDialog<int> { private int _attempts = 3; public async Task StartAsync(IDialogContext context) { await context.PostAsync("To verify please send your mobile number in 01XXXXXXXXX format. example:- 01771998817"); context.Wait(MessageReceivedAsync); } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) { var message = await result; int mobileNumber; if (int.TryParse(message.Text, out mobileNumber) && (mobileNumber.ToString().Length == 10)) { context.Done(mobileNumber); } else { --_attempts; if (message.Text.ToLower().Equals("cancel") || message.Text.ToLower().Equals("exit")) { context.Fail(new OperationCanceledException("")); } else if (_attempts > 0) { await context.PostAsync("I'm sorry, I don't understand your reply. What is your Mobile number (e.g. '01771998817')?"); context.Wait(MessageReceivedAsync); } else { context.Fail(new TooManyAttemptsException("Message was not a valid mobile number.")); } } } } }
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; namespace HRMBot.Dialogs { [Serializable] public class MobileNumberDialog : IDialog<int> { private int _attempts = 3; public async Task StartAsync(IDialogContext context) { await context.PostAsync("To verify please send your mobile number in 01XXXXXXXXX format. example:- 01771998817"); context.Wait(MessageReceivedAsync); } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) { var message = await result; int mobileNumber; if (int.TryParse(message.Text, out mobileNumber) && (mobileNumber.ToString().Length == 10)) { context.Done(mobileNumber); } else { --_attempts; if (message.Text.ToLower().Equals("cancel") || message.Text.ToLower().Equals("exit")) { context.Fail(new OperationCanceledException("")); } if (_attempts > 0) { await context.PostAsync("I'm sorry, I don't understand your reply. What is your Mobile number (e.g. '01771998817')?"); context.Wait(MessageReceivedAsync); } else { context.Fail(new TooManyAttemptsException("Message was not a valid mobile number.")); } } } } }
mit
C#
36dca23ce59a5fc99fdc8eb1d2d467dda75ff835
Add comment
dbelcher/Xamarin.Auth,jorik041/Xamarin.Auth,LoQIStar/Xamarin.Auth,xamarin/Xamarin.Auth,durandt/Xamarin.Auth,severino32/Xamarin.Auth,nachocove/Xamarin.Auth,YoupHulsebos/Xamarin.Auth,xamarin/Xamarin.Auth,xamarin/Xamarin.Auth,ofetisov/Xamarin.Auth
samples/Xamarin.Auth.Sample.iOS/AppDelegate.cs
samples/Xamarin.Auth.Sample.iOS/AppDelegate.cs
using System; using System.Collections.Generic; using System.Json; using System.Linq; using System.Threading.Tasks; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.Dialog; namespace Xamarin.Auth.Sample.iOS { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { void LoginToFacebook () { var auth = new OAuth2Authenticator ( clientId: "346691492084618", scope: "", authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"), redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html")); // If authorization succeeds or is canceled, .Completed will be fired. auth.Completed += (s, e) => { // We presented the UI, so it's up to us to dismiss it. dialog.DismissViewController (true, null); if (!e.IsAuthenticated) { facebookStatus.Caption = "Not authorized"; dialog.ReloadData(); return; } // Now that we're logged in, make a OAuth2 request to get the user's info. var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, e.Account); request.GetResponseAsync().ContinueWith (t => { if (t.IsFaulted) facebookStatus.Caption = "Error: " + t.Exception.InnerException.Message; else if (t.IsCanceled) facebookStatus.Caption = "Canceled"; else { var obj = JsonValue.Parse (t.Result.GetResponseText()); facebookStatus.Caption = "Logged in as " + obj["name"]; } dialog.ReloadData(); }, uiScheduler); }; UIViewController vc = auth.GetUI (); dialog.PresentViewController (vc, true, null); } public override bool FinishedLaunching (UIApplication app, NSDictionary options) { facebook = new Section ("Facebook"); facebook.Add (new StyledStringElement ("Log in", LoginToFacebook)); facebook.Add (facebookStatus = new StringElement (String.Empty)); dialog = new DialogViewController (new RootElement ("Xamarin.Auth Sample") { facebook, }); window = new UIWindow (UIScreen.MainScreen.Bounds); window.RootViewController = new UINavigationController (dialog); window.MakeKeyAndVisible (); return true; } private readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); UIWindow window; DialogViewController dialog; Section facebook; StringElement facebookStatus; // This is the main entry point of the application. static void Main (string[] args) { UIApplication.Main (args, null, "AppDelegate"); } } }
using System; using System.Collections.Generic; using System.Json; using System.Linq; using System.Threading.Tasks; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.Dialog; namespace Xamarin.Auth.Sample.iOS { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { void LoginToFacebook () { var auth = new OAuth2Authenticator ( clientId: "346691492084618", scope: "", authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"), redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html")); // If authorization succeeds or is canceled, .Completed will be fired. auth.Completed += (s, e) => { dialog.DismissViewController (true, null); if (!e.IsAuthenticated) { facebookStatus.Caption = "Not authorized"; dialog.ReloadData(); return; } // Now that we're logged in, make a OAuth2 request to get the user's info. var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, e.Account); request.GetResponseAsync().ContinueWith (t => { if (t.IsFaulted) facebookStatus.Caption = "Error: " + t.Exception.InnerException.Message; else if (t.IsCanceled) facebookStatus.Caption = "Canceled"; else { var obj = JsonValue.Parse (t.Result.GetResponseText()); facebookStatus.Caption = "Logged in as " + obj["name"]; } dialog.ReloadData(); }, uiScheduler); }; UIViewController vc = auth.GetUI (); dialog.PresentViewController (vc, true, null); } public override bool FinishedLaunching (UIApplication app, NSDictionary options) { facebook = new Section ("Facebook"); facebook.Add (new StyledStringElement ("Log in", LoginToFacebook)); facebook.Add (facebookStatus = new StringElement (String.Empty)); dialog = new DialogViewController (new RootElement ("Xamarin.Auth Sample") { facebook, }); window = new UIWindow (UIScreen.MainScreen.Bounds); window.RootViewController = new UINavigationController (dialog); window.MakeKeyAndVisible (); return true; } private readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); UIWindow window; DialogViewController dialog; Section facebook; StringElement facebookStatus; // This is the main entry point of the application. static void Main (string[] args) { UIApplication.Main (args, null, "AppDelegate"); } } }
apache-2.0
C#
1284f04ade8cd9bc2aecadc99e0c123311938245
Improve error messages
Baggykiin/pass-winmenu
pass-winmenu/src/Hotkeys.cs
pass-winmenu/src/Hotkeys.cs
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Forms; namespace PassWinmenu { internal partial class Program { private int hotkeyIdCounter = 0; private Dictionary<int, Action> hotkeyActions = new Dictionary<int, Action>(); [Flags] private enum ModifierKey { None = 0, Alt = 1, Control = 2, Shift = 4, Windows = 8 } internal class HotkeyException : Exception { public HotkeyException(string message) : base(message){ } } private void AddHotKey(ModifierKey mod, Keys key, Action action) { var success = NativeMethods.RegisterHotKey(Handle, hotkeyIdCounter, (int) mod, (int) key); if (!success) { var errorCode = Marshal.GetLastWin32Error(); if (errorCode == 1409) { throw new HotkeyException($"Failed to register the hotkey \"{mod}, {key}\". This hotkey has already been registered by a different application."); } else { throw new HotkeyException($"Failed to register the hotkey \"{mod} + {key}\". An unknown error (Win32 error code {errorCode}) occurred."); } } if(!success) throw new InvalidOperationException(); hotkeyActions[hotkeyIdCounter] = action; } private void DisposeHotkeys() { foreach (var key in hotkeyActions.Keys) { NativeMethods.UnregisterHotKey(Handle, key); } } private const int WM_HOTKEY = 0x312; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_HOTKEY) { //var key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); //var modifier = (ModifierKey)((int)m.LParam & 0xFFFF); var id = m.WParam.ToInt32(); hotkeyActions[id](); } } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Forms; namespace PassWinmenu { internal partial class Program { private int hotkeyIdCounter = 0; private Dictionary<int, Action> hotkeyActions = new Dictionary<int, Action>(); [Flags] private enum ModifierKey { None = 0, Alt = 1, Control = 2, Shift = 4, Windows = 8 } private void AddHotKey(ModifierKey mod, Keys key, Action action) { var success = NativeMethods.RegisterHotKey(Handle, hotkeyIdCounter, (int) mod, (int) key); if(!success) throw new InvalidOperationException($"Failed to set the hotkey. Win32 error code: {Marshal.GetLastWin32Error()}"); hotkeyActions[hotkeyIdCounter] = action; } private void DisposeHotkeys() { foreach (var key in hotkeyActions.Keys) { NativeMethods.UnregisterHotKey(Handle, key); } } private const int WM_HOTKEY = 0x312; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_HOTKEY) { //var key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); //var modifier = (ModifierKey)((int)m.LParam & 0xFFFF); var id = m.WParam.ToInt32(); hotkeyActions[id](); } } } }
mit
C#
0853f0e128dc14a880bc8d7ae0c2553fd67b4b9f
Remove comment
NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,peppy/osu,smoogipoo/osu
osu.Game.Rulesets.Taiko.Tests/DrawableTestHit.cs
osu.Game.Rulesets.Taiko.Tests/DrawableTestHit.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.Taiko.Objects; using osu.Game.Rulesets.Taiko.Objects.Drawables; namespace osu.Game.Rulesets.Taiko.Tests { public class DrawableTestHit : DrawableHit { public readonly HitResult Type; public DrawableTestHit(Hit hit, HitResult type = HitResult.Great) : base(hit) { Type = type; HitObject.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); } [BackgroundDependencyLoader] private void load() { Result.Type = Type; } public override bool OnPressed(TaikoAction action) => false; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.Taiko.Objects; using osu.Game.Rulesets.Taiko.Objects.Drawables; namespace osu.Game.Rulesets.Taiko.Tests { public class DrawableTestHit : DrawableHit { public readonly HitResult Type; public DrawableTestHit(Hit hit, HitResult type = HitResult.Great) : base(hit) { Type = type; // in order to create nested strong hit HitObject.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); } [BackgroundDependencyLoader] private void load() { Result.Type = Type; } public override bool OnPressed(TaikoAction action) => false; } }
mit
C#
5b5ba7df936f159df034467c0786e6ff4d161838
Remove unused offset
ppy/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu
osu.Game/Screens/Play/HUD/DefaultScoreCounter.cs
osu.Game/Screens/Play/HUD/DefaultScoreCounter.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Screens.Play.HUD { public class DefaultScoreCounter : ScoreCounter { public DefaultScoreCounter() : base(6) { Anchor = Anchor.TopCentre; Origin = Anchor.TopCentre; } [Resolved(canBeNull: true)] private HUDOverlay hud { get; set; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Colour = colours.BlueLighter; // todo: check if default once health display is skinnable hud?.ShowHealthbar.BindValueChanged(healthBar => { this.MoveToY(healthBar.NewValue ? 30 : 0, HUDOverlay.FADE_DURATION, HUDOverlay.FADE_EASING); }, true); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Screens.Play.HUD { public class DefaultScoreCounter : ScoreCounter { private readonly Vector2 offset = new Vector2(20, 5); public DefaultScoreCounter() : base(6) { Anchor = Anchor.TopCentre; Origin = Anchor.TopCentre; } [Resolved(canBeNull: true)] private HUDOverlay hud { get; set; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Colour = colours.BlueLighter; // todo: check if default once health display is skinnable hud?.ShowHealthbar.BindValueChanged(healthBar => { this.MoveToY(healthBar.NewValue ? 30 : 0, HUDOverlay.FADE_DURATION, HUDOverlay.FADE_EASING); }, true); } } }
mit
C#
2bcb61ac3a7a390b20434efa50319e18cd64fb8a
test fix for NRE's
Lokosmos/Kerbsplosions
Kerbsplosions/IntegrityModule.cs
Kerbsplosions/IntegrityModule.cs
//Written by Oscar (Matrixmage) using System; using UnityEngine; using KSP.IO; namespace Kerbsplosions { public class IntegrityModule : PartModule { [KSPField] public float Integrity; //Non-input KSPFields [KSPField(guiActive = true, guiName = "Integrity", guiUnits = "%", guiFormat = "0.00")] public float integrityPercentage; [KSPField(isPersistant = true)] public float currentIntegrity = 0f; //Non-input KSPFields void Start() { if (Integrity == 0.0F) { Integrity = part.crashTolerance; } } void Update() { if (Integrity == 0.0F) { Integrity = part.crashTolerance; } if (Integrity != 0.0F) { integrityPercentage = ((currentIntegrity / Integrity) * 100); } //Part death if (currentIntegrity <= 0) { part.explode(); } //Part death } } }
//Written by Oscar (Matrixmage) using System; using UnityEngine; using KSP.IO; namespace Kerbsplosions { public class IntegrityModule : PartModule { [KSPField] public float Integrity; //Non-input KSPFields [KSPField(guiActive = true, guiName = "Integrity", guiUnits = "%", guiFormat = "0.00")] public float integrityPercentage; [KSPField(isPersistant = true)] public float currentIntegrity; //Non-input KSPFields void Start() { if (Integrity == 0.0F) { Integrity = part.crashTolerance; } } void Update() { integrityPercentage = ((currentIntegrity / Integrity) * 100); //Part death if (currentIntegrity <= 0) { part.explode(); } //Part death } } }
mit
C#
e4f772a514b1066ca12a2f3e814922476ad0d2bc
Add vscode to git ignore
JosephWoodward/SlugityDotNet,JosephWoodward/StringToUrlSanitizer,JosephWoodward/SlugityDotNet
src/Slugity.Tests/CustomSlugityConfig.cs
src/Slugity.Tests/CustomSlugityConfig.cs
namespace SlugityLib.Tests { public class CustomSlugityConfig : ISlugityConfig { public CustomSlugityConfig() { TextCase = TextCase.LowerCase; StripStopWords = false; MaxLength = 30; StringSeparator = ' '; ReplacementCharacters = new CharacterReplacement(); } public TextCase TextCase { get; set; } public char StringSeparator { get; set; } public int? MaxLength { get; set; } public CharacterReplacement ReplacementCharacters { get; set; } public bool StripStopWords { get; set; } } }
using SlugityLib.Configuration; namespace SlugityLib.Tests { public class CustomSlugityConfig : ISlugityConfig { public CustomSlugityConfig() { TextCase = TextCase.LowerCase; StripStopWords = false; MaxLength = 30; StringSeparator = ' '; ReplacementCharacters = new CharacterReplacement(); } public TextCase TextCase { get; set; } public char StringSeparator { get; set; } public int? MaxLength { get; set; } public CharacterReplacement ReplacementCharacters { get; set; } public bool StripStopWords { get; set; } } }
mit
C#
e0b5e035f0e760ae1e59d6294ff0937dcbd668f8
Debug output
andlju/swetugg-tix,andlju/swetugg-tix,andlju/swetugg-tix
src/Swetugg.Tix.Activity.Jobs/Program.cs
src/Swetugg.Tix.Activity.Jobs/Program.cs
using Microsoft.Azure.WebJobs; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.ServiceBus; using Microsoft.Extensions.Configuration; namespace Swetugg.Tix.Activity.Jobs { public class Program { public static void Main(string[] args) { var configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile("appsettings.json"); configBuilder.AddEnvironmentVariables(); configBuilder.AddUserSecrets(); var config = configBuilder.Build(); foreach (var envVar in config.GetChildren()) { Console.WriteLine($"{envVar.Key}: {envVar.Value}"); } JobHostConfiguration jobHostConfig = new JobHostConfiguration(config["Data:AzureWebJobsStorage:ConnectionString"]); /*jobHostConfig.StorageConnectionString = config["Data:AzureWebJobsStorage:ConnectionString"]; */ jobHostConfig.UseServiceBus(new ServiceBusConfiguration() { ConnectionString = config["Data:AzureServiceBus:ConnectionString"] }); JobHost host = new JobHost(jobHostConfig); host.RunAndBlock(); } public static void GenerateThumbnail([ServiceBusTrigger("activitycommands")] string command) { Console.Out.WriteLine("Got command"); Console.Out.WriteLine(command); } } }
using Microsoft.Azure.WebJobs; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.ServiceBus; using Microsoft.Extensions.Configuration; namespace Swetugg.Tix.Activity.Jobs { public class Program { public static void Main(string[] args) { var configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile("appsettings.json"); configBuilder.AddUserSecrets(); var config = configBuilder.Build(); JobHostConfiguration jobHostConfig = new JobHostConfiguration(config["Data:AzureWebJobsStorage:ConnectionString"]); /*jobHostConfig.StorageConnectionString = config["Data:AzureWebJobsStorage:ConnectionString"]; */ jobHostConfig.UseServiceBus(new ServiceBusConfiguration() { ConnectionString = config["Data:AzureServiceBus:ConnectionString"] }); JobHost host = new JobHost(jobHostConfig); host.RunAndBlock(); } public static void GenerateThumbnail([ServiceBusTrigger("activitycommands")] string command) { Console.Out.WriteLine("Got command"); Console.Out.WriteLine(command); } } }
mit
C#
807e4022b58b14aa7fa25c37eccc2beb0bfdfc32
Remove RequestPath from WebpackOptions
sergeysolovev/webpack-aspnetcore,sergeysolovev/webpack-aspnetcore,sergeysolovev/webpack-aspnetcore
src/Webpack.AspNetCore/WebpackOptions.cs
src/Webpack.AspNetCore/WebpackOptions.cs
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; namespace Webpack.AspNetCore { public class WebpackOptions { public WebpackOptions() { ManifestPath = new PathString("/asset-manifest.json"); } /// <summary> /// The asset manifest path within the application's web root path. /// Defaults to /asset-manifest.json /// </summary> public PathString ManifestPath { get; set; } public bool UseDevServer { get; set; } /// <summary> /// Default - 127.0.0.1 /// </summary> public string DevServerHost { get; set; } = "127.0.0.1"; /// <summary> /// Default - 8080 /// </summary> public int DevServerPort { get; set; } = 8080; /// <summary> /// Default - http /// </summary> public string DevServerScheme { get; set; } = "http"; /// <summary> /// Default - / /// </summary> public PathString DevServerPublicPath { get; set; } = PathString.Empty; /// <summary> /// Useful for reverse proxy url rewriting /// Only relevant if UseStaticFiles is set to false, otherwise it's ignored /// </summary> public bool KeepOriginalAssetUrls { get; set; } internal StaticFileLimitedOptions StaticFileOptions { get; set; } public void UseStaticFiles(Action<StaticFileLimitedOptions> configureOptions = null) { StaticFileOptions = new StaticFileLimitedOptions(); configureOptions?.Invoke(StaticFileOptions); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; namespace Webpack.AspNetCore { public class WebpackOptions { public WebpackOptions() { ManifestPath = new PathString("/asset-manifest.json"); RequestPath = PathString.Empty; } /// <summary> /// The asset manifest path within the application's web root path. /// Defaults to /asset-manifest.json /// </summary> public PathString ManifestPath { get; set; } public PathString RequestPath { get; set; } public bool UseDevServer { get; set; } /// <summary> /// Default - 127.0.0.1 /// </summary> public string DevServerHost { get; set; } = "127.0.0.1"; /// <summary> /// Default - 8080 /// </summary> public int DevServerPort { get; set; } = 8080; /// <summary> /// Default - http /// </summary> public string DevServerScheme { get; set; } = "http"; /// <summary> /// Default - / /// </summary> public PathString DevServerPublicPath { get; set; } = PathString.Empty; /// <summary> /// Useful for reverse proxy url rewriting /// Only relevant if UseStaticFiles is set to false, otherwise it's ignored /// </summary> public bool KeepOriginalAssetUrls { get; set; } internal StaticFileLimitedOptions StaticFileOptions { get; set; } public void UseStaticFiles(Action<StaticFileLimitedOptions> configureOptions = null) { StaticFileOptions = new StaticFileLimitedOptions(); configureOptions?.Invoke(StaticFileOptions); } } }
mit
C#
516b1042846d1443040625b413069eddc0b15a4f
Make a book titled "blah 2 blah" sort before "blah 2.1 blah"
BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,gmartin7/myBloomFork,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop
src/BloomExe/Collection/NaturalSortComparer.cs
src/BloomExe/Collection/NaturalSortComparer.cs
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Bloom.Collection { /// <summary> /// From James McCormack, http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html /// </summary> /// <typeparam name="T"></typeparam> public class NaturalSortComparer<T> : IComparer<string> { private bool isAscending; public NaturalSortComparer(bool inAscendingOrder = true) { this.isAscending = inAscendingOrder; } #region IComparer<string> Members public int Compare(string x, string y) { throw new NotImplementedException(); } #endregion #region IComparer<string> Members int IComparer<string>.Compare(string x, string y) { if (x == y) return 0; string[] x1, y1; if (!table.TryGetValue(x, out x1)) { x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)"); table.Add(x, x1); } if (!table.TryGetValue(y, out y1)) { y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)"); table.Add(y, y1); } int returnVal; for (int i = 0; i < x1.Length && i < y1.Length; i++) { if (x1[i] != y1[i]) { returnVal = PartCompare(x1[i], y1[i]); return isAscending ? returnVal : -returnVal; } } if (y1.Length > x1.Length) { returnVal = 1; } else if (x1.Length > y1.Length) { returnVal = -1; } else { returnVal = 0; } return isAscending ? returnVal : -returnVal; } private static int PartCompare(string left, string right) { // Make "blah 2 blah" sort before "blah 2.1 blah". NB: Sort order ends up determinging order in the Folio PDF, so SIL-Lead SHRP (Uganda) is dependent on this if (left == ".") return 1; if(right == ".") return -1; int x, y; if (!int.TryParse(left, out x)) return left.CompareTo(right); if (!int.TryParse(right, out y)) return left.CompareTo(right); return x.CompareTo(y); } #endregion private Dictionary<string, string[]> table = new Dictionary<string, string[]>(); } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Bloom.Collection { /// <summary> /// From James McCormack, http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html /// </summary> /// <typeparam name="T"></typeparam> public class NaturalSortComparer<T> : IComparer<string> { private bool isAscending; public NaturalSortComparer(bool inAscendingOrder = true) { this.isAscending = inAscendingOrder; } #region IComparer<string> Members public int Compare(string x, string y) { throw new NotImplementedException(); } #endregion #region IComparer<string> Members int IComparer<string>.Compare(string x, string y) { if (x == y) return 0; string[] x1, y1; if (!table.TryGetValue(x, out x1)) { x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)"); table.Add(x, x1); } if (!table.TryGetValue(y, out y1)) { y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)"); table.Add(y, y1); } int returnVal; for (int i = 0; i < x1.Length && i < y1.Length; i++) { if (x1[i] != y1[i]) { returnVal = PartCompare(x1[i], y1[i]); return isAscending ? returnVal : -returnVal; } } if (y1.Length > x1.Length) { returnVal = 1; } else if (x1.Length > y1.Length) { returnVal = -1; } else { returnVal = 0; } return isAscending ? returnVal : -returnVal; } private static int PartCompare(string left, string right) { int x, y; if (!int.TryParse(left, out x)) return left.CompareTo(right); if (!int.TryParse(right, out y)) return left.CompareTo(right); return x.CompareTo(y); } #endregion private Dictionary<string, string[]> table = new Dictionary<string, string[]>(); } }
mit
C#
460e6f86f96586762c333794a7d942f578a63587
Add new ICFType interface
jorik041/maccore,mono/maccore,cwensley/maccore
src/CoreFoundation/CFType.cs
src/CoreFoundation/CFType.cs
// // Copyright 2012 Xamarin // using System; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; namespace MonoMac.CoreFoundation { public class CFType { [DllImport (Constants.CoreFoundationLibrary, EntryPoint="CFGetTypeID")] public static extern int GetTypeID (IntPtr typeRef); } public interface ICFType : INativeObject { } }
using System; using System.Runtime.InteropServices; namespace MonoMac.CoreFoundation { public class CFType { [DllImport (Constants.CoreFoundationLibrary, EntryPoint="CFGetTypeID")] public static extern int GetTypeID (IntPtr typeRef); } }
apache-2.0
C#
b06ba330638245b15beac973847a05cfe1068d67
Fix error dialog close button not working
Zyrio/ictus,Zyrio/ictus
src/Yio/Views/Shared/_ErrorPanelPartial.cshtml
src/Yio/Views/Shared/_ErrorPanelPartial.cshtml
<div class="panel" id="error-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="error-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1 id="error-title">Error!</h1> <p id="error-message"> <img src="http://i.imgur.com/ne6uoFj.png" style="margin-bottom: 10px; width: 100%;"/><br /> Uh, I can explain... </p> </div> </div>
<div class="panel" id="error-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1 id="error-title">Error!</h1> <p id="error-message"> Oh no! </p> </div> </div>
mit
C#
a4e006c5e75442b7ab451573d600f994b917cfdd
Use Automapper AssertConfigurationIsValid
ASP-NET-MVC-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-MVC-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework
Benchmarks/Boxed.Mapping.Benchmark/Mapping/AutomapperConfiguration.cs
Benchmarks/Boxed.Mapping.Benchmark/Mapping/AutomapperConfiguration.cs
namespace Boxed.Mapping.Benchmark.Mapping { using AutoMapper; using Boxed.Mapping.Benchmark.Models; public static class AutomapperConfiguration { public static IMapper CreateMapper() { var configuration = new MapperConfiguration( x => x.CreateMap<MapFrom, MapTo>() .ForMember(y => y.BooleanTo, y => y.MapFrom(z => z.BooleanFrom)) .ForMember(y => y.DateTimeOffsetTo, y => y.MapFrom(z => z.DateTimeOffsetFrom)) .ForMember(y => y.IntegerTo, y => y.MapFrom(z => z.IntegerFrom)) .ForMember(y => y.LongTo, y => y.MapFrom(z => z.LongFrom)) .ForMember(y => y.StringTo, y => y.MapFrom(z => z.StringFrom))); configuration.AssertConfigurationIsValid(); return configuration.CreateMapper(); } } }
namespace Boxed.Mapping.Benchmark.Mapping { using AutoMapper; using Boxed.Mapping.Benchmark.Models; public static class AutomapperConfiguration { public static IMapper CreateMapper() { var configuration = new MapperConfiguration( x => x.CreateMap<MapFrom, MapTo>() .ForMember(y => y.BooleanTo, y => y.MapFrom(z => z.BooleanFrom)) .ForMember(y => y.DateTimeOffsetTo, y => y.MapFrom(z => z.DateTimeOffsetFrom)) .ForMember(y => y.IntegerTo, y => y.MapFrom(z => z.IntegerFrom)) .ForMember(y => y.LongTo, y => y.MapFrom(z => z.LongFrom)) .ForMember(y => y.StringTo, y => y.MapFrom(z => z.StringFrom))); return configuration.CreateMapper(); } } }
mit
C#
111f3c2d070c2a8125c1b3893c8200148d90648b
allow to provide the task state explicitly
mastersign/Mastersign.Tasks
src/Library/TaskEventArgs.cs
src/Library/TaskEventArgs.cs
using System; using System.Collections.Generic; using System.Text; namespace Mastersign.Tasks { public class TaskEventArgs : EventArgs { public ITask Task { get; private set; } public TaskState State { get; private set; } public TaskEventArgs(ITask task) { Task = task; State = task.State; } public TaskEventArgs(ITask task, TaskState state) { Task = task; State = state; } } }
using System; using System.Collections.Generic; using System.Text; namespace Mastersign.Tasks { public class TaskEventArgs : EventArgs { public ITask Task { get; private set; } public TaskState State { get; private set; } public TaskEventArgs(ITask task) { Task = task; State = task.State; } } }
mit
C#
0a6260df081fec40d4e493c60b3021dafeac7000
Fix V96Domains DevToolsVersion property value
SeleniumHQ/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,titusfortner/selenium,titusfortner/selenium,SeleniumHQ/selenium,valfirst/selenium,valfirst/selenium,titusfortner/selenium,HtmlUnit/selenium,valfirst/selenium,joshmgrant/selenium,valfirst/selenium,joshmgrant/selenium,HtmlUnit/selenium,titusfortner/selenium,valfirst/selenium,valfirst/selenium,joshmgrant/selenium,joshmgrant/selenium,titusfortner/selenium,titusfortner/selenium,joshmgrant/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,valfirst/selenium,titusfortner/selenium,joshmgrant/selenium,valfirst/selenium,titusfortner/selenium,valfirst/selenium,SeleniumHQ/selenium,joshmgrant/selenium,valfirst/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,titusfortner/selenium,valfirst/selenium,titusfortner/selenium,HtmlUnit/selenium,joshmgrant/selenium,joshmgrant/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,joshmgrant/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,joshmgrant/selenium,SeleniumHQ/selenium,titusfortner/selenium,SeleniumHQ/selenium
dotnet/src/webdriver/DevTools/v96/V96Domains.cs
dotnet/src/webdriver/DevTools/v96/V96Domains.cs
// <copyright file="V96Domains.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Text; namespace OpenQA.Selenium.DevTools.V96 { /// <summary> /// Class containing the domain implementation for version 94 of the DevTools Protocol. /// </summary> public class V96Domains : DevToolsDomains { private DevToolsSessionDomains domains; public V96Domains(DevToolsSession session) { this.domains = new DevToolsSessionDomains(session); } /// <summary> /// Gets the DevTools Protocol version for which this class is valid. /// </summary> public static int DevToolsVersion => 96; /// <summary> /// Gets the version-specific domains for the DevTools session. This value must be cast to a version specific type to be at all useful. /// </summary> public override DevTools.DevToolsSessionDomains VersionSpecificDomains => this.domains; /// <summary> /// Gets the object used for manipulating network information in the browser. /// </summary> public override DevTools.Network Network => new V96Network(domains.Network, domains.Fetch); /// <summary> /// Gets the object used for manipulating the browser's JavaScript execution. /// </summary> public override JavaScript JavaScript => new V96JavaScript(domains.Runtime, domains.Page); /// <summary> /// Gets the object used for manipulating DevTools Protocol targets. /// </summary> public override DevTools.Target Target => new V96Target(domains.Target); /// <summary> /// Gets the object used for manipulating the browser's logs. /// </summary> public override DevTools.Log Log => new V96Log(domains.Log); } }
// <copyright file="V96Domains.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Text; namespace OpenQA.Selenium.DevTools.V96 { /// <summary> /// Class containing the domain implementation for version 94 of the DevTools Protocol. /// </summary> public class V96Domains : DevToolsDomains { private DevToolsSessionDomains domains; public V96Domains(DevToolsSession session) { this.domains = new DevToolsSessionDomains(session); } /// <summary> /// Gets the DevTools Protocol version for which this class is valid. /// </summary> public static int DevToolsVersion => 95; /// <summary> /// Gets the version-specific domains for the DevTools session. This value must be cast to a version specific type to be at all useful. /// </summary> public override DevTools.DevToolsSessionDomains VersionSpecificDomains => this.domains; /// <summary> /// Gets the object used for manipulating network information in the browser. /// </summary> public override DevTools.Network Network => new V96Network(domains.Network, domains.Fetch); /// <summary> /// Gets the object used for manipulating the browser's JavaScript execution. /// </summary> public override JavaScript JavaScript => new V96JavaScript(domains.Runtime, domains.Page); /// <summary> /// Gets the object used for manipulating DevTools Protocol targets. /// </summary> public override DevTools.Target Target => new V96Target(domains.Target); /// <summary> /// Gets the object used for manipulating the browser's logs. /// </summary> public override DevTools.Log Log => new V96Log(domains.Log); } }
apache-2.0
C#
a4c99d2e963768d89c069bbf5c3a9f53b40261e9
Allow NullProcess to return null properties
Haacked/Rothko
src/Processes/NullProcess.cs
src/Processes/NullProcess.cs
using System; using System.Diagnostics; using System.IO; using NullGuard; namespace Rothko { public sealed class NullProcess : IProcess { #pragma warning disable 67 public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; #pragma warning restore 67 public NullProcess(ProcessStartInfo psi) { StartInfo = psi; } public NullProcess() { } public int Id { get { return 4; } } public ProcessStartInfo StartInfo { get; set; } public StreamWriter StandardInput { [return: AllowNull] get { return null; } } public StreamReader StandardOutput { [return: AllowNull] get { return null; } } public StreamReader StandardError { [return: AllowNull] get { return null; } } public int ExitCode { get { return 0; } } public IntPtr MainWindowHandle { get { return IntPtr.Zero; } } public string ProcessName { [return: AllowNull] get { return null; } } public void BeginOutputReadLine() { } public void BeginErrorReadLine() { } public bool Start() { return true; } public bool WaitForExit(int milliseconds) { return true; } public void Close() { } public void Kill() { } public void KillProcessTree() { } public bool Show() { return false; } public void Dispose() { } } }
using System; using System.Diagnostics; using System.IO; namespace Rothko { public sealed class NullProcess : IProcess { #pragma warning disable 67 public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; #pragma warning restore 67 public NullProcess(ProcessStartInfo psi) { StartInfo = psi; } public NullProcess() { } public int Id { get { return 4; } } public ProcessStartInfo StartInfo { get; set; } public StreamWriter StandardInput { get { return null; } } public StreamReader StandardOutput { get { return null; } } public StreamReader StandardError { get { return null; } } public int ExitCode { get { return 0; } } public IntPtr MainWindowHandle { get { return IntPtr.Zero; } } public string ProcessName { get { return null; } } public void BeginOutputReadLine() { } public void BeginErrorReadLine() { } public bool Start() { return true; } public bool WaitForExit(int milliseconds) { return true; } public void Close() { } public void Kill() { } public void KillProcessTree() { } public bool Show() { return false; } public void Dispose() { } } }
mit
C#
44983291e178c7952e7bd14715af78c793715e2c
Implement method
restful-routing/restful-routing,restful-routing/restful-routing,stevehodgkiss/restful-routing,stevehodgkiss/restful-routing,stevehodgkiss/restful-routing,restful-routing/restful-routing
src/RestfulRouting/Mapper.cs
src/RestfulRouting/Mapper.cs
using System.Web.Mvc; using System.Web.Routing; namespace RestfulRouting { public abstract class Mapper { protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods) { return new Route(path, new RouteValueDictionary(new { controller, action }), new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }), new MvcRouteHandler()); } } }
using System; using System.Web.Routing; namespace RestfulRouting { public abstract class Mapper { protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods) { throw new NotImplementedException(); } } }
mit
C#
69cb370c97f77418ac2ffd09275dda0e13eff7ea
Enable escaping by default
Shiney/roslyn,gafter/roslyn,ErikSchierboom/roslyn,khellang/roslyn,thomaslevesque/roslyn,brettfo/roslyn,diryboy/roslyn,tmeschter/roslyn,nguerrera/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,physhi/roslyn,drognanar/roslyn,weltkante/roslyn,michalhosala/roslyn,jkotas/roslyn,vslsnap/roslyn,Hosch250/roslyn,CaptainHayashi/roslyn,MatthieuMEZIL/roslyn,akrisiun/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,MattWindsor91/roslyn,jcouv/roslyn,OmarTawfik/roslyn,Pvlerick/roslyn,weltkante/roslyn,akrisiun/roslyn,MichalStrehovsky/roslyn,amcasey/roslyn,natgla/roslyn,gafter/roslyn,zooba/roslyn,jamesqo/roslyn,reaction1989/roslyn,yeaicc/roslyn,tmeschter/roslyn,dotnet/roslyn,mmitche/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,sharadagrawal/Roslyn,AlekseyTs/roslyn,TyOverby/roslyn,swaroop-sridhar/roslyn,paulvanbrenk/roslyn,eriawan/roslyn,mattwar/roslyn,bbarry/roslyn,kelltrick/roslyn,MattWindsor91/roslyn,mmitche/roslyn,pdelvo/roslyn,khyperia/roslyn,heejaechang/roslyn,stephentoub/roslyn,brettfo/roslyn,KevinH-MS/roslyn,reaction1989/roslyn,SeriaWei/roslyn,mattscheffer/roslyn,vslsnap/roslyn,xoofx/roslyn,TyOverby/roslyn,kelltrick/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,brettfo/roslyn,Giftednewt/roslyn,a-ctor/roslyn,mattscheffer/roslyn,khyperia/roslyn,MichalStrehovsky/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,Shiney/roslyn,srivatsn/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,panopticoncentral/roslyn,rgani/roslyn,khyperia/roslyn,robinsedlaczek/roslyn,cston/roslyn,budcribar/roslyn,diryboy/roslyn,sharadagrawal/Roslyn,sharadagrawal/Roslyn,ErikSchierboom/roslyn,dpoeschl/roslyn,cston/roslyn,agocke/roslyn,MatthieuMEZIL/roslyn,balajikris/roslyn,tvand7093/roslyn,gafter/roslyn,yeaicc/roslyn,SeriaWei/roslyn,stephentoub/roslyn,tvand7093/roslyn,AmadeusW/roslyn,amcasey/roslyn,kelltrick/roslyn,yeaicc/roslyn,tmat/roslyn,khellang/roslyn,Pvlerick/roslyn,vslsnap/roslyn,drognanar/roslyn,tmat/roslyn,bkoelman/roslyn,amcasey/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,DustinCampbell/roslyn,ValentinRueda/roslyn,KirillOsenkov/roslyn,AArnott/roslyn,CaptainHayashi/roslyn,tmeschter/roslyn,agocke/roslyn,AlekseyTs/roslyn,jmarolf/roslyn,mattwar/roslyn,orthoxerox/roslyn,KevinRansom/roslyn,Maxwe11/roslyn,aelij/roslyn,abock/roslyn,KevinH-MS/roslyn,paulvanbrenk/roslyn,jkotas/roslyn,weltkante/roslyn,pdelvo/roslyn,paulvanbrenk/roslyn,bartdesmet/roslyn,stephentoub/roslyn,jmarolf/roslyn,wvdd007/roslyn,ljw1004/roslyn,zooba/roslyn,ericfe-ms/roslyn,ErikSchierboom/roslyn,CaptainHayashi/roslyn,natidea/roslyn,jaredpar/roslyn,wvdd007/roslyn,basoundr/roslyn,sharwell/roslyn,Maxwe11/roslyn,bbarry/roslyn,jhendrixMSFT/roslyn,ljw1004/roslyn,michalhosala/roslyn,KevinH-MS/roslyn,orthoxerox/roslyn,jaredpar/roslyn,bkoelman/roslyn,MattWindsor91/roslyn,KevinRansom/roslyn,jmarolf/roslyn,mavasani/roslyn,ljw1004/roslyn,srivatsn/roslyn,mgoertz-msft/roslyn,rgani/roslyn,Maxwe11/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,lorcanmooney/roslyn,swaroop-sridhar/roslyn,antonssonj/roslyn,a-ctor/roslyn,KiloBravoLima/roslyn,jeffanders/roslyn,jeffanders/roslyn,abock/roslyn,wvdd007/roslyn,physhi/roslyn,vcsjones/roslyn,tmat/roslyn,antonssonj/roslyn,jeffanders/roslyn,mavasani/roslyn,bkoelman/roslyn,budcribar/roslyn,vcsjones/roslyn,jhendrixMSFT/roslyn,heejaechang/roslyn,Hosch250/roslyn,physhi/roslyn,jamesqo/roslyn,MatthieuMEZIL/roslyn,leppie/roslyn,basoundr/roslyn,rgani/roslyn,DustinCampbell/roslyn,AnthonyDGreen/roslyn,pdelvo/roslyn,natidea/roslyn,xoofx/roslyn,VSadov/roslyn,abock/roslyn,bbarry/roslyn,nguerrera/roslyn,SeriaWei/roslyn,jamesqo/roslyn,jasonmalinowski/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,Hosch250/roslyn,ValentinRueda/roslyn,jkotas/roslyn,michalhosala/roslyn,lorcanmooney/roslyn,DustinCampbell/roslyn,agocke/roslyn,tvand7093/roslyn,Giftednewt/roslyn,mattwar/roslyn,vcsjones/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,VSadov/roslyn,AmadeusW/roslyn,dotnet/roslyn,AArnott/roslyn,xasx/roslyn,jaredpar/roslyn,KiloBravoLima/roslyn,a-ctor/roslyn,reaction1989/roslyn,jcouv/roslyn,VSadov/roslyn,OmarTawfik/roslyn,KirillOsenkov/roslyn,nguerrera/roslyn,dpoeschl/roslyn,aelij/roslyn,akrisiun/roslyn,AnthonyDGreen/roslyn,xasx/roslyn,drognanar/roslyn,dotnet/roslyn,budcribar/roslyn,shyamnamboodiripad/roslyn,MattWindsor91/roslyn,KirillOsenkov/roslyn,AArnott/roslyn,TyOverby/roslyn,Giftednewt/roslyn,mavasani/roslyn,natidea/roslyn,ericfe-ms/roslyn,leppie/roslyn,aelij/roslyn,dpoeschl/roslyn,robinsedlaczek/roslyn,antonssonj/roslyn,jcouv/roslyn,jasonmalinowski/roslyn,mattscheffer/roslyn,tannergooding/roslyn,Pvlerick/roslyn,robinsedlaczek/roslyn,lorcanmooney/roslyn,AlekseyTs/roslyn,MichalStrehovsky/roslyn,swaroop-sridhar/roslyn,khellang/roslyn,panopticoncentral/roslyn,leppie/roslyn,natgla/roslyn,davkean/roslyn,thomaslevesque/roslyn,zooba/roslyn,genlu/roslyn,cston/roslyn,genlu/roslyn,Shiney/roslyn,mmitche/roslyn,natgla/roslyn,balajikris/roslyn,sharwell/roslyn,ericfe-ms/roslyn,tannergooding/roslyn,AnthonyDGreen/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,xoofx/roslyn,heejaechang/roslyn,xasx/roslyn,ValentinRueda/roslyn,thomaslevesque/roslyn,jhendrixMSFT/roslyn,srivatsn/roslyn,genlu/roslyn,basoundr/roslyn,bartdesmet/roslyn,tannergooding/roslyn,KiloBravoLima/roslyn,balajikris/roslyn,orthoxerox/roslyn,eriawan/roslyn,bartdesmet/roslyn
src/Scripting/Core/Hosting/PrintOptions.cs
src/Scripting/Core/Hosting/PrintOptions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.CodeAnalysis.Scripting.Hosting { public class PrintOptions { private NumberRadix _numberRadix = NumberRadix.Decimal; private MemberDisplayFormat _memberDisplayFormat; private int _maximumOutputLength = 1024; public string Ellipsis { get; set; } = "..."; public bool EscapeNonPrintableCharacters { get; set; } = true; public NumberRadix NumberRadix { get { return _numberRadix; } set { if (!value.IsValid()) { throw new ArgumentOutOfRangeException(nameof(value)); } _numberRadix = value; } } public MemberDisplayFormat MemberDisplayFormat { get { return _memberDisplayFormat; } set { if (!value.IsValid()) { throw new ArgumentOutOfRangeException(nameof(value)); } _memberDisplayFormat = value; } } public int MaximumOutputLength { get { return _maximumOutputLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maximumOutputLength = value; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.CodeAnalysis.Scripting.Hosting { public class PrintOptions { private NumberRadix _numberRadix = NumberRadix.Decimal; private MemberDisplayFormat _memberDisplayFormat; private int _maximumOutputLength = 1024; public string Ellipsis { get; set; } = "..."; public bool EscapeNonPrintableCharacters { get; set; } public NumberRadix NumberRadix { get { return _numberRadix; } set { if (!value.IsValid()) { throw new ArgumentOutOfRangeException(nameof(value)); } _numberRadix = value; } } public MemberDisplayFormat MemberDisplayFormat { get { return _memberDisplayFormat; } set { if (!value.IsValid()) { throw new ArgumentOutOfRangeException(nameof(value)); } _memberDisplayFormat = value; } } public int MaximumOutputLength { get { return _maximumOutputLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maximumOutputLength = value; } } } }
mit
C#
c64b1978d707585d39e07cc0d9e7238aa519bece
Update PowerShellMetricTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Framework.Core/Analytics/Telemetry/PowerShellMetricTelemeter.cs
TIKSN.Framework.Core/Analytics/Telemetry/PowerShellMetricTelemeter.cs
using System.Management.Automation; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public class PowerShellMetricTelemeter : IMetricTelemeter { private readonly Cmdlet cmdlet; public PowerShellMetricTelemeter(Cmdlet cmdlet) => this.cmdlet = cmdlet; public Task TrackMetric(string metricName, decimal metricValue) { this.cmdlet.WriteVerbose($"METRIC: {metricName} - {metricValue}"); return Task.FromResult<object>(null); } } }
using System.Management.Automation; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public class PowerShellMetricTelemeter : IMetricTelemeter { private readonly Cmdlet cmdlet; public PowerShellMetricTelemeter(Cmdlet cmdlet) { this.cmdlet = cmdlet; } public Task TrackMetric(string metricName, decimal metricValue) { cmdlet.WriteVerbose($"METRIC: {metricName} - {metricValue}"); return Task.FromResult<object>(null); } } }
mit
C#
bdf36d881bf2fbb3fa3bfc8e58bfd2a2e6a67a3f
test commit
HatfieldConsultants/Hatfield.EnviroData.DataImport
Test/Hatfield.DataImport.Test/ValueParsers/DateTimeValueParserTest.cs
Test/Hatfield.DataImport.Test/ValueParsers/DateTimeValueParserTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Hatfield.DataImport.ValueParsers; namespace Hatfield.DataImport.Test.ValueParsers { [TestFixture] public class DateTimeValueParserTest { static object[] testCases = new object[] { new object[]{ "2014-01-05", new DateTime(2014, 1, 5) }, new object[]{ "2013-12-12 13:30:00", new DateTime(2013, 12, 12, 13, 30, 0) }, new object[]{ "2013-12-13 11:15:00", new DateTime(2013, 12, 13, 11, 15, 0) } }; [Test] [TestCaseSource("testCases")] public void AssertParseTest(object valueToParse, object expectedParsedValue) { var dateTimeValueParser = new DateTimeValueParser(); var parsedValue = dateTimeValueParser.Parse(valueToParse); Assert.AreEqual(expectedParsedValue, parsedValue); } [Test] [TestCase(null, typeof(ArgumentNullException), "Can not parse null value to datetime")] [TestCase("Hello World", typeof(FormatException), "Can not parse value to datetime")] public void AssertParseFailTest(string valueToParse, Type expectionType, string exceptionMessage) { var dateTimeValueParser = new DateTimeValueParser(); Assert.Throws(expectionType, () => dateTimeValueParser.Parse(valueToParse), exceptionMessage); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Hatfield.DataImport.ValueParsers; namespace Hatfield.DataImport.Test.ValueParsers { [TestFixture] public class DateTimeValueParserTest { static object[] testCases = new object[] { new object[]{ "2014-01-05", new DateTime(2014, 1, 5) }, new object[]{ "2013-12-12 13:30:00", new DateTime(2013, 12, 12, 13, 30, 0) }, new object[]{ "2013-12-13 11:15:00", new DateTime(2013, 12, 13, 11, 15, 0) } }; [Test] [TestCaseSource("testCases")] public void AssertParseTest(object valueToParse, object expectedParsedValue) { var dateTimeValueParser = new DateTimeValueParser(); var parsedValue = dateTimeValueParser.Parse(valueToParse); Assert.AreEqual(expectedParsedValue, parsedValue); } [Test] [TestCase(null, typeof(ArgumentNullException), "Can not parse null value to datetime")] [TestCase("Hello World", typeof(FormatException), "Can not parse value to datetime")] public void AssertParseFailTest(string valueToParse, Type expectionType, string exceptionMessage) { var dateTimeValueParser = new DateTimeValueParser(); Assert.Throws(expectionType, () => dateTimeValueParser.Parse(valueToParse), exceptionMessage); } } }
mpl-2.0
C#
dba9d777ba447601cf851ead6808878df5b825e9
Remove unused using
hey-red/Mime
test/MimeTests/GuessMime.cs
test/MimeTests/GuessMime.cs
using HeyRed.Mime; using System.IO; using Xunit; namespace MimeTests { public class GuessMime { public GuessMime() => MimeGuesser.MagicFilePath = ResourceUtils.GetMagicFilePath; [Fact] public void GuessMimeFromFilePath() { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(ResourceUtils.GetFileFixture); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromBuffer() { byte[] buffer = File.ReadAllBytes(ResourceUtils.GetFileFixture); string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(buffer); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromStream() { using (var stream = File.OpenRead(ResourceUtils.GetFileFixture)) { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(stream); Assert.Equal(expected, actual); } } [Fact] public void GuessMimeFromFileInfo() { string expected = "image/jpeg"; var fi = new FileInfo(ResourceUtils.GetFileFixture); string actual = fi.GuessMimeType(); Assert.Equal(expected, actual); } } }
using HeyRed.Mime; using System.IO; using System.Net.Http; using Xunit; namespace MimeTests { public class GuessMime { public GuessMime() => MimeGuesser.MagicFilePath = ResourceUtils.GetMagicFilePath; [Fact] public void GuessMimeFromFilePath() { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(ResourceUtils.GetFileFixture); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromBuffer() { byte[] buffer = File.ReadAllBytes(ResourceUtils.GetFileFixture); string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(buffer); Assert.Equal(expected, actual); } [Fact] public void GuessMimeFromStream() { using (var stream = File.OpenRead(ResourceUtils.GetFileFixture)) { string expected = "image/jpeg"; string actual = MimeGuesser.GuessMimeType(stream); Assert.Equal(expected, actual); } } [Fact] public void GuessMimeFromFileInfo() { string expected = "image/jpeg"; var fi = new FileInfo(ResourceUtils.GetFileFixture); string actual = fi.GuessMimeType(); Assert.Equal(expected, actual); } } }
mit
C#
380acd1d6f60670e937842ad3ade259c2eacbc50
Initialize ease curve
bartlomiejwolk/AnimationPathAnimator
PathData.cs
PathData.cs
using UnityEngine; using System.Collections; namespace ATP.AnimationPathTools { public class PathData : ScriptableObject { [SerializeField] private AnimationPath animatedObjectPath; [SerializeField] private AnimationPath rotationPath; [SerializeField] private AnimationCurve easeCurve; [SerializeField] private AnimationCurve tiltingCurve; private void OnEnable() { InstantiateReferenceTypes(); AssignDefaultValues(); } private void AssignDefaultValues() { InitializeAnimatedObjectPath(); InitializeRotationPath(); InitializeEaseCurve(); } private void InitializeEaseCurve() { easeCurve.AddKey(0, DefaultEaseCurveValue); easeCurve.AddKey(1, DefaultEaseCurveValue); } private float DefaultEaseCurveValue { get { return 0.05f; } } private void InitializeRotationPath() { var firstNodePos = new Vector3(0, 0, 0); rotationPath.CreateNewNode(0, firstNodePos); var lastNodePos = new Vector3(1, 0, 1); rotationPath.CreateNewNode(1, lastNodePos); } private void InitializeAnimatedObjectPath() { var firstNodePos = new Vector3(0, 0, 0); animatedObjectPath.CreateNewNode(0, firstNodePos); var lastNodePos = new Vector3(1, 0, 1); animatedObjectPath.CreateNewNode(1, lastNodePos); } private void InstantiateReferenceTypes() { animatedObjectPath = ScriptableObject.CreateInstance<AnimationPath>(); rotationPath = ScriptableObject.CreateInstance<AnimationPath>(); easeCurve = new AnimationCurve(); tiltingCurve = new AnimationCurve(); } } }
using UnityEngine; using System.Collections; namespace ATP.AnimationPathTools { public class PathData : ScriptableObject { [SerializeField] private AnimationPath animatedObjectPath; [SerializeField] private AnimationPath rotationPath; [SerializeField] private AnimationCurve easeCurve; [SerializeField] private AnimationCurve tiltingCurve; private void OnEnable() { InstantiateReferenceTypes(); AssignDefaultValues(); } private void AssignDefaultValues() { InitializeAnimatedObjectPath(); InitializeRotationPath(); } private void InitializeRotationPath() { var firstNodePos = new Vector3(0, 0, 0); rotationPath.CreateNewNode(0, firstNodePos); var lastNodePos = new Vector3(1, 0, 1); rotationPath.CreateNewNode(1, lastNodePos); } private void InitializeAnimatedObjectPath() { var firstNodePos = new Vector3(0, 0, 0); animatedObjectPath.CreateNewNode(0, firstNodePos); var lastNodePos = new Vector3(1, 0, 1); animatedObjectPath.CreateNewNode(1, lastNodePos); } private void InstantiateReferenceTypes() { animatedObjectPath = ScriptableObject.CreateInstance<AnimationPath>(); rotationPath = ScriptableObject.CreateInstance<AnimationPath>(); easeCurve = new AnimationCurve(); tiltingCurve = new AnimationCurve(); } } }
mit
C#
1042205b3291889b6974b66ab9770b9973548483
Remove filter (default will work)
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/ChristianHoejsager.cs
src/Firehose.Web/Authors/ChristianHoejsager.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/feed"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IFilterMyBlogPosts, IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/feed"); } } public bool Filter(SyndicationItem item) { return item.Categories?.Any(c => c.Name.ToLowerInvariant().Contains("powershell")) ?? false; } public string FeedLanguageCode => "en"; } }
mit
C#
f005af37b401e921d5402a9d4db8519bdcdd5192
add Format.Url, Format.EscapeUrl
RogueException/Discord.Net,AntiTcb/Discord.Net
src/Discord.Net.Core/Format.cs
src/Discord.Net.Core/Format.cs
namespace Discord { /// <summary> A helper class for formatting characters. </summary> public static class Format { // Characters which need escaping private static readonly string[] SensitiveCharacters = { "\\", "*", "_", "~", "`" }; /// <summary> Returns a markdown-formatted string with bold formatting. </summary> public static string Bold(string text) => $"**{text}**"; /// <summary> Returns a markdown-formatted string with italics formatting. </summary> public static string Italics(string text) => $"*{text}*"; /// <summary> Returns a markdown-formatted string with underline formatting. </summary> public static string Underline(string text) => $"__{text}__"; /// <summary> Returns a markdown-formatted string with strikethrough formatting. </summary> public static string Strikethrough(string text) => $"~~{text}~~"; /// <summary> Returns a markdown-formatted URL. Only works in <see cref="EmbedBuilder"/> descriptions and fields. </summary> public static string Url(string text, string url) => $"[{text}]({url})"; /// <summary> Escapes a URL so that a preview is not generated. </summary> public static string EscapeUrl(string url) => $"<{url}>"; /// <summary> Returns a markdown-formatted string with codeblock formatting. </summary> public static string Code(string text, string language = null) { if (language != null || text.Contains("\n")) return $"```{language ?? ""}\n{text}\n```"; else return $"`{text}`"; } /// <summary> Sanitizes the string, safely escaping any Markdown sequences. </summary> public static string Sanitize(string text) { foreach (string unsafeChar in SensitiveCharacters) text = text.Replace(unsafeChar, $"\\{unsafeChar}"); return text; } } }
namespace Discord { /// <summary> A helper class for formatting characters. </summary> public static class Format { // Characters which need escaping private static readonly string[] SensitiveCharacters = { "\\", "*", "_", "~", "`" }; /// <summary> Returns a markdown-formatted string with bold formatting. </summary> public static string Bold(string text) => $"**{text}**"; /// <summary> Returns a markdown-formatted string with italics formatting. </summary> public static string Italics(string text) => $"*{text}*"; /// <summary> Returns a markdown-formatted string with underline formatting. </summary> public static string Underline(string text) => $"__{text}__"; /// <summary> Returns a markdown-formatted string with strikethrough formatting. </summary> public static string Strikethrough(string text) => $"~~{text}~~"; /// <summary> Returns a markdown-formatted string with codeblock formatting. </summary> public static string Code(string text, string language = null) { if (language != null || text.Contains("\n")) return $"```{language ?? ""}\n{text}\n```"; else return $"`{text}`"; } /// <summary> Sanitizes the string, safely escaping any Markdown sequences. </summary> public static string Sanitize(string text) { foreach (string unsafeChar in SensitiveCharacters) text = text.Replace(unsafeChar, $"\\{unsafeChar}"); return text; } } }
mit
C#
1c6a4d65a048acbd61d197b2daa244e6f906214c
Add logging of TPL threadpool state on test failures
ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Logging/LoadingComponentsLogger.cs
osu.Framework/Logging/LoadingComponentsLogger.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using System.Threading; using osu.Framework.Development; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log($"⏳ Currently loading components ({loading_components.Count()})"); foreach (var c in loading_components.OrderBy(c => c.LoadThread?.Name).ThenBy(c => c.LoadState)) { Logger.Log(c.ToString()); Logger.Log($"- thread: {c.LoadThread?.Name ?? "none"}"); Logger.Log($"- state: {c.LoadState}"); } loading_components.Clear(); Logger.Log("🧵 Task schedulers"); Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString()); Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString()); } ThreadPool.GetAvailableThreads(out int workerAvailable, out int completionAvailable); ThreadPool.GetMinThreads(out int workerMin, out int completionMin); ThreadPool.GetMaxThreads(out int workerMax, out int completionMax); Logger.Log("🎱 Thread pool"); Logger.Log($"worker: min {workerMin,-6:#,0} max {workerMax,-6:#,0} available {workerAvailable,-6:#,0}"); Logger.Log($"completion: min {completionMin,-6:#,0} max {completionMax,-6:#,0} available {completionAvailable,-6:#,0}"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Development; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log($"⏳ Currently loading components ({loading_components.Count()})"); foreach (var c in loading_components.OrderBy(c => c.LoadThread?.Name).ThenBy(c => c.LoadState)) { Logger.Log(c.ToString()); Logger.Log($"- thread: {c.LoadThread?.Name ?? "none"}"); Logger.Log($"- state: {c.LoadState}"); } loading_components.Clear(); Logger.Log("🧵 Task schedulers"); Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString()); Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString()); } } } }
mit
C#
215c946c20693cc09cc635ae05be4f99dacd14c7
Set version 1.0.6.0
nunit/teamcity-event-listener,nunit/teamcity-event-listener
src/extension/Properties/AssemblyInfo.cs
src/extension/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("teamcity-event-listener")] [assembly: AssemblyDescription("NUnit Engine extension that helps integration with TeamCity.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("teamcity-event-listener")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a867079b-a172-4dae-9549-63b331092a23")] // 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.6.0")] [assembly: AssemblyFileVersion("1.0.6.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("teamcity-event-listener")] [assembly: AssemblyDescription("NUnit Engine extension that helps integration with TeamCity.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("teamcity-event-listener")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a867079b-a172-4dae-9549-63b331092a23")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.4.0")] [assembly: AssemblyFileVersion("1.0.4.0")]
mit
C#
be8dbcbfbd73d09d207ad8a1d4673a815e0e7570
Refactor to a thread-safe queue.
getsentry/raven-csharp,xpicio/raven-csharp,xpicio/raven-csharp,getsentry/raven-csharp,getsentry/raven-csharp
src/app/SharpRaven/Utilities/CircularBuffer.cs
src/app/SharpRaven/Utilities/CircularBuffer.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace SharpRaven.Utilities { public class CircularBuffer<T> { private readonly int size; private ConcurrentQueue<T> queue; public CircularBuffer(int size = 100) { this.size = size; queue = new ConcurrentQueue<T>(); } public List<T> ToList() { var listReturn = this.queue.ToList(); return listReturn.Skip(Math.Max(0, listReturn.Count - size)).ToList(); } public void Clear() { queue = new ConcurrentQueue<T>(); } public void Add(T item) { if (queue.Count >= size) { T result; this.queue.TryDequeue(out result); } queue.Enqueue(item); } public bool IsEmpty() { return queue.Count <= 0; } } }
using System.Collections.Generic; using System.Linq; namespace SharpRaven.Utilities { public class CircularBuffer<T> { private readonly int size; private readonly Queue<T> queue; public CircularBuffer(int size = 100) { this.size = size; queue = new Queue<T>(); } public List<T> ToList() { return queue.ToList(); } public void Clear() { queue.Clear(); } public void Add(T item) { if (queue.Count >= size) queue.Dequeue(); queue.Enqueue(item); } public bool IsEmpty() { return queue.Count <= 0; } } }
bsd-3-clause
C#
d45f95ddf4dd9749f526c3b4da88f4ced138f45a
Set version 1.0.7.0
nunit/teamcity-event-listener,nunit/teamcity-event-listener
src/extension/Properties/AssemblyInfo.cs
src/extension/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("teamcity-event-listener")] [assembly: AssemblyDescription("NUnit Engine extension that helps integration with TeamCity.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("teamcity-event-listener")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a867079b-a172-4dae-9549-63b331092a23")] // 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.7.0")] [assembly: AssemblyFileVersion("1.0.7.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("teamcity-event-listener")] [assembly: AssemblyDescription("NUnit Engine extension that helps integration with TeamCity.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("teamcity-event-listener")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a867079b-a172-4dae-9549-63b331092a23")] // 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.6.0")] [assembly: AssemblyFileVersion("1.0.6.0")]
mit
C#
9a179f5a28db7da4ad3cadf12fe4d00338932a95
Update ScopeDefinitionAttribute.ContainingClass property to use FirstOrDefault method instead of SingleOrDefault
YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata
src/Atata/Attributes/ScopeDefinitionAttribute.cs
src/Atata/Attributes/ScopeDefinitionAttribute.cs
using System.Linq; namespace Atata { /// <summary> /// Represents the base attribute class for component scope definition. /// The basic definition is represented with XPath. /// </summary> public abstract class ScopeDefinitionAttribute : MulticastAttribute { /// <summary> /// The default scope XPath, which is <c>"*"</c>. /// </summary> public const string DefaultScopeXPath = "*"; private readonly string baseScopeXPath; protected ScopeDefinitionAttribute(string scopeXPath = DefaultScopeXPath) { baseScopeXPath = scopeXPath; } /// <summary> /// Gets the XPath of the scope element which is a combination of XPath passed through the constructor and <see cref="ContainingClasses"/> property values. /// </summary> public string ScopeXPath => BuildScopeXPath(); /// <summary> /// Gets or sets the containing CSS class name. /// </summary> public string ContainingClass { get => ContainingClasses?.FirstOrDefault(); set => ContainingClasses = value == null ? null : new[] { value }; } /// <summary> /// Gets or sets the containing CSS class names. /// Multiple class names are used in XPath as conditions joined with <c>and</c> operator. /// </summary> public string[] ContainingClasses { get; set; } /// <summary> /// Builds the complete XPath of the scope element which is a combination of XPath passed through the constructor and <see cref="ContainingClasses"/> property values. /// </summary> /// <returns>The built XPath.</returns> protected virtual string BuildScopeXPath() { string scopeXPath = baseScopeXPath ?? DefaultScopeXPath; if (ContainingClasses?.Any() ?? false) { var classConditions = ContainingClasses.Select(x => $"contains(concat(' ', normalize-space(@class), ' '), ' {x.Trim()} ')"); return $"{scopeXPath}[{string.Join(" and ", classConditions)}]"; } else { return scopeXPath; } } } }
using System.Linq; namespace Atata { /// <summary> /// Represents the base attribute class for component scope definition. /// The basic definition is represented with XPath. /// </summary> public abstract class ScopeDefinitionAttribute : MulticastAttribute { /// <summary> /// The default scope XPath, which is <c>"*"</c>. /// </summary> public const string DefaultScopeXPath = "*"; private readonly string baseScopeXPath; protected ScopeDefinitionAttribute(string scopeXPath = DefaultScopeXPath) { baseScopeXPath = scopeXPath; } /// <summary> /// Gets the XPath of the scope element which is a combination of XPath passed through the constructor and <see cref="ContainingClasses"/> property values. /// </summary> public string ScopeXPath => BuildScopeXPath(); /// <summary> /// Gets or sets the containing CSS class name. /// </summary> public string ContainingClass { get => ContainingClasses?.SingleOrDefault(); set => ContainingClasses = value == null ? null : new[] { value }; } /// <summary> /// Gets or sets the containing CSS class names. /// Multiple class names are used in XPath as conditions joined with <c>and</c> operator. /// </summary> public string[] ContainingClasses { get; set; } /// <summary> /// Builds the complete XPath of the scope element which is a combination of XPath passed through the constructor and <see cref="ContainingClasses"/> property values. /// </summary> /// <returns>The built XPath.</returns> protected virtual string BuildScopeXPath() { string scopeXPath = baseScopeXPath ?? DefaultScopeXPath; if (ContainingClasses?.Any() ?? false) { var classConditions = ContainingClasses.Select(x => $"contains(concat(' ', normalize-space(@class), ' '), ' {x.Trim()} ')"); return $"{scopeXPath}[{string.Join(" and ", classConditions)}]"; } else { return scopeXPath; } } } }
apache-2.0
C#
e13ea1beaaa62f9814ff8d5281debc9c54ecde27
Fix string substitution
Nemo157/DocNuget,Nemo157/DocNuget,Nemo157/DocNuget,Nemo157/DocNuget,Nemo157/DocNuget
src/DocNuget.Models.Loader/NuGetPackageLoader.cs
src/DocNuget.Models.Loader/NuGetPackageLoader.cs
using System.Linq; using System.Threading.Tasks; using Microsoft.Framework.PackageManager; using Microsoft.Framework.Logging; using NuGet; namespace DocNuget.Models.Loader { public class NuGetPackageLoader { private readonly ILoggerFactory _loggerFactory; public NuGetPackageLoader(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public async Task<Package> LoadAsync(string id, string version) { var logger = _loggerFactory.CreateLogger<NuGetPackageLoader>(); var sourceProvider = new PackageSourceProvider( NullSettings.Instance, new[] { new PackageSource(NuGetConstants.DefaultFeedUrl) }); var feed = sourceProvider .LoadPackageSources() .Select(source => PackageSourceUtils.CreatePackageFeed( source, noCache: false, ignoreFailedSources: false, reports: logger.CreateReports())) .Where(f => f != null) .First(); logger.LogInformation($"Looking up {id} v{version} from nuget"); var packages = (await feed.FindPackagesByIdAsync(id)).OrderByDescending(p => p.Version); var package = version == null ? packages.FirstOrDefault() : packages.FirstOrDefault(p => p.Version == new SemanticVersion(version)); if (package == null) { logger.LogError($"Unable to locate {id} v{version}"); return null; } logger.LogInformation($"Found version {package.Version} of {package.Id}"); var zipPackage = new ZipPackage(await feed.OpenNupkgStreamAsync(package)); return zipPackage.ToPackage(packages.Select(p => p.Version.ToString()).ToList(), logger); } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.Framework.PackageManager; using Microsoft.Framework.Logging; using NuGet; namespace DocNuget.Models.Loader { public class NuGetPackageLoader { private readonly ILoggerFactory _loggerFactory; public NuGetPackageLoader(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public async Task<Package> LoadAsync(string id, string version) { var logger = _loggerFactory.CreateLogger<NuGetPackageLoader>(); var sourceProvider = new PackageSourceProvider( NullSettings.Instance, new[] { new PackageSource(NuGetConstants.DefaultFeedUrl) }); var feed = sourceProvider .LoadPackageSources() .Select(source => PackageSourceUtils.CreatePackageFeed( source, noCache: false, ignoreFailedSources: false, reports: logger.CreateReports())) .Where(f => f != null) .First(); logger.LogInformation($"Looking up {id} v{version} from nuget"); var packages = (await feed.FindPackagesByIdAsync(id)).OrderByDescending(p => p.Version); var package = version == null ? packages.FirstOrDefault() : packages.FirstOrDefault(p => p.Version == new SemanticVersion(version)); if (package == null) { logger.LogError($"Unable to locate {id} v{version}"); return null; } logger.LogInformation("Found version {package.Version} of {package.Id}"); var zipPackage = new ZipPackage(await feed.OpenNupkgStreamAsync(package)); return zipPackage.ToPackage(packages.Select(p => p.Version.ToString()).ToList(), logger); } } }
mit
C#
4db730a7ded3174a1971a0b65e81f3f609170c7b
remove unused constructor.
dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP
src/DotNetCore.CAP/Models/CapPublishedMessage.cs
src/DotNetCore.CAP/Models/CapPublishedMessage.cs
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; namespace DotNetCore.CAP.Models { public class CapPublishedMessage { /// <summary> /// Initializes a new instance of <see cref="CapPublishedMessage" />. /// </summary> public CapPublishedMessage() { Added = DateTime.Now; } public int Id { get; set; } public string Name { get; set; } public string Content { get; set; } public DateTime Added { get; set; } public DateTime? ExpiresAt { get; set; } public int Retries { get; set; } public string StatusName { get; set; } public override string ToString() { return "name:" + Name + ", content:" + Content; } } }
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; namespace DotNetCore.CAP.Models { public class CapPublishedMessage { /// <summary> /// Initializes a new instance of <see cref="CapPublishedMessage" />. /// </summary> public CapPublishedMessage() { Added = DateTime.Now; } public CapPublishedMessage(MessageContext message) { Name = message.Name; Content = message.Content; } public int Id { get; set; } public string Name { get; set; } public string Content { get; set; } public DateTime Added { get; set; } public DateTime? ExpiresAt { get; set; } public int Retries { get; set; } public string StatusName { get; set; } public override string ToString() { return "name:" + Name + ", content:" + Content; } } }
mit
C#
144983cf769c39c0b818afa6a5167d4e8c0ae79d
Update ExceptionSerializer.cs
hprose/hprose-dotnet
src/Hprose.IO/Serializers/ExceptionSerializer.cs
src/Hprose.IO/Serializers/ExceptionSerializer.cs
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | ExceptionSerializer.cs | | | | ExceptionSerializer class for C#. | | | | LastModified: Feb 8, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using System; namespace Hprose.IO.Serializers { using static Tags; internal class ExceptionSerializer<T> : ReferenceSerializer<T> where T : Exception { public override void Write(Writer writer, T obj) { // No reference to exception writer.AddReferenceCount(1); var stream = writer.Stream; stream.WriteByte(TagError); stream.WriteByte(TagString); ValueWriter.Write(stream, obj.Message); } } }
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | ExceptionSerializer.cs | | | | ExceptionSerializer class for C#. | | | | LastModified: Feb 8, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using System; namespace Hprose.IO.Serializers { using static Tags; internal class ExceptionSerializer<T> : ReferenceSerializer<T> where T : Exception { public override void Write(Writer writer, T obj) { // No reference to exception writer.SetReference(new object()); var stream = writer.Stream; stream.WriteByte(TagError); stream.WriteByte(TagString); ValueWriter.Write(stream, obj.Message); } } }
mit
C#
58ae086a7385c46cd5d99b290a81f679ada16869
Move using-statements within namespace declaration.
AcklenAvenue/Nancy,asbjornu/Nancy,khellang/Nancy,ayoung/Nancy,hitesh97/Nancy,asbjornu/Nancy,charleypeng/Nancy,sadiqhirani/Nancy,AlexPuiu/Nancy,thecodejunkie/Nancy,guodf/Nancy,albertjan/Nancy,EliotJones/NancyTest,sloncho/Nancy,ayoung/Nancy,jchannon/Nancy,tparnell8/Nancy,anton-gogolev/Nancy,JoeStead/Nancy,danbarua/Nancy,sadiqhirani/Nancy,AlexPuiu/Nancy,tareq-s/Nancy,Worthaboutapig/Nancy,davidallyoung/Nancy,Novakov/Nancy,NancyFx/Nancy,ayoung/Nancy,horsdal/Nancy,VQComms/Nancy,rudygt/Nancy,sloncho/Nancy,jonathanfoster/Nancy,albertjan/Nancy,vladlopes/Nancy,rudygt/Nancy,grumpydev/Nancy,sroylance/Nancy,duszekmestre/Nancy,MetSystem/Nancy,davidallyoung/Nancy,xt0rted/Nancy,joebuschmann/Nancy,vladlopes/Nancy,charleypeng/Nancy,AlexPuiu/Nancy,hitesh97/Nancy,Worthaboutapig/Nancy,AIexandr/Nancy,jchannon/Nancy,jonathanfoster/Nancy,daniellor/Nancy,guodf/Nancy,AIexandr/Nancy,cgourlay/Nancy,albertjan/Nancy,malikdiarra/Nancy,murador/Nancy,EliotJones/NancyTest,danbarua/Nancy,anton-gogolev/Nancy,tareq-s/Nancy,xt0rted/Nancy,ccellar/Nancy,felipeleusin/Nancy,fly19890211/Nancy,jeff-pang/Nancy,blairconrad/Nancy,lijunle/Nancy,tsdl2013/Nancy,blairconrad/Nancy,danbarua/Nancy,jongleur1983/Nancy,felipeleusin/Nancy,davidallyoung/Nancy,thecodejunkie/Nancy,damianh/Nancy,adamhathcock/Nancy,AIexandr/Nancy,xt0rted/Nancy,nicklv/Nancy,vladlopes/Nancy,jeff-pang/Nancy,tparnell8/Nancy,nicklv/Nancy,lijunle/Nancy,daniellor/Nancy,horsdal/Nancy,duszekmestre/Nancy,joebuschmann/Nancy,anton-gogolev/Nancy,sroylance/Nancy,guodf/Nancy,khellang/Nancy,EIrwin/Nancy,tareq-s/Nancy,sadiqhirani/Nancy,wtilton/Nancy,sroylance/Nancy,rudygt/Nancy,tsdl2013/Nancy,jongleur1983/Nancy,tareq-s/Nancy,damianh/Nancy,felipeleusin/Nancy,murador/Nancy,dbabox/Nancy,blairconrad/Nancy,Novakov/Nancy,phillip-haydon/Nancy,duszekmestre/Nancy,sloncho/Nancy,jmptrader/Nancy,thecodejunkie/Nancy,fly19890211/Nancy,joebuschmann/Nancy,adamhathcock/Nancy,phillip-haydon/Nancy,Worthaboutapig/Nancy,charleypeng/Nancy,asbjornu/Nancy,ayoung/Nancy,duszekmestre/Nancy,JoeStead/Nancy,dbabox/Nancy,asbjornu/Nancy,cgourlay/Nancy,MetSystem/Nancy,khellang/Nancy,dbabox/Nancy,thecodejunkie/Nancy,adamhathcock/Nancy,lijunle/Nancy,jeff-pang/Nancy,albertjan/Nancy,charleypeng/Nancy,ccellar/Nancy,jmptrader/Nancy,davidallyoung/Nancy,blairconrad/Nancy,wtilton/Nancy,felipeleusin/Nancy,Novakov/Nancy,AIexandr/Nancy,sadiqhirani/Nancy,NancyFx/Nancy,SaveTrees/Nancy,jmptrader/Nancy,ccellar/Nancy,danbarua/Nancy,lijunle/Nancy,dbolkensteyn/Nancy,jmptrader/Nancy,NancyFx/Nancy,EIrwin/Nancy,SaveTrees/Nancy,malikdiarra/Nancy,SaveTrees/Nancy,jongleur1983/Nancy,rudygt/Nancy,tparnell8/Nancy,cgourlay/Nancy,jongleur1983/Nancy,sroylance/Nancy,dbolkensteyn/Nancy,fly19890211/Nancy,Crisfole/Nancy,jonathanfoster/Nancy,VQComms/Nancy,EliotJones/NancyTest,nicklv/Nancy,VQComms/Nancy,grumpydev/Nancy,VQComms/Nancy,daniellor/Nancy,tsdl2013/Nancy,NancyFx/Nancy,adamhathcock/Nancy,murador/Nancy,malikdiarra/Nancy,anton-gogolev/Nancy,wtilton/Nancy,jchannon/Nancy,davidallyoung/Nancy,SaveTrees/Nancy,damianh/Nancy,MetSystem/Nancy,dbolkensteyn/Nancy,murador/Nancy,jchannon/Nancy,daniellor/Nancy,JoeStead/Nancy,Crisfole/Nancy,dbabox/Nancy,fly19890211/Nancy,EliotJones/NancyTest,vladlopes/Nancy,horsdal/Nancy,Worthaboutapig/Nancy,AlexPuiu/Nancy,charleypeng/Nancy,ccellar/Nancy,AcklenAvenue/Nancy,tsdl2013/Nancy,horsdal/Nancy,MetSystem/Nancy,jchannon/Nancy,Novakov/Nancy,EIrwin/Nancy,joebuschmann/Nancy,nicklv/Nancy,grumpydev/Nancy,asbjornu/Nancy,hitesh97/Nancy,xt0rted/Nancy,AIexandr/Nancy,wtilton/Nancy,EIrwin/Nancy,VQComms/Nancy,phillip-haydon/Nancy,grumpydev/Nancy,jeff-pang/Nancy,AcklenAvenue/Nancy,jonathanfoster/Nancy,guodf/Nancy,Crisfole/Nancy,tparnell8/Nancy,khellang/Nancy,JoeStead/Nancy,hitesh97/Nancy,cgourlay/Nancy,AcklenAvenue/Nancy,phillip-haydon/Nancy,malikdiarra/Nancy,dbolkensteyn/Nancy,sloncho/Nancy
src/Nancy.ViewEngines.Razor/EncodedHtmlString.cs
src/Nancy.ViewEngines.Razor/EncodedHtmlString.cs
namespace Nancy.ViewEngines.Razor { using System; using Nancy.Helpers; /// <summary> /// An html string that is encoded. /// </summary> public class EncodedHtmlString : IHtmlString { /// <summary> /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly. /// </summary> public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty); private readonly string encodedValue; /// <summary> /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class. /// </summary> /// <param name="value">The encoded value.</param> public EncodedHtmlString(string value) { encodedValue = HttpUtility.HtmlEncode(value); } /// <summary> /// Returns an HTML-encoded string. /// </summary> /// <returns>An HTML-encoded string.</returns> public string ToHtmlString() { return encodedValue; } public static implicit operator EncodedHtmlString(string value) { return new EncodedHtmlString(value); } } }
using System; using Nancy.Helpers; namespace Nancy.ViewEngines.Razor { /// <summary> /// An html string that is encoded. /// </summary> public class EncodedHtmlString : IHtmlString { /// <summary> /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly. /// </summary> public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty); private readonly Lazy<string> encoderFactory; /// <summary> /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class. /// </summary> /// <param name="value">The value.</param> public EncodedHtmlString(string value) { encoderFactory = new Lazy<string>(() => HttpUtility.HtmlEncode(value)); } /// <summary> /// Returns an HTML-encoded string. /// </summary> /// <returns>An HTML-encoded string.</returns> public string ToHtmlString() { return encoderFactory.Value; } public static implicit operator EncodedHtmlString(string value) { return new EncodedHtmlString(value); } } }
mit
C#
1ea4781188c8614684650bd8afa6504435320f3c
Fix code styling
NeoAdonis/osu,peppy/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,DrabWeb/osu,DrabWeb/osu,smoogipooo/osu,2yangk23/osu,2yangk23/osu,DrabWeb/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,johnneijzen/osu,UselessToucan/osu,ZLima12/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,ZLima12/osu,EVAST9919/osu
osu.Game.Rulesets.Catch.Tests/TestCaseHyperDash.cs
osu.Game.Rulesets.Catch.Tests/TestCaseHyperDash.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Screens.Play; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestCaseHyperDash : Game.Tests.Visual.TestCasePlayer { public TestCaseHyperDash() : base(new CatchRuleset()) { } protected override IBeatmap CreateBeatmap(Ruleset ruleset) { var beatmap = new Beatmap { BeatmapInfo = { Ruleset = ruleset.RulesetInfo, BaseDifficulty = new BeatmapDifficulty { CircleSize = 3.6f } } }; // Should produce a hperdash beatmap.HitObjects.Add(new Fruit { StartTime = 816, X = 308 / 512f, NewCombo = true }); beatmap.HitObjects.Add(new Fruit { StartTime = 1008, X = 56 / 512f, }); for (int i = 0; i < 512; i++) if (i % 5 < 3) beatmap.HitObjects.Add(new Fruit { X = i % 10 < 5 ? 0.02f : 0.98f, StartTime = 2000 + i * 100, NewCombo = i % 8 == 0 }); return beatmap; } protected override void AddCheckSteps(Func<Player> player) { base.AddCheckSteps(player); AddAssert("First note is hyperdash", () => Beatmap.Value.Beatmap.HitObjects[0] is Fruit f && f.HyperDash); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Screens.Play; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestCaseHyperDash : Game.Tests.Visual.TestCasePlayer { public TestCaseHyperDash() : base(new CatchRuleset()) { } protected override IBeatmap CreateBeatmap(Ruleset ruleset) { var beatmap = new Beatmap { BeatmapInfo = { Ruleset = ruleset.RulesetInfo, BaseDifficulty = new BeatmapDifficulty { CircleSize = 3.6f } } }; // Should produce a hperdash beatmap.HitObjects.Add(new Fruit { StartTime = 816, X = 308 / 512f, NewCombo = true }); beatmap.HitObjects.Add(new Fruit { StartTime = 1008, X = 56 / 512f, }); for (int i = 0; i < 512; i++) if (i % 5 < 3) beatmap.HitObjects.Add(new Fruit { X = i % 10 < 5 ? 0.02f : 0.98f, StartTime = 2000 + i * 100, NewCombo = i % 8 == 0 }); return beatmap; } protected override void AddCheckSteps(Func<Player> player) { base.AddCheckSteps(player); AddAssert("First note is hyperdash", () => Beatmap.Value.Beatmap.HitObjects[0] is Fruit f && f.HyperDash); } } }
mit
C#
b32d6017ab2168cad0654518c1ff9eb32b7b7ae8
Add case for locked files
Microsoft/Vipr
src/Core/Vipr/FileWriter.cs
src/Core/Vipr/FileWriter.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Vipr.Core; namespace Vipr { internal static class FileWriter { public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null) { if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath)) Directory.CreateDirectory(outputDirectoryPath); var fileTasks = new List<Task>(); foreach (var file in textFilesToWrite) { var filePath = file.RelativePath; if (!string.IsNullOrWhiteSpace(outputDirectoryPath)) filePath = Path.Combine(outputDirectoryPath, filePath); if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) && !Path.IsPathRooted(filePath)) filePath = Path.Combine(Environment.CurrentDirectory, filePath); if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); fileTasks.Add(WriteToDisk(filePath, file.Contents)); } await Task.WhenAll(fileTasks); } /** * Write the file to disk. If the file is locked for editing, * sleep until available */ public static async Task WriteToDisk(string filePath, string output) { for (int tries = 0; tries < 10; tries++) { StreamWriter sw = null; try { using (sw = new StreamWriter(filePath, false, Encoding.UTF8)) { await sw.WriteAsync(output); break; } } // If the file is currently locked for editing, sleep // This shouldn't be hit if the generator is running correctly, // however, files are currently being overwritten several times catch (IOException) { Thread.Sleep(5); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Vipr.Core; namespace Vipr { internal static class FileWriter { public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null) { if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath)) Directory.CreateDirectory(outputDirectoryPath); var fileTasks = new List<Task>(); foreach (var file in textFilesToWrite) { var filePath = file.RelativePath; if (!string.IsNullOrWhiteSpace(outputDirectoryPath)) filePath = Path.Combine(outputDirectoryPath, filePath); if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) && !Path.IsPathRooted(filePath)) filePath = Path.Combine(Environment.CurrentDirectory, filePath); if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); fileTasks.Add(WriteToDisk(filePath, file.Contents)); } await Task.WhenAll(fileTasks); } public static async Task WriteToDisk(string filePath, string output) { StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8); await sw.WriteAsync(output); sw.Close(); } } }
mit
C#
45c1f0d453662fa1a13b92aeabaddbc3effc9f33
Improve Caliburn.Micro compatibility for multiple views
JPVenson/ConfuserEx,mirbegtlax/ConfuserEx,AgileJoshua/ConfuserEx,manojdjoshi/ConfuserEx,engdata/ConfuserEx,jbeshir/ConfuserEx,JPVenson/ConfuserEx,mirbegtlax/ConfuserEx,arpitpanwar/ConfuserEx,timnboys/ConfuserEx,yuligang1234/ConfuserEx,MetSystem/ConfuserEx,yeaicc/ConfuserEx,Desolath/ConfuserEx3,fretelweb/ConfuserEx,HalidCisse/ConfuserEx,KKKas/ConfuserEx,modulexcite/ConfuserEx,farmaair/ConfuserEx,HalidCisse/ConfuserEx,Desolath/Confuserex,Immortal-/ConfuserEx,apexrichard/ConfuserEx,yuligang1234/ConfuserEx
Confuser.Renamer/Analyzers/CaliburnAnalyzer.cs
Confuser.Renamer/Analyzers/CaliburnAnalyzer.cs
using System; using System.Text.RegularExpressions; using Confuser.Core; using Confuser.Renamer.BAML; using dnlib.DotNet; namespace Confuser.Renamer.Analyzers { internal class CaliburnAnalyzer : IRenamer { public CaliburnAnalyzer(WPFAnalyzer wpfAnalyzer) { wpfAnalyzer.AnalyzeBAMLElement += AnalyzeBAMLElement; } public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { var type = def as TypeDef; if (type == null || type.DeclaringType != null) return; if (type.Name.Contains("ViewModel")) { string viewNs = type.Namespace.Replace("ViewModels", "Views"); string viewName = type.Name.Replace("PageViewModel", "Page").Replace("ViewModel", "View"); TypeDef view = type.Module.Find(viewNs + "." + viewName, true); if (view != null) { service.SetCanRename(type, false); service.SetCanRename(view, false); } // Test for Multi-view string multiViewNs = type.Namespace + "." + type.Name.Replace("ViewModel", ""); foreach (var t in type.Module.Types) if (t.Namespace == multiViewNs) { service.SetCanRename(type, false); service.SetCanRename(t, false); } } } private void AnalyzeBAMLElement(BAMLAnalyzer analyzer, BamlElement elem) { foreach (var rec in elem.Body) { var prop = rec as PropertyWithConverterRecord; if (prop == null) continue; var attr = analyzer.ResolveAttribute(prop.AttributeId); if (attr.Item2 == null || attr.Item2.Name != "Attach") continue; var attrDeclType = analyzer.ResolveType(attr.Item2.OwnerTypeId); if (attrDeclType.FullName != "Caliburn.Micro.Message") continue; string actionStr = prop.Value; foreach (var msg in actionStr.Split(';')) { string msgStr; if (msg.Contains("=")) { msgStr = msg.Split('=')[1].Trim('[', ']', ' '); } else { msgStr = msg.Trim('[', ']', ' '); } if (msgStr.StartsWith("Action")) msgStr = msgStr.Substring(6); int parenIndex = msgStr.IndexOf('('); if (parenIndex != -1) msgStr = msgStr.Substring(0, parenIndex); string actName = msgStr.Trim(); foreach (var method in analyzer.LookupMethod(actName)) analyzer.NameService.SetCanRename(method, false); } } } public void PreRename(ConfuserContext context, INameService service, IDnlibDef def) { // } public void PostRename(ConfuserContext context, INameService service, IDnlibDef def) { // } } }
using System; using System.Text.RegularExpressions; using Confuser.Core; using Confuser.Renamer.BAML; using dnlib.DotNet; namespace Confuser.Renamer.Analyzers { internal class CaliburnAnalyzer : IRenamer { public CaliburnAnalyzer(WPFAnalyzer wpfAnalyzer) { wpfAnalyzer.AnalyzeBAMLElement += AnalyzeBAMLElement; } public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { var type = def as TypeDef; if (type == null || type.DeclaringType != null) return; if (type.Name.Contains("ViewModel")) { string viewNs = type.Namespace.Replace("ViewModels", "Views"); string viewName = type.Name.Replace("PageViewModel", "Page").Replace("ViewModel", "View"); TypeDef view = type.Module.Find(viewNs + "." + viewName, true); if (view != null) { service.SetCanRename(type, false); service.SetCanRename(view, false); } } } private void AnalyzeBAMLElement(BAMLAnalyzer analyzer, BamlElement elem) { foreach (var rec in elem.Body) { var prop = rec as PropertyWithConverterRecord; if (prop == null) continue; var attr = analyzer.ResolveAttribute(prop.AttributeId); if (attr.Item2 == null || attr.Item2.Name != "Attach") continue; var attrDeclType = analyzer.ResolveType(attr.Item2.OwnerTypeId); if (attrDeclType.FullName != "Caliburn.Micro.Message") continue; string actionStr = prop.Value; foreach (var msg in actionStr.Split(';')) { string msgStr; if (msg.Contains("=")) { msgStr = msg.Split('=')[1].Trim('[', ']', ' '); } else { msgStr = msg.Trim('[', ']', ' '); } if (msgStr.StartsWith("Action")) msgStr = msgStr.Substring(6); int parenIndex = msgStr.IndexOf('('); if (parenIndex != -1) msgStr = msgStr.Substring(0, parenIndex); string actName = msgStr.Trim(); foreach (var method in analyzer.LookupMethod(actName)) analyzer.NameService.SetCanRename(method, false); } } } public void PreRename(ConfuserContext context, INameService service, IDnlibDef def) { // } public void PostRename(ConfuserContext context, INameService service, IDnlibDef def) { // } } }
mit
C#
b82fc3350fcf4b0bd2d730d310d2638927e38db9
Set default UmbracoConnectionString value
umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS
src/Umbraco.Core/Configuration/Models/ConnectionStrings.cs
src/Umbraco.Core/Configuration/Models/ConnectionStrings.cs
// Copyright (c) Umbraco. // See LICENSE for more details. namespace Umbraco.Cms.Core.Configuration.Models { /// <summary> /// Typed configuration options for connection strings. /// </summary> [UmbracoOptions("ConnectionStrings", BindNonPublicProperties = true)] public class ConnectionStrings { // Backing field for UmbracoConnectionString to load from configuration value with key umbracoDbDSN. // Attributes cannot be applied to map from keys that don't match, and have chosen to retain the key name // used in configuration for older Umbraco versions. // See: https://stackoverflow.com/a/54607296/489433 #pragma warning disable SA1300 // Element should begin with upper-case letter #pragma warning disable IDE1006 // Naming Styles private string umbracoDbDSN #pragma warning restore IDE1006 // Naming Styles #pragma warning restore SA1300 // Element should begin with upper-case letter { get => UmbracoConnectionString?.ConnectionString; set => UmbracoConnectionString = new ConfigConnectionString(Constants.System.UmbracoConnectionName, value); } /// <summary> /// Gets or sets a value for the Umbraco database connection string.. /// </summary> public ConfigConnectionString UmbracoConnectionString { get; set; } = new ConfigConnectionString(Constants.System.UmbracoConnectionName, null); } }
// Copyright (c) Umbraco. // See LICENSE for more details. namespace Umbraco.Cms.Core.Configuration.Models { /// <summary> /// Typed configuration options for connection strings. /// </summary> [UmbracoOptions("ConnectionStrings", BindNonPublicProperties = true)] public class ConnectionStrings { // Backing field for UmbracoConnectionString to load from configuration value with key umbracoDbDSN. // Attributes cannot be applied to map from keys that don't match, and have chosen to retain the key name // used in configuration for older Umbraco versions. // See: https://stackoverflow.com/a/54607296/489433 #pragma warning disable SA1300 // Element should begin with upper-case letter #pragma warning disable IDE1006 // Naming Styles private string umbracoDbDSN #pragma warning restore IDE1006 // Naming Styles #pragma warning restore SA1300 // Element should begin with upper-case letter { get => UmbracoConnectionString?.ConnectionString; set => UmbracoConnectionString = new ConfigConnectionString(Constants.System.UmbracoConnectionName, value); } /// <summary> /// Gets or sets a value for the Umbraco database connection string.. /// </summary> public ConfigConnectionString UmbracoConnectionString { get; set; } } }
mit
C#
86fb5d8a263e846357cc297b73573afaefb7a681
Update AzureFileStorageTests.cs
A51UK/File-Repository
File-Repository-Tests/AzureFileStorageTests.cs
File-Repository-Tests/AzureFileStorageTests.cs
/* * Copyright 2017 Craig Lee Mark Adams Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * * */ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; namespace ile_Repository_Tests { [TestClass] public class AzureFileStorageTests { } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; namespace ile_Repository_Tests { [TestClass] public class AzureFileStorageTests { } }
apache-2.0
C#
6b8ef40129c1c258e67ad0d767c1e113b52b98b2
Tweak benchmarks, still don't trust the results.
JohanLarsson/Gu.Analyzers
Gu.Analyzers.Benchmarks/Benchmarks/Analyzer.cs
Gu.Analyzers.Benchmarks/Benchmarks/Analyzer.cs
namespace Gu.Analyzers.Benchmarks.Benchmarks { using System.Collections.Immutable; using System.Threading; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Diagnostics; public abstract class Analyzer { private readonly CompilationWithAnalyzers compilation; protected Analyzer(DiagnosticAnalyzer analyzer) { var project = Factory.CreateProject(analyzer); this.compilation = project.GetCompilationAsync(CancellationToken.None) .Result .WithAnalyzers( ImmutableArray.Create(analyzer), project.AnalyzerOptions, CancellationToken.None); } [Benchmark] public object GetAnalyzerDiagnosticsAsync() { return this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None).Result; } } }
namespace Gu.Analyzers.Benchmarks.Benchmarks { using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Diagnostics; public abstract class Analyzer { private readonly CompilationWithAnalyzers compilation; protected Analyzer(DiagnosticAnalyzer analyzer) { var project = Factory.CreateProject(analyzer); this.compilation = project.GetCompilationAsync(CancellationToken.None) .Result .WithAnalyzers( ImmutableArray.Create(analyzer), project.AnalyzerOptions, CancellationToken.None); } [Benchmark] public async Task<object> GetAnalyzerDiagnosticsAsync() { return await this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None) .ConfigureAwait(false); } } }
mit
C#
5d651aa81fcfad1456e8cff1869718459a6d234c
Update TextHitTest.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D.Editor/Bounds/Shapes/TextHitTest.cs
src/Draw2D.Editor/Bounds/Shapes/TextHitTest.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Draw2D.Core; using Draw2D.Core.Shapes; using Draw2D.Spatial; namespace Draw2D.Editor.Bounds.Shapes { public class TextHitTest : BoxHitTest { public override Type TargetType => typeof(TextShape); } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Draw2D.Core; using Draw2D.Core.Shapes; using Draw2D.Spatial; namespace Draw2D.Editor.Bounds.Shapes { public class TextHitTest : HitTestBase { public override Type TargetType => typeof(TextShape); public override PointShape TryToGetPoint(ShapeObject shape, Point2 target, double radius, IHitTest hitTest) { var text = shape as TextShape; if (text == null) throw new ArgumentNullException("shape"); var pointHitTest = hitTest.Registered[typeof(PointShape)]; if (pointHitTest.TryToGetPoint(text.TopLeft, target, radius, hitTest) != null) { return text.TopLeft; } if (pointHitTest.TryToGetPoint(text.BottomRight, target, radius, hitTest) != null) { return text.BottomRight; } foreach (var point in text.Points) { if (pointHitTest.TryToGetPoint(point, target, radius, hitTest) != null) { return point; } } return null; } public override ShapeObject Contains(ShapeObject shape, Point2 target, double radius, IHitTest hitTest) { var text = shape as TextShape; if (text == null) throw new ArgumentNullException("shape"); return Rect2.FromPoints( text.TopLeft.X, text.TopLeft.Y, text.BottomRight.X, text.BottomRight.Y).Contains(target) ? shape : null; } public override ShapeObject Overlaps(ShapeObject shape, Rect2 target, double radius, IHitTest hitTest) { var text = shape as TextShape; if (text == null) throw new ArgumentNullException("shape"); return Rect2.FromPoints( text.TopLeft.X, text.TopLeft.Y, text.BottomRight.X, text.BottomRight.Y).IntersectsWith(target) ? shape : null; } } }
mit
C#
498dad9cf8df75a39c62cadec4d55625fb6c9928
Make ConnectionDetails a struct.
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.Exports/Models/ConnectionDetails.cs
src/GitHub.Exports/Models/ConnectionDetails.cs
using System; using GitHub.Primitives; using GitHub.Services; namespace GitHub.Models { /// <summary> /// Represents details about a connection stored in an <see cref="IConnectionCache"/>. /// </summary> public struct ConnectionDetails : IEquatable<ConnectionDetails> { /// <summary> /// Initializes a new instance of the <see cref="ConnectionDetails"/> struct. /// </summary> /// <param name="hostAddress">The address of the host.</param> /// <param name="userName">The username for the host.</param> public ConnectionDetails(string hostAddress, string userName) { HostAddress = HostAddress.Create(hostAddress); UserName = userName; } /// <summary> /// Initializes a new instance of the <see cref="ConnectionDetails"/> struct. /// </summary> /// <param name="hostAddress">The address of the host.</param> /// <param name="userName">The username for the host.</param> public ConnectionDetails(HostAddress hostAddress, string userName) { HostAddress = hostAddress; UserName = userName; } /// <summary> /// Gets the address of the host. /// </summary> public HostAddress HostAddress { get; } /// <summary> /// Gets the username for the host. /// </summary> public string UserName { get; } public bool Equals(ConnectionDetails other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return HostAddress.Equals(other.HostAddress) && string.Equals(UserName, other.UserName, StringComparison.OrdinalIgnoreCase); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == this.GetType() && Equals((ConnectionDetails)obj); } public override int GetHashCode() { unchecked { return (HostAddress.GetHashCode()*397) ^ StringComparer.InvariantCultureIgnoreCase.GetHashCode(UserName); } } public static bool operator ==(ConnectionDetails left, ConnectionDetails right) { return Equals(left, right); } public static bool operator !=(ConnectionDetails left, ConnectionDetails right) { return !Equals(left, right); } } }
using System; using GitHub.Primitives; namespace GitHub.Models { public class ConnectionDetails : IEquatable<ConnectionDetails> { public ConnectionDetails(string hostAddress, string userName) { HostAddress = HostAddress.Create(hostAddress); UserName = userName; } public ConnectionDetails(HostAddress hostAddress, string userName) { HostAddress = hostAddress; UserName = userName; } public HostAddress HostAddress { get; } public string UserName { get; } public bool Equals(ConnectionDetails other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return HostAddress.Equals(other.HostAddress) && string.Equals(UserName, other.UserName, StringComparison.OrdinalIgnoreCase); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == this.GetType() && Equals((ConnectionDetails)obj); } public override int GetHashCode() { unchecked { return (HostAddress.GetHashCode()*397) ^ StringComparer.InvariantCultureIgnoreCase.GetHashCode(UserName); } } public static bool operator ==(ConnectionDetails left, ConnectionDetails right) { return Equals(left, right); } public static bool operator !=(ConnectionDetails left, ConnectionDetails right) { return !Equals(left, right); } } }
mit
C#
bb34e17bd35a9e22b2fdc1136e44c99e986df4c4
Reorder visitors to prioritize more common expression types
dsharlet/ComputerAlgebra
ComputerAlgebra/Expression/Visitors/Visitor.cs
ComputerAlgebra/Expression/Visitors/Visitor.cs
namespace ComputerAlgebra { /// <summary> /// Visits an expression. /// </summary> /// <typeparam name="T">Result type of the visitor.</typeparam> public abstract class ExpressionVisitor<T> { protected abstract T VisitUnknown(Expression E); protected virtual T VisitSum(Sum A) { return VisitUnknown(A); } protected virtual T VisitProduct(Product M) { return VisitUnknown(M); } protected virtual T VisitConstant(Constant C) { return VisitUnknown(C); } protected virtual T VisitVariable(Variable V) { return VisitUnknown(V); } protected virtual T VisitSet(Set S) { return VisitUnknown(S); } protected virtual T VisitBinary(Binary B) { return VisitUnknown(B); } protected virtual T VisitUnary(Unary U) { return VisitUnknown(U); } protected virtual T VisitPower(Power P) { return VisitBinary(P); } protected virtual T VisitCall(Call F) { return VisitUnknown(F); } protected virtual T VisitMatrix(Matrix A) { return VisitUnknown(A); } protected virtual T VisitIndex(Index I) { return VisitUnknown(I); } public virtual T Visit(Expression E) { if (E is Sum sum) return VisitSum(sum); else if (E is Product product) return VisitProduct(product); else if (E is Constant constant) return VisitConstant(constant); else if (E is Call call) return VisitCall(call); else if (E is Variable variable) return VisitVariable(variable); else if (E is Power power) return VisitPower(power); else if (E is Binary binary) return VisitBinary(binary); else if (E is Unary unary) return VisitUnary(unary); else if (E is Index index) return VisitIndex(index); else if (E is Matrix matrix) return VisitMatrix(matrix); else if (E is Set set) return VisitSet(set); else return VisitUnknown(E); } } }
namespace ComputerAlgebra { /// <summary> /// Visits an expression. /// </summary> /// <typeparam name="T">Result type of the visitor.</typeparam> public abstract class ExpressionVisitor<T> { protected abstract T VisitUnknown(Expression E); protected virtual T VisitSum(Sum A) { return VisitUnknown(A); } protected virtual T VisitProduct(Product M) { return VisitUnknown(M); } protected virtual T VisitConstant(Constant C) { return VisitUnknown(C); } protected virtual T VisitVariable(Variable V) { return VisitUnknown(V); } protected virtual T VisitSet(Set S) { return VisitUnknown(S); } protected virtual T VisitBinary(Binary B) { return VisitUnknown(B); } protected virtual T VisitUnary(Unary U) { return VisitUnknown(U); } protected virtual T VisitPower(Power P) { return VisitBinary(P); } protected virtual T VisitCall(Call F) { return VisitUnknown(F); } protected virtual T VisitMatrix(Matrix A) { return VisitUnknown(A); } protected virtual T VisitIndex(Index I) { return VisitUnknown(I); } public virtual T Visit(Expression E) { if (E is Sum sum) return VisitSum(sum); else if (E is Product product) return VisitProduct(product); else if (E is Constant constant) return VisitConstant(constant); else if (E is Variable variable) return VisitVariable(variable); else if (E is Set set) return VisitSet(set); else if (E is Power power) return VisitPower(power); else if (E is Binary binary) return VisitBinary(binary); else if (E is Unary unary) return VisitUnary(unary); else if (E is Call call) return VisitCall(call); else if (E is Matrix matrix) return VisitMatrix(matrix); else if (E is Index index) return VisitIndex(index); else return VisitUnknown(E); } } }
mit
C#
0ce8213aeea5fce87de43d9811166b2f69b85e9d
Bump to 1.4.3
mhutch/MonoDevelop.AddinMaker,mhutch/MonoDevelop.AddinMaker
MonoDevelop.AddinMaker/Properties/AddinInfo.cs
MonoDevelop.AddinMaker/Properties/AddinInfo.cs
using Mono.Addins; using Mono.Addins.Description; [assembly: Addin ( "AddinMaker", Namespace = "MonoDevelop", Version = "1.4.3", Url = "http://github.com/mhutch/MonoDevelop.AddinMaker" )] [assembly: AddinName ("AddinMaker")] [assembly: AddinCategory ("Extension Development")] [assembly: AddinDescription ("Makes it easy to create and edit IDE extensions")] [assembly: AddinAuthor ("Mikayla Hutchinson")]
using Mono.Addins; using Mono.Addins.Description; [assembly: Addin ( "AddinMaker", Namespace = "MonoDevelop", Version = "1.4.2", Url = "http://github.com/mhutch/MonoDevelop.AddinMaker" )] [assembly: AddinName ("AddinMaker")] [assembly: AddinCategory ("Extension Development")] [assembly: AddinDescription ("Makes it easy to create and edit IDE extensions")] [assembly: AddinAuthor ("Mikayla Hutchinson")]
mit
C#
be54b7e54d0bfee5e5350fba1ce27209d1665187
Remove code task
roman-yagodin/R7.News,roman-yagodin/R7.News,roman-yagodin/R7.News
R7.News/Integrations/UniversityDivisionInfo.cs
R7.News/Integrations/UniversityDivisionInfo.cs
// // UniversityDivisionInfo.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using DotNetNuke.ComponentModel.DataAnnotations; namespace R7.News.Integrations { [TableName ("University_Divisions")] [PrimaryKey ("DivisionID", AutoIncrement = false)] public class UniversityDivisionInfo { public int DivisionID { get; set; } public string Title { get; set; } public string HomePage { get; set; } public int? DivisionTermId { get; set; } } }
// // UniversityDivisionInfo.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using DotNetNuke.ComponentModel.DataAnnotations; namespace R7.News.Integrations { // TODO: Move to separate assembly? [TableName ("University_Divisions")] [PrimaryKey ("DivisionID", AutoIncrement = false)] public class UniversityDivisionInfo { public int DivisionID { get; set; } public string Title { get; set; } public string HomePage { get; set; } public int? DivisionTermId { get; set; } } }
agpl-3.0
C#
f54fcfd563723d202dd5f977a5f85ea22a5350a9
Update PaginableExtensions.cs
neekgreen/PaginableCollections,neekgreen/PaginableCollections
src/PaginableCollections/PaginableExtensions.cs
src/PaginableCollections/PaginableExtensions.cs
namespace PaginableCollections { using System.Collections.Generic; using System.Linq; public static class PaginableExtensions { /// <summary> /// Convert queryable to paginable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <param name="pageNumber"></param> /// <param name="itemCountPerPage"></param> /// <returns></returns> public static IPaginable<T> ToPaginable<T>(this IQueryable<T> queryable, int pageNumber, int itemCountPerPage) { return new QueryableBasedPaginable<T>(queryable, pageNumber, itemCountPerPage); } /// <summary> /// Convert queryable to paginable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <param name="paginableInfo"></param> /// <returns></returns> public static IPaginable<T> ToPaginable<T>(this IQueryable<T> queryable, IPaginableRequest paginableRequest) { return queryable.ToPaginable(paginableRequest.PageNumber, paginableRequest.ItemCountPerPage); } /// <summary> /// /// </summary> /// <param name="paginable"></param> /// <param name="maximumPageNumberCount"></param> /// <returns></returns> public static IPager ToPager(this IPaginable paginable, int maximumPageNumberCount) { return new StaticPager(paginable, maximumPageNumberCount); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <param name="pageNumber"></param> /// <param name="itemCountPerPage"></param> /// <returns></returns> internal static IEnumerable<IPaginableItem<T>> ToPaginableItemList<T>(this IEnumerable<T> t, int pageNumber, int itemCountPerPage) { var offset = (pageNumber - 1) * itemCountPerPage; var list = t as IList<T> ?? t.ToList(); for (var i = 0; i < list.Count; i++) { yield return new PaginableItem<T>(list[i], offset + 1); offset++; } } } }
namespace PaginableCollections { using System.Collections.Generic; using System.Linq; public static class PaginableExtensions { /// <summary> /// Convert queryable to paginable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <param name="pageNumber"></param> /// <param name="itemCountPerPage"></param> /// <returns></returns> public static IPaginable<T> ToPaginable<T>(this IQueryable<T> queryable, int pageNumber, int itemCountPerPage) { return new QueryableBasedPaginable<T>(queryable, pageNumber, itemCountPerPage); } /// <summary> /// Convert queryable to paginable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable"></param> /// <param name="paginableInfo"></param> /// <returns></returns> public static IPaginable<T> ToPaginable<T>(this IQueryable<T> queryable, IPaginableRequest paginableInfo) { return queryable.ToPaginable(paginableInfo.PageNumber, paginableInfo.ItemCountPerPage); } /// <summary> /// /// </summary> /// <param name="paginable"></param> /// <param name="maximumPageNumberCount"></param> /// <returns></returns> public static IPager ToPager(this IPaginable paginable, int maximumPageNumberCount) { return new StaticPager(paginable, maximumPageNumberCount); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <param name="pageNumber"></param> /// <param name="itemCountPerPage"></param> /// <returns></returns> internal static IEnumerable<IPaginableItem<T>> ToPaginableItemList<T>(this IEnumerable<T> t, int pageNumber, int itemCountPerPage) { var offset = (pageNumber - 1) * itemCountPerPage; var list = t as IList<T> ?? t.ToList(); for (var i = 0; i < list.Count; i++) { yield return new PaginableItem<T>(list[i], offset + 1); offset++; } } } }
mit
C#
36fed0c9c1c955f3b43f6e13c5cb336b3f71874e
Make PubSub/SimpleDispatchStrategy more thread-safe
Whiteknight/Acquaintance,Whiteknight/Acquaintance
Acquaintance/PubSub/SimpleDispatchStrategy.cs
Acquaintance/PubSub/SimpleDispatchStrategy.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Acquaintance.PubSub { public class SimpleDispatchStrategy : IPubSubChannelDispatchStrategy { private readonly ConcurrentDictionary<string, IPubSubChannel> _pubSubChannels; public SimpleDispatchStrategy() { _pubSubChannels = new ConcurrentDictionary<string, IPubSubChannel>(); } private string GetPubSubKey(Type type, string name) { return $"Type={type.AssemblyQualifiedName}:Name={name ?? string.Empty}"; } public IPubSubChannel<TPayload> GetChannelForSubscription<TPayload>(string name) { string key = GetPubSubKey(typeof(TPayload), name); if (!_pubSubChannels.ContainsKey(key)) _pubSubChannels.TryAdd(key, new PubSubChannel<TPayload>()); var channel = _pubSubChannels[key] as IPubSubChannel<TPayload>; if (channel == null) throw new Exception("Channel has incorrect type"); return channel; } public IEnumerable<IPubSubChannel<TPayload>> GetExistingChannels<TPayload>(string name) { string key = GetPubSubKey(typeof(TPayload), name); if (!_pubSubChannels.ContainsKey(key)) return Enumerable.Empty<IPubSubChannel<TPayload>>(); var channel = _pubSubChannels[key] as IPubSubChannel<TPayload>; if (channel == null) return Enumerable.Empty<IPubSubChannel<TPayload>>(); return new[] { channel }; } public void Dispose() { foreach (var channel in _pubSubChannels.Values) channel.Dispose(); _pubSubChannels.Clear(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Acquaintance.PubSub { public class SimpleDispatchStrategy : IPubSubChannelDispatchStrategy { private readonly Dictionary<string, IPubSubChannel> _pubSubChannels; public SimpleDispatchStrategy() { _pubSubChannels = new Dictionary<string, IPubSubChannel>(); } private string GetPubSubKey(Type type, string name) { return $"Type={type.AssemblyQualifiedName}:Name={name ?? string.Empty}"; } public IPubSubChannel<TPayload> GetChannelForSubscription<TPayload>(string name) { string key = GetPubSubKey(typeof(TPayload), name); if (!_pubSubChannels.ContainsKey(key)) _pubSubChannels.Add(key, new PubSubChannel<TPayload>()); var channel = _pubSubChannels[key] as IPubSubChannel<TPayload>; if (channel == null) throw new Exception("Channel has incorrect type"); return channel; } public IEnumerable<IPubSubChannel<TPayload>> GetExistingChannels<TPayload>(string name) { string key = GetPubSubKey(typeof(TPayload), name); if (!_pubSubChannels.ContainsKey(key)) return Enumerable.Empty<IPubSubChannel<TPayload>>(); var channel = _pubSubChannels[key] as IPubSubChannel<TPayload>; if (channel == null) return Enumerable.Empty<IPubSubChannel<TPayload>>(); return new[] { channel }; } public void Dispose() { foreach (var channel in _pubSubChannels.Values) channel.Dispose(); _pubSubChannels.Clear(); } } }
apache-2.0
C#
6cecca57a5159b665276f52129b54d89f48144c7
Update gradient descent sample.
alexshtf/autodiff
AutoDiff/Samples/GradientDescentSample/Program.cs
AutoDiff/Samples/GradientDescentSample/Program.cs
using System; using AutoDiff; namespace GradientDescentSample { class Program { static void Main(string[] args) { var x = new Variable(); var y = new Variable(); var z = new Variable(); // f(x, y, z) = (x-2)² + (y+4)² + (z-1)² // the min should be (x, y, z) = (2, -4, 1) var func = TermBuilder.Power(x - 2, 2) + TermBuilder.Power(y + 4, 2) + TermBuilder.Power(z - 1, 2); var compiled = func.Compile(x, y, z); // perform optimization var vec = new double[3]; vec = GradientDescent(compiled, vec, stepSize: 0.01, iterations: 1000); Console.WriteLine("The approx. minimizer is: {0}, {1}, {2}", vec[0], vec[1], vec[2]); } static double[] GradientDescent(ICompiledTerm func, double[] init, double stepSize, int iterations) { // clone the initial argument var x = (double[])init.Clone(); var gradient = new double[x.Length]; // perform the iterations for (int i = 0; i < iterations; ++i) { // compute the gradient - fill the gradient array func.Differentiate(x, gradient); // perform a descent step for (int j = 0; j < x.Length; ++j) x[j] -= stepSize * gradient[j]; } return x; } } }
using System; using AutoDiff; namespace GradientDescentSample { class Program { static void Main(string[] args) { var x = new Variable(); var y = new Variable(); var z = new Variable(); // f(x, y, z) = (x-2)² + (y+4)² + (z-1)² // the min should be (x, y, z) = (2, -4, 1) var func = TermBuilder.Power(x - 2, 2) + TermBuilder.Power(y + 4, 2) + TermBuilder.Power(z - 1, 2); var compiled = func.Compile(x, y, z); // perform optimization var vec = new double[3]; vec = GradientDescent(compiled, vec, stepSize: 0.01, iterations: 1000); Console.WriteLine("The approx. minimizer is: {0}, {1}, {2}", vec[0], vec[1], vec[2]); } static double[] GradientDescent(ICompiledTerm func, double[] init, double stepSize, int iterations) { // clone the initial argument var x = (double[])init.Clone(); // perform the iterations for (int i = 0; i < iterations; ++i) { // compute the gradient var gradient = func.Differentiate(x).Item1; // perform a descent step for (int j = 0; j < x.Length; ++j) x[j] -= stepSize * gradient[j]; } return x; } } }
mit
C#
ca09b56d72a4a84b2ba883c06b4de9ffc0ce8796
Update for April 2017 release
OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core
Core/OfficeDevPnP.Core/Properties/AssemblyInfo.cs
Core/OfficeDevPnP.Core/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OfficeDevPnP.Core")] #if SP2013 [assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2013")] #elif SP2016 [assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2016")] #else [assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint Online")] #endif [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OfficeDevPnP.Core")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] // 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("065331b6-0540-44e1-84d5-d38f09f17f9e")] // 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: // Convention: // Major version = current version 2 // Minor version = Sequence...version 0 was with January release...so 1=Feb 2=Mar, 3=Apr, 4=May, 5=Jun, 6=Aug, 7=Sept,...11=Jan 2017 // Third part = version indenpendant showing the release month in YYMM // Fourth part = 0 normally or a sequence number when we do an emergency release [assembly: AssemblyVersion("2.14.1704.0")] [assembly: AssemblyFileVersion("2.14.1704.0")] [assembly: InternalsVisibleTo("OfficeDevPnP.Core.Tests")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OfficeDevPnP.Core")] #if SP2013 [assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2013")] #elif SP2016 [assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint 2016")] #else [assembly: AssemblyDescription("Office Dev PnP Core library for SharePoint Online")] #endif [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OfficeDevPnP.Core")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] // 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("065331b6-0540-44e1-84d5-d38f09f17f9e")] // 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: // Convention: // Major version = current version 2 // Minor version = Sequence...version 0 was with January release...so 1=Feb 2=Mar, 3=Apr, 4=May, 5=Jun, 6=Aug, 7=Sept,...11=Jan 2017 // Third part = version indenpendant showing the release month in YYMM // Fourth part = 0 normally or a sequence number when we do an emergency release [assembly: AssemblyVersion("2.13.1703.0")] [assembly: AssemblyFileVersion("2.13.1703.0")] [assembly: InternalsVisibleTo("OfficeDevPnP.Core.Tests")]
mit
C#
9727b64d6568dfda6000444c55e8a304b7ee789c
Fix files encoding to UTF-8
InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform
InfinniPlatform.Sdk/Hosting/IHostAddressParser.cs
InfinniPlatform.Sdk/Hosting/IHostAddressParser.cs
namespace InfinniPlatform.Sdk.Hosting { /// <summary> /// Интерфейс для разбора адресов узлов. /// </summary> public interface IHostAddressParser { /// <summary> /// Определяет, является ли адрес локальным. /// </summary> /// <param name="hostNameOrAddress">Имя узла или его адрес.</param> /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress); /// <summary> /// Определяет, является ли адрес локальным. /// </summary> /// <param name="hostNameOrAddress">Имя узла или его адрес.</param> /// <param name="normalizedAddress">Нормализованный адрес узла.</param> /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress); } }
namespace InfinniPlatform.Sdk.Hosting { /// <summary> /// . /// </summary> public interface IHostAddressParser { /// <summary> /// , . /// </summary> /// <param name="hostNameOrAddress"> .</param> /// <returns> <c>true</c>, ; <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress); /// <summary> /// , . /// </summary> /// <param name="hostNameOrAddress"> .</param> /// <param name="normalizedAddress"> .</param> /// <returns> <c>true</c>, ; <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress); } }
agpl-3.0
C#
207be2a04c540ac54652d0fd73471c6b094e7894
Switch to v1.2.2
AtwooTM/Zebus,biarne-a/Zebus,rbouallou/Zebus,Abc-Arbitrage/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.2.2")] [assembly: AssemblyFileVersion("1.2.2")] [assembly: AssemblyInformationalVersion("1.2.2")]
using System.Reflection; [assembly: AssemblyVersion("1.2.1")] [assembly: AssemblyFileVersion("1.2.1")] [assembly: AssemblyInformationalVersion("1.2.1")]
mit
C#
0cf1b834688a3d11ba800a36303d721774aea427
use where keyword
persimmon-projects/Persimmon.Dried,persimmon-projects/Persimmon.Dried
tests/Persimmon.Dried.CSharp.Tests/CSharpTest.cs
tests/Persimmon.Dried.CSharp.Tests/CSharpTest.cs
using System; using System.Linq; using Persimmon.Dried.Ext; namespace Persimmon.Dried.CSharp.Tests { public static class CSharpTest { public static TestCase<Unit> syntaxCheck() { return Property.Default .Add(Syntax.Prop.ForAll(Arb.Int, i => (new Lazy<bool>(() => (i + 1) % 2 != 0)).When(i % 2 == 0))); } public class Foo { public int Bar { get; set; } public int Buz { get; set; } } public static Gen<Foo> genFoo = from x in Arb.Int.Gen from y in Arb.Int.Gen where y != x select new Foo { Bar = x, Buz = y }; public static Arbitrary<Foo> arbFoo = Arbitrary.Create(genFoo, Shrink.Any<Foo>(), PrettyModule.Any); public static TestCase<Unit> querySyntaxCheck() { return Property.Default .Add(Syntax.Prop.ForAll(arbFoo, foo => foo.Bar != foo.Buz)); } } }
using System; using System.Linq; using Persimmon.Dried.Ext; namespace Persimmon.Dried.CSharp.Tests { public static class CSharpTest { public static TestCase<Unit> syntaxCheck() { return Property.Default .Add(Syntax.Prop.ForAll(Arb.Int, i => (new Lazy<bool>(() => (i + 1) % 2 != 0)).When(i % 2 == 0))); } public class Foo { public int Bar { get; set; } public int Buz { get; set; } } public static Gen<Foo> genFoo = from x in Arb.Int.Gen from y in Arb.Int.Gen.Where(i => i != x) select new Foo { Bar = x, Buz = y }; public static Arbitrary<Foo> arbFoo = Arbitrary.Create(genFoo, Shrink.Any<Foo>(), PrettyModule.Any); public static TestCase<Unit> querySyntaxCheck() { return Property.Default .Add(Syntax.Prop.ForAll(arbFoo, foo => foo.Bar != foo.Buz)); } } }
mit
C#
576c42680d48f019d3271b745bca558b99be67de
Fix for unit testing embedded service configuration
BrightstarDB/BrightstarDB,kentcb/BrightstarDB,BrightstarDB/BrightstarDB,kentcb/BrightstarDB,dharmatech/BrightstarDB,kentcb/BrightstarDB,dharmatech/BrightstarDB,dharmatech/BrightstarDB,kentcb/BrightstarDB,BrightstarDB/BrightstarDB,dharmatech/BrightstarDB,dharmatech/BrightstarDB,dharmatech/BrightstarDB,BrightstarDB/BrightstarDB
src/core/BrightstarDB.Tests/EmbeddedClientTests.cs
src/core/BrightstarDB.Tests/EmbeddedClientTests.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BrightstarDB.Client; using BrightstarDB.Config; using NUnit.Framework; namespace BrightstarDB.Tests { [TestFixture] public class EmbeddedClientTests { private readonly string _baseConnectionString; public EmbeddedClientTests() { _baseConnectionString = "type=embedded;storesDirectory=" + Configuration.StoreLocation; } private static string MakeStoreName(string testName) { return "EmbeddedClientTests_" + testName + "_" + DateTime.UtcNow.Ticks; } [TestFixtureSetUp] public void TestFixtureSetUp() { // Ensure a complete shutdown of embedded services before running these tests as they depend on re-initialization BrightstarService.Shutdown(); } [TearDown] public void Cleanup() { // Ensure a complete shutdown between tests to prevent reuse of the embedded client configuration BrightstarService.Shutdown(); } [Test] public void TestCreateStoreWithTransactionLoggingDisabled() { var client = BrightstarService.GetClient(_baseConnectionString, new EmbeddedServiceConfiguration(enableTransactionLoggingOnNewStores: false)); var storeName = MakeStoreName("CreateStoreWithTransactionLoggingDisabled"); client.CreateStore(storeName); Assert.IsFalse(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactionheaders.bs"))); Assert.IsFalse(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactions.bs"))); Assert.IsFalse(client.GetTransactions(storeName, 0, 10).Any()); } [Test] public void TestCreateStoreWithTransactionLoggingEnabled() { var client = BrightstarService.GetClient(_baseConnectionString, new EmbeddedServiceConfiguration(enableTransactionLoggingOnNewStores: true)); var storeName = MakeStoreName("CreateStoreWithTransactionLoggingEnabled"); client.CreateStore(storeName); Assert.IsTrue(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactionheaders.bs"))); Assert.IsTrue(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactions.bs"))); Assert.IsFalse(client.GetTransactions(storeName, 0, 10).Any()); // Will still be false as no operations executed yet } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BrightstarDB.Client; using BrightstarDB.Config; using NUnit.Framework; namespace BrightstarDB.Tests { [TestFixture] public class EmbeddedClientTests { private readonly string _baseConnectionString; public EmbeddedClientTests() { _baseConnectionString = "type=embedded;storesDirectory=" + Configuration.StoreLocation; } private static string MakeStoreName(string testName) { return "EmbeddedClientTests_" + testName + "_" + DateTime.UtcNow.Ticks; } [TearDown] public void Cleanup() { // Ensure a complete shutdown between tests to prevent reuse of the embedded client configuration BrightstarService.Shutdown(); } [Test] public void TestCreateStoreWithTransactionLoggingDisabled() { var client = BrightstarService.GetClient(_baseConnectionString, new EmbeddedServiceConfiguration(enableTransactionLoggingOnNewStores: false)); var storeName = MakeStoreName("CreateStoreWithTransactionLoggingDisabled"); client.CreateStore(storeName); Assert.IsFalse(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactionheaders.bs"))); Assert.IsFalse(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactions.bs"))); Assert.IsFalse(client.GetTransactions(storeName, 0, 10).Any()); } [Test] public void TestCreateStoreWithTransactionLoggingEnabled() { var client = BrightstarService.GetClient(_baseConnectionString, new EmbeddedServiceConfiguration(enableTransactionLoggingOnNewStores: true)); var storeName = MakeStoreName("CreateStoreWithTransactionLoggingEnabled"); client.CreateStore(storeName); Assert.IsTrue(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactionheaders.bs"))); Assert.IsTrue(File.Exists(Path.Combine(Configuration.StoreLocation, storeName, "transactions.bs"))); Assert.IsFalse(client.GetTransactions(storeName, 0, 10).Any()); // Will still be false as no operations executed yet } } }
mit
C#
10ce7595bdd95121d114c74110c63cf82064f876
Change LineNumber to nullable so it does not get serialized unless set
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
Mindscape.Raygun4Net.Core/RaygunBreadcrumb.cs
Mindscape.Raygun4Net.Core/RaygunBreadcrumb.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunBreadcrumb { public string Message { get; set; } public string Category { get; set; } public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info; public IDictionary CustomData { get; set; } public string ClassName { get; set; } public string MethodName { get; set; } public int? LineNumber { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunBreadcrumb { public string Message { get; set; } public string Category { get; set; } public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info; public IDictionary CustomData { get; set; } public string ClassName { get; set; } public string MethodName { get; set; } public int LineNumber { get; set; } } }
mit
C#
c3cc53cfba8388c8dee27670d93227ee15002020
Update CriteriaTarget.cs
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
main/Smartsheet/Api/Models/CriteriaTarget.cs
main/Smartsheet/Api/Models/CriteriaTarget.cs
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2018 SmartsheetClient // %% // 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. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { /// <summary> /// The target for the filter query /// </summary> public enum CriteriaTarget { ROW } }
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2018 SmartsheetClient // %% // 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. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { /// <summary> /// The target for the filter query /// </summary> public enum CriteriaTarget { ROW } }
apache-2.0
C#
63653238d7fb8d1d3c77787251a73eaf84781cc0
Store data path
feliwir/openSage,feliwir/openSage
src/OpenZH.DataViewer.UWP/Services/FilePicker.cs
src/OpenZH.DataViewer.UWP/Services/FilePicker.cs
using System; using System.Threading.Tasks; using OpenZH.DataViewer.Services; using OpenZH.DataViewer.UWP.Util; using Windows.ApplicationModel.Core; using Windows.Storage.AccessCache; using Windows.Storage.Pickers; namespace OpenZH.DataViewer.UWP.Services { public class FilePicker : IFilePicker { public Task<string> PickFolder() { return CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync( async () => { var futureAccessList = StorageApplicationPermissions.FutureAccessList; if (futureAccessList.Entries.Count > 0) { var entry = futureAccessList.Entries[0]; var futureFolder = await futureAccessList.GetFolderAsync(entry.Token); return futureFolder.Path; } var folderPicker = new FolderPicker(); folderPicker.FileTypeFilter.Add(".something"); // Otherwise PickSingleFolderAsync throws a COMException. var pickedFolder = await folderPicker.PickSingleFolderAsync(); futureAccessList.Add(pickedFolder); return pickedFolder.Path; }); } } }
using System; using System.Threading.Tasks; using OpenZH.DataViewer.Services; using OpenZH.DataViewer.UWP.Util; using Windows.ApplicationModel.Core; using Windows.Storage.Pickers; namespace OpenZH.DataViewer.UWP.Services { public class FilePicker : IFilePicker { public Task<string> PickFolder() { return CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync( async () => { var folderPicker = new FolderPicker(); folderPicker.FileTypeFilter.Add(".something"); // Otherwise PickSingleFolderAsync throws a COMException. var pickedFolder = await folderPicker.PickSingleFolderAsync(); return pickedFolder.Path; }); } } }
mit
C#
2e579d4cf341dd0d31a17ce33e53384fc5d913eb
Update Menu.cshtml
IndivisibleTacoma/website,IndivisibleTacoma/website,IndivisibleTacoma/website,IndivisibleTacoma/website
src/Orchard.Web/Themes/Bourbon/Views/Menu.cshtml
src/Orchard.Web/Themes/Bourbon/Views/Menu.cshtml
@{ // Model is Model.Menu from the layout (Layout.Menu) var tag = Tag(Model, "ul"); var items = (IList<dynamic>)Enumerable.Cast<dynamic>(Model.Items); if (items.Any()) { items[0].Classes.Add("first"); items[items.Count - 1].Classes.Add("last"); } } @*<div id="google_translate_element"></div>*@ <nav> <a href="@Href("~/")" class="navbar-brand"> <img src="https://indivisibletacoma.blob.core.windows.net/media/Default/images/weblogo.svg" alt="Indivisible Tacoma" /> </a> <div class="tagline">Resisting the Trump agenda in the Great Pacific Northwest!</div> @tag.StartElement @* see MenuItem shape template *@ @DisplayChildren(Model) @tag.EndElement <button class="c-hamburger c-hamburger--htx" id="tgl"> <span>toggle menu</span> </button> </nav>
@{ // Model is Model.Menu from the layout (Layout.Menu) var tag = Tag(Model, "ul"); var items = (IList<dynamic>)Enumerable.Cast<dynamic>(Model.Items); if (items.Any()) { items[0].Classes.Add("first"); items[items.Count - 1].Classes.Add("last"); } } @*<div id="google_translate_element"></div>*@ <nav> <a href="@Href("~/")" class="navbar-brand"> <img src="https://indivisibletacoma.blob.core.windows.net/media/Default/images/weblogo.svg" alt="Indivisible Tacoma" /> </a> <div class="tagline">Resisting the Trump/Bannon agenda in the Great Pacific Northwest!</div> @tag.StartElement @* see MenuItem shape template *@ @DisplayChildren(Model) @tag.EndElement <button class="c-hamburger c-hamburger--htx" id="tgl"> <span>toggle menu</span> </button> </nav>
bsd-3-clause
C#
0106fb69a249b15bbadc61d787e2febe9c2a845c
Update NamespaceDoc
YallaDotNet/Yalla
src/Yalla/Portable/Configuration/NamespaceDoc.cs
src/Yalla/Portable/Configuration/NamespaceDoc.cs
namespace Yalla.Configuration { /// <summary> /// YALLA.NET configuration classes. /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] internal sealed class NamespaceDoc { } }
namespace Yalla.Configuration { /// <summary> /// Yalla Configuration types. /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] internal sealed class NamespaceDoc { } }
apache-2.0
C#
0fbf77b42db6f98b84ef0c9b90d730307eb22af6
Revert "[API] Add Fields prop to EndpointBase"
arthurrump/Zermelo.API
Zermelo/Zermelo.API/Endpoints/EndpointBase.cs
Zermelo/Zermelo.API/Endpoints/EndpointBase.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Interfaces; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Endpoints { abstract internal class EndpointBase { protected IAuthentication _auth; protected IUrlBuilder _urlBuilder; protected IHttpService _httpService; protected IJsonService _jsonService; protected EndpointBase(IAuthentication auth, IUrlBuilder urlBuilder, IHttpService httpService, IJsonService jsonService) { _auth = auth; _urlBuilder = urlBuilder; _httpService = httpService; _jsonService = jsonService; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zermelo.API.Interfaces; using Zermelo.API.Services.Interfaces; namespace Zermelo.API.Endpoints { abstract internal class EndpointBase { protected IAuthentication _auth; protected IUrlBuilder _urlBuilder; protected IHttpService _httpService; protected IJsonService _jsonService; protected EndpointBase(IAuthentication auth, IUrlBuilder urlBuilder, IHttpService httpService, IJsonService jsonService) { _auth = auth; _urlBuilder = urlBuilder; _httpService = httpService; _jsonService = jsonService; } /// <summary> /// The list of fields to return. Set to <c>null</c> or an empty list for defaults. /// </summary> public List<string> Fields { get; set; } = null; } }
mit
C#
eaef40b3a3adcc819efcbfd411b84b06c8b21cba
处理二次验证函数 TwoVerification接口没有参数的问题
lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,down4u/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,wanddy/WeiXinMPSDK,down4u/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,JeffreySu/WxOpen,JeffreySu/WxOpen,wanddy/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK
Senparc.Weixin.QY/Senparc.Weixin.QY/AdvancedAPIs/Concern/ConcernApi.cs
Senparc.Weixin.QY/Senparc.Weixin.QY/AdvancedAPIs/Concern/ConcernApi.cs
/*---------------------------------------------------------------- Copyright (C) 2015 Senparc 文件名:ConcernApi.cs 文件功能描述:二次验证接口 创建标识:Senparc - 20150313 修改标识:MysticBoy - 20150414 修改描述:TwoVerification接口没有参数 ----------------------------------------------------------------*/ /* 官方文档:http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%B3%E6%B3%A8%E4%B8%8E%E5%8F%96%E6%B6%88%E5%85%B3%E6%B3%A8 */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using Senparc.Weixin.QY.CommonAPIs; using Senparc.Weixin.Entities; using Senparc.Weixin.HttpUtility; namespace Senparc.Weixin.QY.AdvancedAPIs.Concern { /// <summary> /// 关注与取消关注 /// </summary> public static class ConcernApi { /// <summary> /// 二次验证 /// </summary> /// <param name="accessToken">调用接口凭证</param> /// <param name="userId">员工UserID</param> /// <returns></returns> public static QyJsonResult TwoVerification(string accessToken, string userId) { var url =string.Format ( "https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?access_token={0}&userid={1}",accessToken,userId); return Get.GetJson<QyJsonResult>(url); } } }
/*---------------------------------------------------------------- Copyright (C) 2015 Senparc 文件名:ConcernApi.cs 文件功能描述:二次验证接口 创建标识:Senparc - 20150313 修改标识:Senparc - 20150313 修改描述:整理接口 ----------------------------------------------------------------*/ /* 官方文档:http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%B3%E6%B3%A8%E4%B8%8E%E5%8F%96%E6%B6%88%E5%85%B3%E6%B3%A8 */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using Senparc.Weixin.QY.CommonAPIs; using Senparc.Weixin.Entities; using Senparc.Weixin.HttpUtility; namespace Senparc.Weixin.QY.AdvancedAPIs.Concern { /// <summary> /// 关注与取消关注 /// </summary> public static class ConcernApi { /// <summary> /// 二次验证 /// </summary> /// <param name="accessToken">调用接口凭证</param> /// <param name="userId">员工UserID</param> /// <returns></returns> public static QyJsonResult TwoVerification(string accessToken, string userId) { var url = "https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?access_token={0}&userid={1}"; return Get.GetJson<QyJsonResult>(url); } } }
apache-2.0
C#
b5562eae2b40ee16cff5b915e81d0e40835c4e99
Add help message to !alarmclock
CaitSith2/KtaneTwitchPlays,samfun123/KtaneTwitchPlays
TwitchPlaysAssembly/Src/Holdables/Vanilla/AlarmClockHoldableHandler.cs
TwitchPlaysAssembly/Src/Holdables/Vanilla/AlarmClockHoldableHandler.cs
using System.Collections; using System.Reflection; using Assets.Scripts.Props; using UnityEngine; public class AlarmClockHoldableHandler : HoldableHandler { public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller) { clock = Holdable.GetComponentInChildren<AlarmClock>(); HelpMessage = "Snooze the alarm clock with !{0} snooze"; HelpMessage += TwitchPlaySettings.data.AllowSnoozeOnly ? " (Current Twitch play settings forbids turning the Alarm clock back on.)" : " Alarm clock may also be turned back on with !{0} snooze"; } protected override IEnumerator RespondToCommandInternal(string command) { if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break; yield return null; yield return DoInteractionClick(clock.SnoozeButton); } static AlarmClockHoldableHandler() { _alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance); } private static FieldInfo _alarmClockOnField = null; private AlarmClock clock; }
using System.Collections; using System.Reflection; using Assets.Scripts.Props; using UnityEngine; public class AlarmClockHoldableHandler : HoldableHandler { public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller) { clock = Holdable.GetComponentInChildren<AlarmClock>(); } protected override IEnumerator RespondToCommandInternal(string command) { if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break; yield return null; yield return DoInteractionClick(clock.SnoozeButton); } static AlarmClockHoldableHandler() { _alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance); } private static FieldInfo _alarmClockOnField = null; private AlarmClock clock; }
mit
C#
917bca7cabb1dbeca609a75d33f3aad069b21805
Improve exceptions.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
MitternachtWeb/Areas/User/Controllers/UserBaseController.cs
MitternachtWeb/Areas/User/Controllers/UserBaseController.cs
using Discord.WebSocket; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using MitternachtWeb.Controllers; using System; namespace MitternachtWeb.Areas.User.Controllers { public abstract class UserBaseController : DiscordUserController { [ViewData] public ulong RequestedUserId { get; set; } [ViewData] public SocketUser RequestedSocketUser { get; set; } public override void OnActionExecuting(ActionExecutingContext context) { if(RouteData.Values.TryGetValue("userId", out var userIdString)) { if(ulong.TryParse(userIdString.ToString(), out var userId)) { RequestedUserId = userId; RequestedSocketUser = Program.MitternachtBot.Client.GetUser(RequestedUserId); } else { throw new ArgumentException("userId"); } } else { throw new ArgumentNullException("userId"); } base.OnActionExecuting(context); } } }
using Discord.WebSocket; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using MitternachtWeb.Controllers; using System; namespace MitternachtWeb.Areas.User.Controllers { public abstract class UserBaseController : DiscordUserController { [ViewData] public ulong RequestedUserId { get; set; } [ViewData] public SocketUser RequestedSocketUser { get; set; } public override void OnActionExecuting(ActionExecutingContext context) { if(RouteData.Values.TryGetValue("userId", out var userIdString)) { RequestedUserId = ulong.Parse(userIdString.ToString()); RequestedSocketUser = Program.MitternachtBot.Client.GetUser(RequestedUserId); } else { throw new ArgumentNullException("userId"); } base.OnActionExecuting(context); } } }
mit
C#
d163e5fafec0d488caeb318de1148f07a359134a
Make EvaluationResult immutable.
mono/debugger-libs,mono/debugger-libs,Unity-Technologies/debugger-libs,Unity-Technologies/debugger-libs,joj/debugger-libs,joj/debugger-libs
Mono.Debugging/Mono.Debugging.Backend/IObjectValueSource.cs
Mono.Debugging/Mono.Debugging.Backend/IObjectValueSource.cs
// IObjectValueSource.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // using System; using Mono.Debugging.Client; namespace Mono.Debugging.Backend { public interface IObjectValueSource { ObjectValue[] GetChildren (ObjectPath path, int index, int count, EvaluationOptions options); EvaluationResult SetValue (ObjectPath path, string value, EvaluationOptions options); ObjectValue GetValue (ObjectPath path, EvaluationOptions options); object GetRawValue (ObjectPath path, EvaluationOptions options); void SetRawValue (ObjectPath path, object value, EvaluationOptions options); } public interface IRawValue { object CallMethod (string name, object[] parameters, EvaluationOptions options); object GetMemberValue (string name, EvaluationOptions options); void SetMemberValue (string name, object value, EvaluationOptions options); } public interface IRawValueArray { object GetValue (int[] index); void SetValue (int[] index, object value); int[] Dimensions { get; } Array ToArray (); } [Serializable] public class EvaluationResult { public EvaluationResult (string value) { Value = value; } public EvaluationResult (string value, string displayValue) { Value = value; DisplayValue = displayValue; } public string Value { get; private set; } public string DisplayValue { get; private set; } public override string ToString () { return Value; } } }
// IObjectValueSource.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // using System; using Mono.Debugging.Client; namespace Mono.Debugging.Backend { public interface IObjectValueSource { ObjectValue[] GetChildren (ObjectPath path, int index, int count, EvaluationOptions options); EvaluationResult SetValue (ObjectPath path, string value, EvaluationOptions options); ObjectValue GetValue (ObjectPath path, EvaluationOptions options); object GetRawValue (ObjectPath path, EvaluationOptions options); void SetRawValue (ObjectPath path, object value, EvaluationOptions options); } public interface IRawValue { object CallMethod (string name, object[] parameters, EvaluationOptions options); object GetMemberValue (string name, EvaluationOptions options); void SetMemberValue (string name, object value, EvaluationOptions options); } public interface IRawValueArray { object GetValue (int[] index); void SetValue (int[] index, object value); int[] Dimensions { get; } Array ToArray (); } [Serializable] public class EvaluationResult { public static readonly EvaluationResult Empty = new EvaluationResult (string.Empty); public EvaluationResult (string value) { Value = value; } public EvaluationResult (string value, string displayValue) { Value = value; DisplayValue = displayValue; } public string Value { get; set; } public string DisplayValue { get; set; } public override string ToString () { return Value; } } }
mit
C#
1755910009452a0ba61d2579c87918335afd09fe
Add xml doc.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Tor/Socks5/Models/Messages/TorSocks5Request.cs
WalletWasabi/Tor/Socks5/Models/Messages/TorSocks5Request.cs
using System; using WalletWasabi.Helpers; using WalletWasabi.Tor.Socks5.Models.Bases; using WalletWasabi.Tor.Socks5.Models.Fields.ByteArrayFields; using WalletWasabi.Tor.Socks5.Models.Fields.OctetFields; namespace WalletWasabi.Tor.Socks5.Models.Messages { /// <summary> /// SOCKS5 request representation. /// </summary> /// <remarks> /// <code> /// The SOCKS request is formed as follows: /// +----+-----+-------+------+----------+----------+ /// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | /// +----+-----+-------+------+----------+----------+ /// | 1 | 1 | X'00' | 1 | Variable | 2 | /// +----+-----+-------+------+----------+----------+ /// </code> /// </remarks> /// <seealso href="https://tools.ietf.org/html/rfc1928">Section 4. Requests</seealso> public class TorSocks5Request : ByteArraySerializableBase { public TorSocks5Request(byte[] bytes) { Guard.NotNullOrEmpty(nameof(bytes), bytes); Guard.MinimumAndNotNull($"{nameof(bytes)}.{nameof(bytes.Length)}", bytes.Length, 6); Ver = new VerField(bytes[0]); Cmd = new CmdField(bytes[1]); Rsv = new RsvField(bytes[2]); Atyp = new AtypField(bytes[3]); DstAddr = new AddrField(bytes[4..^2]); DstPort = new PortField(bytes[^2..]); } public TorSocks5Request(CmdField cmd, AddrField dstAddr, PortField dstPort) { Cmd = Guard.NotNull(nameof(cmd), cmd); DstAddr = Guard.NotNull(nameof(dstAddr), dstAddr); DstPort = Guard.NotNull(nameof(dstPort), dstPort); Ver = VerField.Socks5; Rsv = RsvField.X00; Atyp = dstAddr.Atyp; } public VerField Ver { get; } public CmdField Cmd { get; } public RsvField Rsv { get; } public AtypField Atyp { get; } public AddrField DstAddr { get; } public PortField DstPort { get; } public override byte[] ToBytes() => ByteHelpers.Combine(new byte[] { Ver.ToByte(), Cmd.ToByte(), Rsv.ToByte(), Atyp.ToByte() }, DstAddr.ToBytes(), DstPort.ToBytes()); } }
using System; using WalletWasabi.Helpers; using WalletWasabi.Tor.Socks5.Models.Bases; using WalletWasabi.Tor.Socks5.Models.Fields.ByteArrayFields; using WalletWasabi.Tor.Socks5.Models.Fields.OctetFields; namespace WalletWasabi.Tor.Socks5.Models.Messages { public class TorSocks5Request : ByteArraySerializableBase { public TorSocks5Request(byte[] bytes) { Guard.NotNullOrEmpty(nameof(bytes), bytes); Guard.MinimumAndNotNull($"{nameof(bytes)}.{nameof(bytes.Length)}", bytes.Length, 6); Ver = new VerField(bytes[0]); Cmd = new CmdField(bytes[1]); Rsv = new RsvField(bytes[2]); Atyp = new AtypField(bytes[3]); DstAddr = new AddrField(bytes[4..^2]); DstPort = new PortField(bytes[^2..]); } public TorSocks5Request(CmdField cmd, AddrField dstAddr, PortField dstPort) { Cmd = Guard.NotNull(nameof(cmd), cmd); DstAddr = Guard.NotNull(nameof(dstAddr), dstAddr); DstPort = Guard.NotNull(nameof(dstPort), dstPort); Ver = VerField.Socks5; Rsv = RsvField.X00; Atyp = dstAddr.Atyp; } #region PropertiesAndMembers public VerField Ver { get; } public CmdField Cmd { get; } public RsvField Rsv { get; } public AtypField Atyp { get; } public AddrField DstAddr { get; } public PortField DstPort { get; } #endregion PropertiesAndMembers #region Serialization public override byte[] ToBytes() => ByteHelpers.Combine(new byte[] { Ver.ToByte(), Cmd.ToByte(), Rsv.ToByte(), Atyp.ToByte() }, DstAddr.ToBytes(), DstPort.ToBytes()); #endregion Serialization } }
mit
C#
c280565c88e330688e2ea0c37c06317ff1e22926
Support Mono+.NET4.6 in CommonExtensions.ToStr.
ig-sinicyn/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,redknightlois/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Teknikaali/BenchmarkDotNet
BenchmarkDotNet/Extensions/CommonExtensions.cs
BenchmarkDotNet/Extensions/CommonExtensions.cs
using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Helpers; using BenchmarkDotNet.Horology; namespace BenchmarkDotNet.Extensions { internal static class CommonExtensions { public static List<T> ToSortedList<T>(this IEnumerable<T> values) { var list = new List<T>(); list.AddRange(values); list.Sort(); return list; } public static string ToTimeStr(this double value, TimeUnit unit = null, int unitNameWidth = 1) { unit = unit ?? TimeUnit.GetBestTimeUnit(value); var unitValue = TimeUnit.Convert(value, TimeUnit.Nanoseconds, unit); var unitName = unit.Name.PadLeft(unitNameWidth); return $"{unitValue.ToStr("N4")} {unitName}"; } public static string ToStr(this double value, string format = "0.##") { // Here we should manually create an object[] for string.Format // If we write something like // string.Format(EnvironmentInfo.MainCultureInfo, $"{{0:{format}}}", value) // it will be resolved to: // string.Format(System.IFormatProvider, string, params object[]) // .NET 4.5 // string.Format(System.IFormatProvider, string, object) // .NET 4.6 // Unfortunately, Mono doesn't have the second overload (with object instead of params object[]). var args = new object[] { value }; return string.Format(EnvironmentInfo.MainCultureInfo, $"{{0:{format}}}", args); } public static bool IsNullOrEmpty<T>(this IList<T> value) => value == null || value.Count == 0; public static bool IsEmpty<T>(this IList<T> value) => value.Count == 0; public static T Penult<T>(this IList<T> list) => list[list.Count - 2]; public static bool IsOneOf<T>(this T value, params T[] values) => values.Contains(value); } }
using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Helpers; using BenchmarkDotNet.Horology; namespace BenchmarkDotNet.Extensions { internal static class CommonExtensions { public static List<T> ToSortedList<T>(this IEnumerable<T> values) { var list = new List<T>(); list.AddRange(values); list.Sort(); return list; } public static string ToTimeStr(this double value, TimeUnit unit = null, int unitNameWidth = 1) { unit = unit ?? TimeUnit.GetBestTimeUnit(value); var unitValue = TimeUnit.Convert(value, TimeUnit.Nanoseconds, unit); var unitName = unit.Name.PadLeft(unitNameWidth); return $"{unitValue.ToStr("N4")} {unitName}"; } public static string ToStr(this double value, string format = "0.##") => string.Format(EnvironmentInfo.MainCultureInfo, $"{{0:{format}}}", value); public static bool IsNullOrEmpty<T>(this IList<T> value) => value == null || value.Count == 0; public static bool IsEmpty<T>(this IList<T> value) => value.Count == 0; public static T Penult<T>(this IList<T> list) => list[list.Count - 2]; public static bool IsOneOf<T>(this T value, params T[] values) => values.Contains(value); } }
mit
C#
ebdc11f99e81c2d7971bec7811949af59ff72f1b
Update Computer.cs
Vinogradov-Mikhail/semestr3
workTwo/workTwo/Computer.cs
workTwo/workTwo/Computer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Network { /// <summary> /// class for comuter /// </summary> public class Computer { /// <summary> /// OperatingSystem of this PC /// </summary> private OperatingSystems os; /// <summary> /// is computer infected /// </summary> public bool Infected { get; set; } /// <summary> /// get os probability /// </summary> /// <returns></returns> public int GetProbability() => os.InfectionProbability; /// <summary> /// get os name /// </summary> /// <returns></returns> public string GetOsName() { return os.NameOfOs; } public Computer(OperatingSystems thisOs, bool poison) { os = thisOs; Infected = poison; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Network { /// <summary> /// class for comuter /// </summary> public class Computer { /// <summary> /// OperatingSystem of this PC /// </summary> private OperatingSystems os; /// <summary> /// is computer infected /// </summary> public bool Infected { get; set; } /// <summary> /// get os probability /// </summary> /// <returns></returns> public int GetProbability() { return os.InfectionProbability; } /// <summary> /// get os name /// </summary> /// <returns></returns> public string GetOsName() { return os.NameOfOs; } public int GetProbability() => os.InfectionProbability; } }
apache-2.0
C#
39df19bbbe9664f816612b54717637a45f175ffb
fix for Test Module Flickr provider
sdl/dxa-modules,sdl/dxa-modules,sdl/dxa-modules,sdl/dxa-modules,sdl/dxa-modules
webapp-net/Test/Models/TestFlickrImageModel.cs
webapp-net/Test/Models/TestFlickrImageModel.cs
using Sdl.Web.Common.Models; using System.Globalization; namespace Sdl.Web.Modules.Test.Models { [SemanticEntity(Vocab = CoreVocabulary, EntityName = "TestFlickrImageModel", Prefix = "test", Public = true)] public class TestFlickrImageModel : EclItem { [SemanticProperty("test:testProp1")] public string TestProperty1 { get; set; } public override string ToHtml(string widthFactor, double aspect = 0, string cssClass = null, int containerSize = 0) { string classAttr = string.IsNullOrEmpty(cssClass) ? string.Empty : string.Format(" class=\"{0}\"", cssClass); string widthAttr = string.IsNullOrEmpty(widthFactor) ? string.Empty : string.Format(" width=\"{0}\"", widthFactor); string aspectAttr = (aspect == 0) ? string.Empty : string.Format(" data-aspect=\"{0}\"", aspect.ToString(CultureInfo.InvariantCulture)); return string.Format("<img src=\"{0}\"{1}{2}{3}>", Url, widthAttr, aspectAttr, classAttr); } } }
using Sdl.Web.Common.Models; namespace Sdl.Web.Modules.Test.Models { [SemanticEntity(Vocab = CoreVocabulary, EntityName = "TestFlickrImageModel", Prefix = "test", Public = true)] public class TestFlickrImageModel : EclItem { [SemanticProperty("test:testProp1")] public string TestProperty1 { get; set; } } }
apache-2.0
C#