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
6151c935551c9b5904e40de67b228bb72fd3db39
Update PassthroughAssemblyDirectoryFormatter.cs
toddams/RazorLight,toddams/RazorLight
src/RazorLight/Compilation/PassthroughAssemblyDirectoryFormatter.cs
src/RazorLight/Compilation/PassthroughAssemblyDirectoryFormatter.cs
using System; using System.IO; using System.Reflection; namespace RazorLight.Compilation { public class PassthroughAssemblyDirectoryFormatter : IAssemblyDirectoryFormatter { public string GetAssemblyDirectory(Assembly assembly) { return Path.GetDirectoryName(assembly.Location); } } }
using System; using System.IO; namespace RazorLight.Compilation { public class PassthroughAssemblyDirectoryFormatter : IAssemblyDirectoryFormatter { public string GetAssemblyDirectory(Assembly assembly) { return Path.GetDirectoryName(assembly.Location); } } }
apache-2.0
C#
433574756e0aa837a856effdc6da670078351598
Refactor ReferenceEqualityComparer
thnetii/dotnet-common
src/THNETII.Common/Collections.Generic/ReferenceEqualityComparer.cs
src/THNETII.Common/Collections.Generic/ReferenceEqualityComparer.cs
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace THNETII.Common.Collections.Generic { /// <summary> /// Provides equality comparison for reference type instances by determining equality through Reference Equality. /// </summary> /// <typeparam name="T">The type of objects to compare.</typeparam> /// <remarks> /// Although a value type can be specified for <typeparamref name="T"/>, two values cannot evaluate to reference equal, as both values are boxed and placed in different memory locations when being compared to each other. /// <para>In oder to use equality comparison for value types, the <see cref="EqualityComparer{T}"/> type should be used.</para> /// </remarks> public class ReferenceEqualityComparer<T> : IEqualityComparer<T> { /// <summary> /// Returns a default reference equality comparer for the type specified by the generic argument. /// </summary> [SuppressMessage("Microsoft.Design", "CA1000")] public static ReferenceEqualityComparer<T> Default { get; } = new ReferenceEqualityComparer<T>(); /// <summary> /// Determines whether two instances of type <typeparamref name="T"/> refer to the same object instance. /// </summary> /// <param name="x">The first object instance.</param> /// <param name="y">The second object reference.</param> /// <returns><c>true</c> if <paramref name="x"/> is the same instance as <paramref name="y"/> or if both are <c>null</c>; otherwise, <c>false</c>.</returns> public bool Equals(T x, T y) => StaticEquals(x, y); /// <summary> /// Determines whether two instances of type <typeparamref name="T"/> refer to the same object instance. /// </summary> /// <param name="x">The first object instance.</param> /// <param name="y">The second object reference.</param> /// <returns><c>true</c> if <paramref name="x"/> is the same instance as <paramref name="y"/> or if both are <c>null</c>; otherwise, <c>false</c>.</returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static bool StaticEquals(T x, T y) => ReferenceEquals(x, y); /// <summary> /// Serves as a hash function for the specified object for hashing algorithms and data structures, such as a hash table. /// </summary> /// <param name="obj">The object for which to get a hash code.</param> /// <returns>A hash code for the specified object, or <c>0</c> (zero) if <paramref name="obj"/> is <c>null</c>.</returns> public int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; } }
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace THNETII.Common.Collections.Generic { /// <summary> /// Provides equality comparison for reference type instances by determining equality through Reference Equality. /// </summary> /// <typeparam name="T">The type of objects to compare.</typeparam> /// <remarks> /// Although a value type can be specified for <typeparamref name="T"/>, two values cannot evaluate to reference equal, as both values are boxed and placed in different memory locations when being compared to each other. /// <para>In oder to use equality comparison for value types, the <see cref="EqualityComparer{T}"/> type should be used.</para> /// </remarks> public class ReferenceEqualityComparer<T> : IEqualityComparer<T> { private static readonly ReferenceEqualityComparer<T> @default = new ReferenceEqualityComparer<T>(); /// <summary> /// Returns a default reference equality comparer for the type specified by the generic argument. /// </summary> [SuppressMessage("Microsoft.Design", "CA1000")] public static ReferenceEqualityComparer<T> Default => @default; /// <summary> /// Determines whether two instances of type <typeparamref name="T"/> refer to the same object instance. /// </summary> /// <param name="x">The first object instance.</param> /// <param name="y">The second object reference.</param> /// <returns><c>true</c> if <paramref name="x"/> is the same instance as <paramref name="y"/> or if both are <c>null</c>; otherwise, <c>false</c>.</returns> public bool Equals(T x, T y) => StaticEquals(x, y); /// <summary> /// Determines whether two instances of type <typeparamref name="T"/> refer to the same object instance. /// </summary> /// <param name="x">The first object instance.</param> /// <param name="y">The second object reference.</param> /// <returns><c>true</c> if <paramref name="x"/> is the same instance as <paramref name="y"/> or if both are <c>null</c>; otherwise, <c>false</c>.</returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static bool StaticEquals(T x, T y) => ReferenceEquals(x, y); /// <summary> /// Serves as a hash function for the specified object for hashing algorithms and data structures, such as a hash table. /// </summary> /// <param name="obj">The object for which to get a hash code.</param> /// <returns>A hash code for the specified object, or <c>0</c> (zero) if <paramref name="obj"/> is <c>null</c>.</returns> public int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; } }
mit
C#
c6bff69a5890fe1e38e2690a951458460d5f918d
Update Egypt Provider
tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date
Src/Nager.Date/PublicHolidays/EgyptProvider.cs
Src/Nager.Date/PublicHolidays/EgyptProvider.cs
using Nager.Date.Contract; using Nager.Date.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nager.Date.PublicHolidays { public class EgyptProvider : IPublicHolidayProvider { public IEnumerable<PublicHoliday> Get(int year) { //Egypt //https://en.wikipedia.org/wiki/Public_holidays_in_Egypt var countryCode = CountryCode.EG; var items = new List<PublicHoliday>(); //TODO: Add Islamic calender logic //Sham El Nessim (Spring Festival) //Islamic New Year //Birthday of the Prophet Muhammad (Sunni) //Eid al-Fitr //Eid al-Adha items.Add(new PublicHoliday(year, 1, 7, "عيد الميلاد المجيد", "Christmas", countryCode)); items.Add(new PublicHoliday(year, 1, 25, "عيد الثورة 25 يناير", "Revolution Day 2011 National Police Day", countryCode)); items.Add(new PublicHoliday(year, 4, 25, "عيد تحرير سيناء", "Sinai Liberation Day", countryCode)); items.Add(new PublicHoliday(year, 5, 1, "عيد العمال", "Labour Day", countryCode)); items.Add(new PublicHoliday(year, 7, 23, "عيد ثورة 23 يوليو", "Revolution Day", countryCode)); items.Add(new PublicHoliday(year, 10, 6, "عيد القوات المسلحة", "Armed Forces Day", countryCode)); return items.OrderBy(o => o.Date); } } }
using Nager.Date.Contract; using Nager.Date.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nager.Date.PublicHolidays { public class EgyptProvider : IPublicHolidayProvider { public IEnumerable<PublicHoliday> Get(int year) { //Egypt //https://en.wikipedia.org/wiki/Public_holidays_in_Egypt var countryCode = CountryCode.EG; var items = new List<PublicHoliday>(); //TODO: Add Islamic calender logic //Sham El Nessim (Spring Festival) //Islamic New Year //Birthday of the Prophet Muhammad (Sunni) //Eid al-Fitr //Eid al-Adha items.Add(new PublicHoliday(year, 1, 7, "عيد الميلاد المجيد", " Christmas", countryCode)); items.Add(new PublicHoliday(year, 1, 25, "عيد الثورة 25 يناير", "Revolution Day 2011 National Police Day", countryCode)); items.Add(new PublicHoliday(year, 4, 25, "عيد تحرير سيناء", "Sinai Liberation Day", countryCode)); items.Add(new PublicHoliday(year, 5, 1, "عيد العمال", "Labour Day", countryCode)); items.Add(new PublicHoliday(year, 7, 23, "عيد ثورة 23 يوليو", "Revolution Day", countryCode)); items.Add(new PublicHoliday(year, 10, 6, "عيد القوات المسلحة", "Armed Forces Day", countryCode)); return items.OrderBy(o => o.Date); } } }
mit
C#
88ebaa82191d2824ee3213967217eacc1542bba7
define as constant
zmira/abremir.AllMyBricks
abremir.AllMyBricks.Onboarding/Helpers/RandomKeyOptionGenerator.cs
abremir.AllMyBricks.Onboarding/Helpers/RandomKeyOptionGenerator.cs
using abremir.AllMyBricks.Core.Enumerations; using System; using System.Runtime.CompilerServices; using System.Security.Cryptography; [assembly: InternalsVisibleTo("abremir.AllMyBricks.Onboarding.Tests")] namespace abremir.AllMyBricks.Onboarding.Helpers { internal static class RandomKeyOptionGenerator { internal static AlgorithmTypeEnum GetRandomKeyOption() { const int min = (int)AlgorithmTypeEnum.Type1; const int max = (int)AlgorithmTypeEnum.Type3 + 1; using (var rng = new RNGCryptoServiceProvider()) { var data = new byte[4]; rng.GetBytes(data); int generatedValue = Math.Abs(BitConverter.ToInt32(data, startIndex: 0)); const int diff = max - min; int mod = generatedValue % diff; return (AlgorithmTypeEnum)(min + mod); } } } }
using abremir.AllMyBricks.Core.Enumerations; using System; using System.Runtime.CompilerServices; using System.Security.Cryptography; [assembly: InternalsVisibleTo("abremir.AllMyBricks.Onboarding.Tests")] namespace abremir.AllMyBricks.Onboarding.Helpers { internal static class RandomKeyOptionGenerator { internal static AlgorithmTypeEnum GetRandomKeyOption() { const int min = (int)AlgorithmTypeEnum.Type1; const int max = (int)AlgorithmTypeEnum.Type3 + 1; using (var rng = new RNGCryptoServiceProvider()) { var data = new byte[4]; rng.GetBytes(data); int generatedValue = Math.Abs(BitConverter.ToInt32(data, startIndex: 0)); int diff = max - min; int mod = generatedValue % diff; return (AlgorithmTypeEnum)(min + mod); } } } }
mit
C#
b3c54a8af1352d6c5d5916778dc4f2c7a2e8c485
Fix issue when feed item provides null for Name, Description or Author
jbe2277/waf
src/NewsReader/NewsReader.Domain/FeedItem.cs
src/NewsReader/NewsReader.Domain/FeedItem.cs
using System; using System.Runtime.Serialization; using System.Waf.Foundation; namespace Jbe.NewsReader.Domain { [DataContract] public class FeedItem : Model { [DataMember] private readonly Uri uri; [DataMember] private DateTimeOffset date; [DataMember] private string name; [DataMember] private string description; [DataMember] private string author; [DataMember] private bool markAsRead; public FeedItem(Uri uri, DateTimeOffset date, string name, string description, string author) { // Note: Serializer does not call the constructor. if (uri == null) { throw new ArgumentNullException(nameof(uri)); } this.uri = uri; Date = date; Name = name; Description = description; Author = author; } public Uri Uri => uri; public DateTimeOffset Date { get { return date; } set { SetProperty(ref date, value); } } public string Name { get { return name; } set { SetProperty(ref name, (value ?? "").Truncate(200).Trim()); } } public string Description { get { return description; } set { SetProperty(ref description, (value ?? "").Truncate(500).Trim()); } } public string Author { get { return author; } set { SetProperty(ref author, (value ?? "").Truncate(100).Trim()); } } public bool MarkAsRead { get { return markAsRead; } set { SetProperty(ref markAsRead, value); } } public void ApplyValuesFrom(FeedItem item) { if (Uri != item.Uri) { throw new InvalidOperationException("The Uri must be the same."); } Date = item.Date; Name = item.Name; Description = item.Description; Author = item.Author; } } }
using System; using System.Runtime.Serialization; using System.Waf.Foundation; namespace Jbe.NewsReader.Domain { [DataContract] public class FeedItem : Model { [DataMember] private readonly Uri uri; [DataMember] private DateTimeOffset date; [DataMember] private string name; [DataMember] private string description; [DataMember] private string author; [DataMember] private bool markAsRead; public FeedItem(Uri uri, DateTimeOffset date, string name, string description, string author) { // Note: Serializer does not call the constructor. this.uri = uri; Date = date; Name = name; Description = description; Author = author; } public Uri Uri => uri; public DateTimeOffset Date { get { return date; } set { SetProperty(ref date, value); } } public string Name { get { return name; } set { SetProperty(ref name, value.Truncate(200).Trim()); } } public string Description { get { return description; } set { SetProperty(ref description, value.Truncate(500).Trim()); } } public string Author { get { return author; } set { SetProperty(ref author, value.Truncate(100).Trim()); } } public bool MarkAsRead { get { return markAsRead; } set { SetProperty(ref markAsRead, value); } } public void ApplyValuesFrom(FeedItem item) { if (Uri != item.Uri) { throw new InvalidOperationException("The Uri must be the same."); } Date = item.Date; Name = item.Name; Description = item.Description; Author = item.Author; } } }
mit
C#
15c4a4b1407a6d96540c22ec72a3034552eb57c3
Update OData WebAPI to 5.5.0.0
lungisam/WebApi,scz2011/WebApi,yonglehou/WebApi,abkmr/WebApi,LianwMS/WebApi,chimpinano/WebApi,chimpinano/WebApi,lewischeng-ms/WebApi,congysu/WebApi,abkmr/WebApi,yonglehou/WebApi,LianwMS/WebApi,lungisam/WebApi,congysu/WebApi,lewischeng-ms/WebApi,scz2011/WebApi
OData/src/CommonAssemblyInfo.cs
OData/src/CommonAssemblyInfo.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.5.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.5.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.4.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.4.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif
mit
C#
78ccb283932ecd11b60823c7d7ee73e52318ab69
Bump revision version
aa2g/PPeX
PPeX/Properties/AssemblyInfo.cs
PPeX/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PP eXtended Archive")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PPeX")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("a611a988-d477-4e16-af2f-d3a661b909a9")] // 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("8.7.1.0")] [assembly: AssemblyFileVersion("8.7.1.0")] [assembly: InternalsVisibleTo("PPeXTests")]
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("PP eXtended Archive")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PPeX")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("a611a988-d477-4e16-af2f-d3a661b909a9")] // 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("8.7.0.0")] [assembly: AssemblyFileVersion("8.7.0.0")] [assembly: InternalsVisibleTo("PPeXTests")]
mit
C#
a697dacbf657f6de0928e9582414872ee8580528
Fix sizing of embedded (wrapped) native NSViews
hamekoz/xwt,TheBrainTech/xwt,akrisiun/xwt,mminns/xwt,hwthomas/xwt,residuum/xwt,cra0zy/xwt,antmicro/xwt,lytico/xwt,iainx/xwt,mminns/xwt,mono/xwt,steffenWi/xwt
Xwt.XamMac/Xwt.Mac/EmbedNativeWidgetBackend.cs
Xwt.XamMac/Xwt.Mac/EmbedNativeWidgetBackend.cs
using System; using Xwt.Backends; using Xwt.Drawing; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; #else using Foundation; using AppKit; using ObjCRuntime; #endif namespace Xwt.Mac { public class EmbedNativeWidgetBackend : ViewBackend, IEmbeddedWidgetBackend { NSView innerView; public EmbedNativeWidgetBackend () { } public override void Initialize () { ViewObject = new WidgetView (EventSink, ApplicationContext); if (innerView != null) { var aView = innerView; innerView = null; SetNativeView (aView); } } public void SetContent (object nativeWidget) { if (nativeWidget is NSView) { if (ViewObject == null) innerView = (NSView)nativeWidget; else SetNativeView ((NSView)nativeWidget); } } void SetNativeView (NSView aView) { if (innerView != null) innerView.RemoveFromSuperview (); innerView = aView; innerView.Frame = Widget.Bounds; innerView.AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable; innerView.TranslatesAutoresizingMaskIntoConstraints = true; Widget.AutoresizesSubviews = true; Widget.AddSubview (innerView); } } }
using System; using Xwt.Backends; using Xwt.Drawing; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; #else using Foundation; using AppKit; using ObjCRuntime; #endif namespace Xwt.Mac { public class EmbedNativeWidgetBackend : ViewBackend, IEmbeddedWidgetBackend { NSView innerView; public EmbedNativeWidgetBackend () { } public override void Initialize () { ViewObject = new WidgetView (EventSink, ApplicationContext); if (innerView != null) { var aView = innerView; innerView = null; SetNativeView (aView); } } public void SetContent (object nativeWidget) { if (nativeWidget is NSView) { if (ViewObject == null) innerView = (NSView)nativeWidget; else SetNativeView ((NSView)nativeWidget); } } void SetNativeView (NSView aView) { if (innerView != null) innerView.RemoveFromSuperview (); innerView = aView; innerView.Frame = Widget.Bounds; Widget.AddSubview (innerView); } } }
mit
C#
3b3a89c2f8699af39b71fb971ed8d52044c7ad3c
Modify text on HFM panel
Zyrio/ictus,Zyrio/ictus
src/Ictus/Views/Shared/_HfmPanelPartial.cshtml
src/Ictus/Views/Shared/_HfmPanelPartial.cshtml
<div class="panel" id="hfm-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="hfm-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>Auto-Click</h1> <p><strong>Auto-Click</strong> (or <strong>Hands-Free Mode</strong>) randomizes the image for you, set via the interval below.</p> <p>The "<span class="fakelink"><i class="fa fa-mouse-pointer"></i></span>" will glow red when in operation. To stop, click on "<span class="fakelink">Auto-Click <i class="fa fa-mouse-pointer"></i></span>" again. For practical reasons, clicking on "<span class="fakelink">Previous File <i class="fa fa-backward"></i></span>" or "<span class="fakelink">Upload File <i class="fa fa-upload"></i></span>" will also stop it.</p> <table> <tr> <td style="width: 100px;"> <input type="number" min="1" max="3600" id="hfm-interval-input" style="width: 100%;" /> </td> <td> &nbsp;Interval between refreshes (in seconds) </td> <tr> <tr class="submit"> <td colspan="2"> <button id="start-hfm-button">Start</button> </td> </tr> </table> </div> </div>
<div class="panel" id="hfm-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="hfm-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>Auto-Click</h1> @if(ViewBag.IsOfficial) { <p><strong>Auto-Click</strong> (or <strong>Hands-Free Mode</strong>) allows you to sit back, put your paw around your cock, and let the pr0nz fly past. Only images (and GIFs) will be displayed.</p> } else { <p><strong>Auto-Click</strong> (or <strong>Hands-Free Mode</strong>) randomizes the image for you, set via the interval below.</p> } <p>The "<span class="fakelink"><i class="fa fa-mouse-pointer"></i></span>" will glow red when in operation. To stop, click on "<span class="fakelink">Auto-Click <i class="fa fa-mouse-pointer"></i></span>" again. For practical reasons, clicking on "<span class="fakelink">Previous File <i class="fa fa-backward"></i></span>" or "<span class="fakelink">Upload File <i class="fa fa-upload"></i></span>" will also stop it.</p> <table> <tr> <td style="width: 100px;"> <input type="number" min="1" max="3600" id="hfm-interval-input" style="width: 100%;" /> </td> <td> &nbsp;Interval between refreshes (in seconds) </td> <tr> <tr class="submit"> <td colspan="2"> <button id="start-hfm-button">Start</button> </td> </tr> </table> </div> </div>
mit
C#
9fc048e219de0ecdedbb91b08a90d20ecf196bb6
Fix Header AutomationPeer bounding rect
AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS
src/Package/Impl/DataInspect/VisualGrid/MatrixViewHeaderAutomationPeer.cs
src/Package/Impl/DataInspect/VisualGrid/MatrixViewHeaderAutomationPeer.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using Microsoft.Common.Wpf.Extensions; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.R.Package.DataInspect { internal sealed class MatrixViewHeaderAutomationPeer : MatrixViewItemAutomationPeer, IInvokeProvider { public int Column { get; } public MatrixViewHeaderAutomationPeer(MatrixView matrixView, int column) : base(matrixView) { Column = column; } protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.HeaderItem; public override object GetPattern(PatternInterface patternInterface) { switch (patternInterface) { case PatternInterface.Invoke: case PatternInterface.VirtualizedItem when VirtualizedItemPatternIdentifiers.Pattern != null && !IsRealized: return this; default: return null; } } protected override Rect GetBoundingRectangleCore() { var bounds = new Rect(Points.xPosition(Column), 0, Points.GetWidth(Column), Points.ColumnHeaderHeight); return new Rect(Owner.ColumnHeader.PointToScreen(bounds.TopLeft), Owner.ColumnHeader.PointToScreen(bounds.BottomRight)); } protected override string GetClassNameCore() => "MatrixViewHeader"; protected override bool IsKeyboardFocusableCore() => Owner.Focusable; protected override bool HasKeyboardFocusCore() => Owner.ColumnHeader.SelectedIndex.Column == Column && Owner.ColumnHeader.HasKeyboardFocus; protected override string GetAutomationIdCore() => $"{Owner.AutomationPeer.GetAutomationId()}_{Column}"; // AutomationControlType.HeaderItem must return IsContentElement false. // See http://msdn.microsoft.com/en-us/library/ms742202.aspx protected override bool IsContentElementCore() => false; protected override void SetFocusCore() => Owner.SetHeaderFocus(Column); public void Invoke() => Owner.ColumnHeader.ToggleSort(new GridIndex(0, Column), false); protected override Rect GetVisibleRect() { var left = Points.xPosition(Column); var right = left + Points.GetWidth(Column); return left.GreaterOrCloseTo(Points.ViewportWidth) || right.LessThanOrClose(0) ? Rect.Empty : new Rect(Math.Max(left, 0), 0, Math.Min(right, Points.ViewportWidth), Points.ColumnHeaderHeight); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using Microsoft.Common.Wpf.Extensions; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.R.Package.DataInspect { internal sealed class MatrixViewHeaderAutomationPeer : MatrixViewItemAutomationPeer, IInvokeProvider { public int Column { get; } public MatrixViewHeaderAutomationPeer(MatrixView matrixView, int column) : base(matrixView) { Column = column; } protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.HeaderItem; public override object GetPattern(PatternInterface patternInterface) { switch (patternInterface) { case PatternInterface.Invoke: case PatternInterface.VirtualizedItem when VirtualizedItemPatternIdentifiers.Pattern != null && !IsRealized: return this; default: return null; } } protected override Rect GetBoundingRectangleCore() { var bounds = new Rect(Points.xPosition(Column), 0, Points.GetWidth(Column), Points.ColumnHeaderHeight); return new Rect(Owner.PointToScreen(bounds.TopLeft), Owner.PointToScreen(bounds.BottomRight)); } protected override string GetClassNameCore() => "MatrixViewHeader"; protected override bool IsKeyboardFocusableCore() => Owner.Focusable; protected override bool HasKeyboardFocusCore() => Owner.ColumnHeader.SelectedIndex.Column == Column && Owner.ColumnHeader.HasKeyboardFocus; protected override string GetAutomationIdCore() => $"{Owner.AutomationPeer.GetAutomationId()}_{Column}"; // AutomationControlType.HeaderItem must return IsContentElement false. // See http://msdn.microsoft.com/en-us/library/ms742202.aspx protected override bool IsContentElementCore() => false; protected override void SetFocusCore() => Owner.SetHeaderFocus(Column); public void Invoke() => Owner.ColumnHeader.ToggleSort(new GridIndex(0, Column), false); protected override Rect GetVisibleRect() { var left = Points.xPosition(Column); var right = left + Points.GetWidth(Column); return left.GreaterOrCloseTo(Points.ViewportWidth) || right.LessThanOrClose(0) ? Rect.Empty : new Rect(Math.Max(left, 0), 0, Math.Min(right, Points.ViewportWidth), Points.ColumnHeaderHeight); } } }
mit
C#
2ffe12eac82bbe5c9a7ef4240f0d3c750702ad42
Fix - Modificata la generazione del Codice Richiesta e del Codice Chiamata come richiesto nella riunone dell'11-07-2019
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
src/backend/SO115App.FakePersistenceJSon/Utility/GeneraCodiceRichiesta.cs
src/backend/SO115App.FakePersistenceJSon/Utility/GeneraCodiceRichiesta.cs
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using SO115App.FakePersistenceJSon.GestioneIntervento; using SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso.GenerazioneCodiciRichiesta; using System; namespace SO115App.FakePersistence.JSon.Utility { public class GeneraCodiceRichiesta : IGeneraCodiceRichiesta { public string Genera(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; string nuovoNumero = GetMaxCodice.GetMax().ToString(); return string.Format("{0}{1}{2:D5}", codiceProvincia.Split('.')[0], ultimeDueCifreAnno, nuovoNumero); } public string GeneraCodiceChiamata(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; int giorno = DateTime.UtcNow.Day; int mese = DateTime.UtcNow.Month; int nuovoNumero = GetMaxCodice.GetMaxCodiceChiamata(); string returnString = string.Format("{0}{1}{2}{3}{4:D5}", codiceProvincia.Split('.')[0], giorno, mese, ultimeDueCifreAnno, nuovoNumero); return returnString; } } }
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using SO115App.FakePersistenceJSon.GestioneIntervento; using SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso.GenerazioneCodiciRichiesta; using System; namespace SO115App.FakePersistence.JSon.Utility { public class GeneraCodiceRichiesta : IGeneraCodiceRichiesta { public string Genera(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; string nuovoNumero = GetMaxCodice.GetMax().ToString(); return string.Format("{0}-{1}-{2:D5}", codiceProvincia, ultimeDueCifreAnno, nuovoNumero); } public string GeneraCodiceChiamata(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; int giorno = DateTime.UtcNow.Day; int mese = DateTime.UtcNow.Month; int nuovoNumero = GetMaxCodice.GetMaxCodiceChiamata(); string returnString = string.Format("{0}-{1}-{2}-{3}_{4:D5}", codiceProvincia, giorno, mese, ultimeDueCifreAnno, nuovoNumero); return returnString; } } }
agpl-3.0
C#
339ab0e0710868a4608bdc425fc9ecf9266e3607
Use Alcatraz's Lat/Long in tests, extract out API key to pre-test set-up.
jcheng31/ForecastPCL,jcheng31/DarkSkyApi
ForecastPCL.Test/ApiTests.cs
ForecastPCL.Test/ApiTests.cs
namespace ForecastPCL.Test { using System.Configuration; using ForecastIOPortable; using NUnit.Framework; /// <summary> /// Tests for the main ForecastApi class. /// </summary> [TestFixture] public class ApiTests { private string apiKey; // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; [TestFixtureSetUp] public void SetUp() { this.apiKey = ConfigurationManager.AppSettings["ApiKey"]; } /// <summary> /// Checks that attempting to retrieve data with a null API key throws /// an exception. /// </summary> [Test] public void NullKeyThrowsException() { var client = new ForecastApi(null); Assert.That(async () => await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude), Throws.InvalidOperationException); } /// <summary> /// Checks that attempting to retrieve data with an empty string as the /// API key throws an exception. /// </summary> [Test] public void EmptyKeyThrowsException() { var client = new ForecastApi(string.Empty); Assert.That(async () => await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude), Throws.InvalidOperationException); } /// <summary> /// Checks that using a valid API key will allow requests to be made. /// <para>An API key can be specified in the project's app.config file.</para> /// </summary> [Test] public async void ValidKeyRetrievesData() { var client = new ForecastApi(this.apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude); Assert.That(result, Is.Not.Null); Assert.That(result.Currently, Is.Not.Null); } var result = await client.GetWeatherDataAsync(1, 1); Assert.That(result, Is.Not.Null); Assert.That(result.Currently, Is.Not.Null); } } }
namespace ForecastPCL.Test { using System.Configuration; using ForecastIOPortable; using NUnit.Framework; /// <summary> /// Tests for the main ForecastApi class. /// </summary> [TestFixture] public class ApiTests { /// <summary> /// Checks that attempting to retrieve data with a null API key throws /// an exception. /// </summary> [Test] public void NullKeyThrowsException() { var client = new ForecastApi(null); Assert.That(async () => await client.GetWeatherDataAsync(1, 1), Throws.InvalidOperationException); } /// <summary> /// Checks that attempting to retrieve data with an empty string as the /// API key throws an exception. /// </summary> [Test] public void EmptyKeyThrowsException() { var client = new ForecastApi(string.Empty); Assert.That(async () => await client.GetWeatherDataAsync(1, 1), Throws.InvalidOperationException); } /// <summary> /// Checks that using a valid API key will allow requests to be made. /// <para>An API key can be specified in the project's app.config file.</para> /// </summary> [Test] public async void ValidKeyRetrievesData() { var key = ConfigurationManager.AppSettings["ApiKey"]; var client = new ForecastApi(key); var result = await client.GetWeatherDataAsync(1, 1); Assert.That(result, Is.Not.Null); Assert.That(result.Currently, Is.Not.Null); } } }
mit
C#
09eba4cc94c771cdbe57585feba787cd73de1633
clean up
dkataskin/bstrkr
bstrkr.mobile/bstrkr.core.android/Views/MvxActionBarEventSourceActivity.cs
bstrkr.mobile/bstrkr.core.android/Views/MvxActionBarEventSourceActivity.cs
using System; using Android.App; using Android.Content; using Android.OS; using Android.Support.V7.App; using Cirrious.CrossCore.Core; using Cirrious.CrossCore.Droid.Views; namespace bstrkr.core.android.views { public abstract class MvxActionBarEventSourceActivity: ActionBarActivity, IMvxEventSourceActivity { protected override void OnCreate(Bundle bundle) { CreateWillBeCalled.Raise(this, bundle); base.OnCreate(bundle); CreateCalled.Raise(this, bundle); } protected override void OnDestroy() { DestroyCalled.Raise(this); base.OnDestroy(); } protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); NewIntentCalled.Raise(this, intent); } protected override void OnResume() { base.OnResume(); ResumeCalled.Raise(this); } protected override void OnPause() { PauseCalled.Raise(this); base.OnPause(); } protected override void OnStart() { base.OnStart(); StartCalled.Raise(this); } protected override void OnRestart() { base.OnRestart(); RestartCalled.Raise(this); } protected override void OnStop() { StopCalled.Raise(this); base.OnStop(); } public override void StartActivityForResult(Intent intent, int requestCode) { StartActivityForResultCalled.Raise(this, new MvxStartActivityForResultParameters(intent, requestCode)); base.StartActivityForResult(intent, requestCode); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { ActivityResultCalled.Raise(this, new MvxActivityResultParameters(requestCode, resultCode, data)); base.OnActivityResult(requestCode, resultCode, data); } protected override void OnSaveInstanceState(Bundle outState) { SaveInstanceStateCalled.Raise(this, outState); base.OnSaveInstanceState(outState); } protected override void Dispose(bool disposing) { if (disposing) { DisposeCalled.Raise(this); } base.Dispose(disposing); } public event EventHandler DisposeCalled; public event EventHandler<MvxValueEventArgs<Bundle>> CreateWillBeCalled; public event EventHandler<MvxValueEventArgs<Bundle>> CreateCalled; public event EventHandler DestroyCalled; public event EventHandler<MvxValueEventArgs<Intent>> NewIntentCalled; public event EventHandler ResumeCalled; public event EventHandler PauseCalled; public event EventHandler StartCalled; public event EventHandler RestartCalled; public event EventHandler StopCalled; public event EventHandler<MvxValueEventArgs<Bundle>> SaveInstanceStateCalled; public event EventHandler<MvxValueEventArgs<MvxStartActivityForResultParameters>> StartActivityForResultCalled; public event EventHandler<MvxValueEventArgs<MvxActivityResultParameters>> ActivityResultCalled; } }
using System; using Android.Content; using Android.OS; using Android.Support.V7.App; using Cirrious.CrossCore.Droid.Views; using Cirrious.CrossCore.Core; namespace bstrkr.core.android.views { public abstract class MvxActionBarEventSourceActivity: ActionBarActivity, IMvxEventSourceActivity { protected override void OnCreate(Bundle bundle) { CreateWillBeCalled.Raise(this, bundle); base.OnCreate(bundle); CreateCalled.Raise(this, bundle); } protected override void OnDestroy() { DestroyCalled.Raise(this); base.OnDestroy(); } protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); NewIntentCalled.Raise(this, intent); } protected override void OnResume() { base.OnResume(); ResumeCalled.Raise(this); } protected override void OnPause() { PauseCalled.Raise(this); base.OnPause(); } protected override void OnStart() { base.OnStart(); StartCalled.Raise(this); } protected override void OnRestart() { base.OnRestart(); RestartCalled.Raise(this); } protected override void OnStop() { StopCalled.Raise(this); base.OnStop(); } public override void StartActivityForResult(Intent intent, int requestCode) { StartActivityForResultCalled.Raise(this, new MvxStartActivityForResultParameters(intent, requestCode)); base.StartActivityForResult(intent, requestCode); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { ActivityResultCalled.Raise(this, new MvxActivityResultParameters(requestCode, resultCode, data)); base.OnActivityResult(requestCode, resultCode, data); } protected override void OnSaveInstanceState(Bundle outState) { SaveInstanceStateCalled.Raise(this, outState); base.OnSaveInstanceState(outState); } protected override void Dispose(bool disposing) { if (disposing) { DisposeCalled.Raise(this); } base.Dispose(disposing); } public event EventHandler DisposeCalled; public event EventHandler<MvxValueEventArgs<Bundle>> CreateWillBeCalled; public event EventHandler<MvxValueEventArgs<Bundle>> CreateCalled; public event EventHandler DestroyCalled; public event EventHandler<MvxValueEventArgs<Intent>> NewIntentCalled; public event EventHandler ResumeCalled; public event EventHandler PauseCalled; public event EventHandler StartCalled; public event EventHandler RestartCalled; public event EventHandler StopCalled; public event EventHandler<MvxValueEventArgs<Bundle>> SaveInstanceStateCalled; public event EventHandler<MvxValueEventArgs<MvxStartActivityForResultParameters>> StartActivityForResultCalled; public event EventHandler<MvxValueEventArgs<MvxActivityResultParameters>> ActivityResultCalled; } }
bsd-2-clause
C#
2d85145eeccde1868c1fb843c852450e37c2abf7
Make legacy accent colour multiplicative
NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,ppy/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,smoogipooo/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu
osu.Game.Rulesets.Osu/Skinning/LegacySliderBody.cs
osu.Game.Rulesets.Osu/Skinning/LegacySliderBody.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 osu.Framework.Extensions.Color4Extensions; using osu.Framework.MathUtils; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning { public class LegacySliderBody : PlaySliderBody { protected override DrawableSliderPath CreateSliderPath() => new LegacyDrawableSliderPath(); private class LegacyDrawableSliderPath : DrawableSliderPath { public new Color4 AccentColour => new Color4(base.AccentColour.R, base.AccentColour.G, base.AccentColour.B, base.AccentColour.A * 0.70f); protected override Color4 ColourAt(float position) { if (CalculatedBorderPortion != 0f && position <= CalculatedBorderPortion) return BorderColour; position -= BORDER_PORTION; Color4 outerColour = AccentColour.Darken(0.1f); Color4 innerColour = lighten(AccentColour, 0.5f); return Interpolation.ValueAt(position / GRADIENT_PORTION, outerColour, innerColour, 0, 1); } /// <summary> /// Lightens a colour in a way more friendly to dark or strong colours. /// </summary> private static Color4 lighten(Color4 color, float amount) { amount *= 0.5f; return new Color4( Math.Min(1, color.R * (1 + 0.5f * amount) + 1 * amount), Math.Min(1, color.G * (1 + 0.5f * amount) + 1 * amount), Math.Min(1, color.B * (1 + 0.5f * amount) + 1 * amount), color.A); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.MathUtils; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning { public class LegacySliderBody : PlaySliderBody { protected override DrawableSliderPath CreateSliderPath() => new LegacyDrawableSliderPath(); private class LegacyDrawableSliderPath : DrawableSliderPath { public new Color4 AccentColour => new Color4(base.AccentColour.R, base.AccentColour.G, base.AccentColour.B, 0.70f); protected override Color4 ColourAt(float position) { if (CalculatedBorderPortion != 0f && position <= CalculatedBorderPortion) return BorderColour; position -= BORDER_PORTION; Color4 outerColour = AccentColour.Darken(0.1f); Color4 innerColour = lighten(AccentColour, 0.5f); return Interpolation.ValueAt(position / GRADIENT_PORTION, outerColour, innerColour, 0, 1); } /// <summary> /// Lightens a colour in a way more friendly to dark or strong colours. /// </summary> private static Color4 lighten(Color4 color, float amount) { amount *= 0.5f; return new Color4( Math.Min(1, color.R * (1 + 0.5f * amount) + 1 * amount), Math.Min(1, color.G * (1 + 0.5f * amount) + 1 * amount), Math.Min(1, color.B * (1 + 0.5f * amount) + 1 * amount), color.A); } } } }
mit
C#
f6cc60c397cd0298221d4e32fbd91c298bb55a9a
Add QuickFix.ForFirstLineInRegion() static constructor
corngood/omnisharp-server,svermeulen/omnisharp-server,mispencer/OmniSharpServer,corngood/omnisharp-server,syl20bnr/omnisharp-server,OmniSharp/omnisharp-server,x335/omnisharp-server,x335/omnisharp-server,syl20bnr/omnisharp-server
OmniSharp/Common/QuickFix.cs
OmniSharp/Common/QuickFix.cs
using OmniSharp.GotoImplementation; using ICSharpCode.NRefactory.TypeSystem; using OmniSharp.Solution; namespace OmniSharp.Common { public class QuickFix { public string FileName { get; set; } public int Line { get; set; } public int Column { get; set; } public string Text { get; set; } public Location ConvertToLocation() { return new Location() { FileName = this.FileName , Line = this.Line , Column = this.Column}; } /// <summary> /// Initialize a QuickFix pointing to the first line of the /// given region in the given file. /// </summary> public static QuickFix ForFirstLineInRegion (DomRegion region, CSharpFile file) { return new QuickFix { FileName = region.FileName , Line = region.BeginLine , Column = region.BeginColumn // Note that we could display an arbitrary amount of // context to the user: ranging from one line to tens, // hundreds.. , Text = file.Document.GetText ( offset: file.Document.GetOffset(region.Begin) , length: file.Document.GetLineByNumber (region.BeginLine).Length)}; } } }
using OmniSharp.GotoImplementation; namespace OmniSharp.Common { public class QuickFix { public string FileName { get; set; } public int Line { get; set; } public int Column { get; set; } public string Text { get; set; } public Location ConvertToLocation() { return new Location() { FileName = this.FileName , Line = this.Line , Column = this.Column}; } } }
mit
C#
6b56a1b39420d2ecbdb6a07da97be3e407d68dc2
Update version to 104.4
fmmendo/RestSharp,mattwalden/RestSharp,restsharp/RestSharp,dyh333/RestSharp,kouweizhong/RestSharp,periface/RestSharp,SaltyDH/RestSharp,benfo/RestSharp,felipegtx/RestSharp,uQr/RestSharp,KraigM/RestSharp,rivy/RestSharp,chengxiaole/RestSharp,mwereda/RestSharp,jiangzm/RestSharp,PKRoma/RestSharp,mattleibow/RestSharp,who/RestSharp,dmgandini/RestSharp,eamonwoortman/RestSharp.Unity,rucila/RestSharp,RestSharp-resurrected/RestSharp,wparad/RestSharp,dgreenbean/RestSharp,huoxudong125/RestSharp,cnascimento/RestSharp,amccarter/RestSharp,haithemaraissia/RestSharp,wparad/RestSharp,lydonchandra/RestSharp
RestSharp/SharedAssemblyInfo.cs
RestSharp/SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; // 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: AssemblyDescription("Simple REST and HTTP API Client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("John Sheehan, RestSharp Community")] [assembly: AssemblyProduct("RestSharp")] [assembly: AssemblyCopyright("Copyright © RestSharp Project 2009-2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [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("1.0.*")] [assembly: AssemblyVersion(SharedAssembylInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SharedAssembylInfo.Version)] [assembly: AssemblyFileVersion(SharedAssembylInfo.Version + ".0")] class SharedAssembylInfo { public const string Version = "104.4.0"; }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; // 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: AssemblyDescription("Simple REST and HTTP API Client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("John Sheehan, RestSharp Community")] [assembly: AssemblyProduct("RestSharp")] [assembly: AssemblyCopyright("Copyright © RestSharp Project 2009-2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [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("1.0.*")] [assembly: AssemblyVersion(SharedAssembylInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SharedAssembylInfo.Version)] [assembly: AssemblyFileVersion(SharedAssembylInfo.Version + ".0")] class SharedAssembylInfo { public const string Version = "104.3.3"; }
apache-2.0
C#
25072662fd6b8603a10754229986dd24f592a967
change BlogService to inheritance BaseServiceWithSimpleCRUD
vinhch/BizwebSharp
src/BizwebSharp/Services/Blog/BlogService.cs
src/BizwebSharp/Services/Blog/BlogService.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BizwebSharp.Infrastructure; using BizwebSharp.Options; namespace BizwebSharp { public class BlogService : BaseServiceWithSimpleCRUD<Blog, BlogOption> { public BlogService(BizwebAuthorizationState authState) : base(authState) { } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BizwebSharp.Infrastructure; using BizwebSharp.Options; namespace BizwebSharp { public class BlogService : BaseService { public BlogService(BizwebAuthorizationState authState) : base(authState) { } public virtual async Task<int> CountAsync(BlogOption options = null) { return await MakeRequest<int>("blogs/count.json", HttpMethod.GET, "count", options); } public virtual async Task<IEnumerable<Blog>> ListAsync(BlogOption options = null) { return await MakeRequest<List<Blog>>("blogs.json", HttpMethod.GET, "blogs", options); } public virtual async Task<Blog> GetAsync(long id, string fields = null) { dynamic option = null; if (!string.IsNullOrEmpty(fields)) { option = new { fields }; } return await MakeRequest<Blog>($"blogs/{id}.json", HttpMethod.GET, "blog", option); } public virtual async Task<Blog> CreateAsync(Blog blog, IEnumerable<MetaField> metafields = null) { var body = blog.ToDictionary(); if (metafields != null && metafields.Any()) { body["metafields"] = metafields; } return await MakeRequest<Blog>($"blogs.json", HttpMethod.POST, "blog", new {blog = body}); } public virtual async Task<Blog> UpdateAsync(long blogId, Blog blog, IEnumerable<MetaField> metafields = null) { var body = blog.ToDictionary(); if (metafields != null && metafields.Any()) { body["metafields"] = metafields; } return await MakeRequest<Blog>($"blogs/{blogId}.json", HttpMethod.PUT, "blog", new {blog = body}); } public virtual async Task DeleteAsync(long id) { await MakeRequest($"blogs/{id}.json", HttpMethod.DELETE); } } }
mit
C#
ff10cea52808369d589fa89bf0960f6b137b4df4
add recursive exception message to ApiError
laurence79/saule,sergey-litvinov-work/saule,goo32/saule,IntertechInc/saule,joukevandermaas/saule,bjornharrtell/saule
Saule/Serialization/ApiError.cs
Saule/Serialization/ApiError.cs
using System; using System.Collections.Generic; using System.Web.Http; namespace Saule.Serialization { internal class ApiError { public ApiError(Exception ex) { Title = ex.Message; Detail = ex.ToString(); Code = ex.GetType().FullName; Links = new Dictionary<string, string> { ["about"] = ex.HelpLink }; } internal ApiError(HttpError ex) { Title = GetRecursiveExceptionMessage(ex); Detail = ex.StackTrace; Code = ex.ExceptionType; } private static string GetRecursiveExceptionMessage(HttpError ex) { var msg = !string.IsNullOrEmpty(ex.ExceptionMessage) ? ex.ExceptionMessage : ex.Message; if (ex.InnerException != null) { msg += ' ' + GetRecursiveExceptionMessage(ex.InnerException); } return msg; } public string Title { get; } public string Detail { get; } public string Code { get; } public Dictionary<string, string> Links { get; } } }
using System; using System.Collections.Generic; using System.Web.Http; namespace Saule.Serialization { internal class ApiError { public ApiError(Exception ex) { Title = ex.Message; Detail = ex.ToString(); Code = ex.GetType().FullName; Links = new Dictionary<string, string> { ["about"] = ex.HelpLink }; } internal ApiError(HttpError ex) { Title = !string.IsNullOrEmpty(ex.ExceptionMessage) ? ex.ExceptionMessage : ex.Message; Detail = ex.StackTrace; Code = ex.ExceptionType; } public string Title { get; } public string Detail { get; } public string Code { get; } public Dictionary<string, string> Links { get; } } }
mit
C#
692ec2847be6589ff9555d315dd39dd6f7d6ab1f
Add comments to public methods
andreazevedo/JsonConfig
src/JsonConfig/JsonConfigManager.cs
src/JsonConfig/JsonConfigManager.cs
using System.Web.Script.Serialization; namespace JsonConfig { public static class JsonConfigManager { #region Fields private static readonly IConfigFileLoader ConfigFileLoader = new ConfigFileLoader(); private static dynamic _defaultConfig; #endregion #region Public Members /// <summary> /// Gets the default config dynamic object, which should be a file named app.json.config located at the root of your project /// </summary> public static dynamic DefaultConfig { get { if (_defaultConfig == null) { _defaultConfig = GetConfig(ConfigFileLoader.LoadDefaultConfigFile()); } return _defaultConfig; } } /// <summary> /// Get a config dynamic object from the json /// </summary> /// <param name="json">Json string</param> /// <returns>The dynamic config object</returns> public static dynamic GetConfig(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); return serializer.Deserialize(json, typeof(object)); } /// <summary> /// Load a config from a specified file /// </summary> /// <param name="filePath">Config file path</param> /// <returns>The dynamic config object</returns> public static dynamic LoadConfig(string filePath) { return GetConfig(ConfigFileLoader.LoadConfigFile(filePath)); } #endregion } }
using System.Web.Script.Serialization; namespace JsonConfig { public static class JsonConfigManager { #region Fields private static readonly IConfigFileLoader ConfigFileLoader = new ConfigFileLoader(); private static dynamic _defaultConfig; #endregion #region Public Members public static dynamic DefaultConfig { get { if (_defaultConfig == null) { _defaultConfig = GetConfig(ConfigFileLoader.LoadDefaultConfigFile()); } return _defaultConfig; } } public static dynamic GetConfig(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); return serializer.Deserialize(json, typeof(object)); } public static dynamic LoadConfig(string filePath) { return GetConfig(ConfigFileLoader.LoadConfigFile(filePath)); } #endregion } }
mit
C#
367bc66877fa06d7fd548a201618bcd4b45344de
添加快速反射方法的框架。 :skull:
Zongsoft/Zongsoft.CoreLibrary
src/Reflection/Reflector.cs
src/Reflection/Reflector.cs
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@qq.com> * * Copyright (C) 2010-2018 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.CoreLibrary. * * Zongsoft.CoreLibrary is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.CoreLibrary 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 * Lesser General Public License for more details. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.CoreLibrary; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Reflection; using System.Collections.Generic; namespace Zongsoft.Reflection { public static class Reflector { public static object GetValue(this MemberInfo member, object target) { switch(member.MemberType) { case MemberTypes.Field: return GetValue((FieldInfo)member, target); case MemberTypes.Property: return GetValue((PropertyInfo)member, target); default: throw new NotSupportedException("Invalid member type."); } } public static object GetValue(this FieldInfo field, object target) { throw new NotImplementedException(); } public static object GetValue(this PropertyInfo property, object target) { throw new NotImplementedException(); } public static void SetValue(this MemberInfo member, object target, object value) { switch(member.MemberType) { case MemberTypes.Field: SetValue((FieldInfo)member, target, value); break; case MemberTypes.Property: SetValue((PropertyInfo)member, target, value); break; default: throw new NotSupportedException("Invalid member type."); } } public static void SetValue(this FieldInfo field, object target, object value) { throw new NotImplementedException(); } public static void SetValue(this PropertyInfo property, object target, object value) { throw new NotImplementedException(); } } }
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@qq.com> * * Copyright (C) 2010-2018 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.CoreLibrary. * * Zongsoft.CoreLibrary is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.CoreLibrary 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 * Lesser General Public License for more details. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.CoreLibrary; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Reflection; using System.Collections.Generic; namespace Zongsoft.Reflection { public static class Reflector { } }
lgpl-2.1
C#
295e5886ed77c4607b488f30ab59b0597ad69f01
Update AgreementTemplateExtensions.cs
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Web/Extensions/AgreementTemplateExtensions.cs
src/SFA.DAS.EmployerAccounts.Web/Extensions/AgreementTemplateExtensions.cs
using SFA.DAS.EmployerAccounts.Web.ViewModels; using System.Collections.Generic; using System.Linq; namespace SFA.DAS.EmployerAccounts.Web.Extensions { public static class AgreementTemplateExtensions { public static readonly int[] VariationsOfv3Agreement = {3, 4, 5, 6}; public static string InsetText(this AgreementTemplateViewModel agreementTemplate, ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel) { switch (agreementTemplate.VersionNumber) { case 1: return string.Empty; case 2: return "This is a variation of the agreement that we published 1 May 2017. We updated it to add clause 7 (transfer of funding)."; case 3: return "This is a new agreement."; case 4: return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020. You only need to accept it if you want to access incentive payments for hiring a new apprentice." : "This is a new agreement."; case var ver when ver >= 5: return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020." : "This is a new agreement."; default: return string.Empty; } } private static bool HasSignedVariationOfv3Agreement(ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel) { return organisationAgreementViewModel .Any(agreement => !string.IsNullOrEmpty(agreement.SignedDateText) && VariationsOfv3Agreement.Contains(agreement.Template.VersionNumber)); } } }
using SFA.DAS.EmployerAccounts.Web.ViewModels; using System.Collections.Generic; using System.Linq; namespace SFA.DAS.EmployerAccounts.Web.Extensions { public static class AgreementTemplateExtensions { public static readonly int[] VariationsOfv3Agreement = {3, 4, 5, 6}; public static string InsetText(this AgreementTemplateViewModel agreementTemplate, ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel) { switch (agreementTemplate.VersionNumber) { case 1: return string.Empty; case 2: return "This is a variation of the agreement that we published 1 May 2017. We updated it to add clause 7 (transfer of funding)."; case 3: return "This is a new agreement."; case 4: return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020. You only need to accept it if you want to access incentive payments for hiring a new apprentice." : "This is a new agreement."; case 5: case 6: case 7: return HasSignedVariationOfv3Agreement(organisationAgreementViewModel) ? "This is a variation to the agreement we published 9 January 2020." : "This is a new agreement."; default: return string.Empty; } } private static bool HasSignedVariationOfv3Agreement(ICollection<OrganisationAgreementViewModel> organisationAgreementViewModel) { return organisationAgreementViewModel .Any(agreement => !string.IsNullOrEmpty(agreement.SignedDateText) && VariationsOfv3Agreement.Contains(agreement.Template.VersionNumber)); } } }
mit
C#
3b4946bb2bbc45fddf30f9b3899f8df85f018ab0
Change SensorDataContract.
radiojam11/connectthedots,noopkat/connectthedots,jeffwilcox/connectthedots,zack076/connectthedots,radiojam11/connectthedots,BretStateham/connectthedots,radiojam11/connectthedots,jessejjohnson/connectthedots,Azure/connectthedots,jomolinare/connectthedots,beeva-marianmoldovan/connectthedots,pietrobr/connectthedots,BretStateham/connectthedots,HydAu/AzureConnectTheDots,radiojam11/connectthedots,yashchandak/connectthedots,HydAu/ConnectTheDots2,HydAu/ConnectTheDots2,beeva-marianmoldovan/connectthedots,pietrobr/connectthedots,Azure/connectthedots,zack076/connectthedots,noopkat/connectthedots,Azure/connectthedots,zack076/connectthedots,HydAu/ConnectTheDots2,jmservera/connectthedots,jomolinare/connectthedots,beeva-marianmoldovan/connectthedots,noopkat/connectthedots,beeva-marianmoldovan/connectthedots,ZingPow/connectthedots,Azure/connectthedots,jmservera/connectthedots,jomolinare/connectthedots,Azure/connectthedots,jessejjohnson/connectthedots,yashchandak/connectthedots,MSOpenTech/connectthedots,BretStateham/connectthedots,pietrobr/connectthedots,jeffwilcox/connectthedots,radiojam11/connectthedots,Azure/connectthedots,jmservera/connectthedots,BretStateham/connectthedots,MSOpenTech/connectthedots,jessejjohnson/connectthedots,MSOpenTech/connectthedots,jeffwilcox/connectthedots,jeffwilcox/connectthedots,ZingPow/connectthedots,pietrobr/connectthedots,zack076/connectthedots,noopkat/connectthedots,HydAu/AzureConnectTheDots,jessejjohnson/connectthedots,BretStateham/connectthedots,pietrobr/connectthedots,HydAu/AzureConnectTheDots,jmservera/connectthedots,HydAu/ConnectTheDots2,jmservera/connectthedots,MSOpenTech/connectthedots,yashchandak/connectthedots,beeva-marianmoldovan/connectthedots,beeva-marianmoldovan/connectthedots,Azure/connectthedots,jmservera/connectthedots,HydAu/AzureConnectTheDots,HydAu/ConnectTheDots2,HydAu/ConnectTheDots2,MSOpenTech/connectthedots,MSOpenTech/connectthedots,noopkat/connectthedots,ZingPow/connectthedots,jessejjohnson/connectthedots,noopkat/connectthedots,radiojam11/connectthedots,ZingPow/connectthedots,BretStateham/connectthedots,pietrobr/connectthedots,jeffwilcox/connectthedots,noopkat/connectthedots,HydAu/AzureConnectTheDots,zack076/connectthedots,BretStateham/connectthedots,HydAu/AzureConnectTheDots,jomolinare/connectthedots,jomolinare/connectthedots,jessejjohnson/connectthedots,zack076/connectthedots,jeffwilcox/connectthedots,ZingPow/connectthedots,yashchandak/connectthedots,jomolinare/connectthedots,ZingPow/connectthedots,yashchandak/connectthedots,yashchandak/connectthedots
Devices/Gateways/GatewayService/Gateway/Models/SensorDataContract.cs
Devices/Gateways/GatewayService/Gateway/Models/SensorDataContract.cs
using System; using System.Runtime.Serialization; namespace Gateway.Models { [DataContract] public class SensorDataContract { [DataMember(Name = "value")] public double Value { get; set; } [DataMember(Name = "guid")] public int Guid { get; set; } [DataMember(Name = "organization")] public string Organization { get; set; } [DataMember(Name = "displayname")] public string DisplayName { get; set; } [DataMember(Name = "unitofmeasure")] public string UnitOfMeasure { get; set; } [DataMember(Name = "measurename")] public string MeasureName { get; set; } [DataMember(Name = "location")] public string Location { get; set; } [DataMember(Name = "timecreated")] public DateTime TimeCreated { get; set; } } }
using System; using System.Runtime.Serialization; namespace Gateway.Models { [DataContract] public class SensorDataContract { [DataMember(Name = "Value")] public double Value { get; set; } [DataMember(Name = "GUID")] public int Guid { get; set; } [DataMember(Name = "Organization")] public string Organization { get; set; } [DataMember(Name = "DisplayName")] public string DisplayName { get; set; } [DataMember(Name = "UnitOfMeasure")] public string UnitOfMeasure { get; set; } [DataMember(Name = "MeasureName")] public string MeasureName { get; set; } [DataMember(Name = "Location")] public string Location { get; set; } [DataMember(Name = "time_created")] public DateTime TimeCreated { get; set; } } }
mit
C#
f951f9005f26076faab3d5b3a5fddb961d8914fd
Update VersionInfo.cs
reanimuse/wz-addon-tosser
Core/VersionInfo.cs
Core/VersionInfo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WzAddonTosser.Core { public static class wzatVersionInfo { public const string ProductName = "wzAddonTosser"; public const string Company = "reanimuse MIT License"; public const string Copyright = "Copyright ©2016 reanimuse"; public const string Version = "0.1.0.0"; public const string BuildVersion = "0.1.1.19"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WzAddonTosser.Core { public static class wzatVersionInfo { public const string ProductName = "wzAddonTosser"; public const string Company = "reanimuse MIT License"; public const string Copyright = "Copyright ©2016 reanimuse"; public const string Version = "0.1.0.0"; public const string BuildVersion = "0.1.1.18"; } }
mit
C#
dc560aae71cf2d0259bd7fbdceba101ac133dc4a
Remove unnecessary references
jensoleg/aspnet5-angular2-typescript,jensoleg/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,myomyinthan/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,myomyinthan/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,myomyinthan/aspnet5-angular2-typescript,jensoleg/aspnet5-angular2-typescript,jensoleg/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,myomyinthan/aspnet5-angular2-typescript
src/PhotoGallery/Views/Shared/_Layout.cshtml
src/PhotoGallery/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@ViewBag.Title</title> @*<base href="/">*@ <link href="~/lib/css/bootstrap.css" rel="stylesheet" /> <link href="~/lib/css/font-awesome.css" rel="stylesheet" /> @RenderSection("styles", required: false) @*<script src="~/lib/js/system.js"></script>*@ @*<script src="~/lib/js/es6-shim.js"></script>*@ <script src="~/lib/js/angular2-polyfills.js"></script> <script src="~/lib/js/system.src.js"></script> <script src="~/lib/js/Rx.js"></script> <script src="~/lib/js/jquery.js"></script> <script src="~/lib/js/bootstrap.js"></script> <script> System.config({ map: { 'rxjs': 'lib/js/rxjs' }, packages: { 'app': { defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } }, defaultJSExtensions: true }); </script> <script src="~/lib/js/angular2.dev.js"></script> <script src="~/lib/js/http.dev.js"></script> <script src="~/lib/js/router.dev.js"></script> </head> <body> <div> @RenderBody() </div> @RenderSection("scripts", required: false) <script type="text/javascript"> @RenderSection("customScript", required: false) </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@ViewBag.Title</title> @*<base href="/">*@ <link href="~/lib/css/bootstrap.css" rel="stylesheet" /> <link href="~/lib/css/font-awesome.css" rel="stylesheet" /> @RenderSection("styles", required: false) @*<script src="~/lib/js/system.js"></script>*@ @*<script src="~/lib/js/es6-shim.js"></script>*@ <script src="~/lib/js/angular2-polyfills.js"></script> <script src="~/lib/js/system.src.js"></script> <script src="~/lib/js/Rx.js"></script> <script src="~/lib/js/angular2.dev.js"></script> <script src="~/lib/js/jquery.js"></script> <script src="~/lib/js/bootstrap.js"></script> <script> System.config({ map: { 'rxjs': 'lib/js/rxjs', //'angular2/angular2': '~/lib/js/angular2.dev.js', 'angular2/http': '~/lib/js/http.dev.js', 'angular2/router': '~/lib/js/router.dev.js' }, packages: { 'app': { defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } }, defaultJSExtensions: true }); </script> <script src="~/lib/js/angular2.dev.js"></script> <script src="~/lib/js/http.dev.js"></script> <script src="~/lib/js/router.dev.js"></script> </head> <body> <div> @RenderBody() </div> @RenderSection("scripts", required: false) <script type="text/javascript"> @RenderSection("customScript", required: false) </script> </body> </html>
mit
C#
974eeccef42fabaf711f5a60d7afd7d2b92d63a4
Remove redundant _message field
lunet-io/scriban,textamina/scriban
src/Scriban/Syntax/ScriptRuntimeException.cs
src/Scriban/Syntax/ScriptRuntimeException.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Collections.Generic; using Scriban.Helpers; using Scriban.Parsing; namespace Scriban.Syntax { public class ScriptRuntimeException : Exception { public ScriptRuntimeException(SourceSpan span, string message) : base(message) { Span = span; } public ScriptRuntimeException(SourceSpan span, string message, Exception innerException) : base(message, innerException) { Span = span; } public SourceSpan Span { get; } public override string Message { get { return new LogMessage(ParserMessageType.Error, Span, base.Message).ToString(); } } public override string ToString() { return Message; } } public class ScriptParserRuntimeException : ScriptRuntimeException { public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages) : this(span, message, parserMessages, null) { } public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages, Exception innerException) : base(span, message, innerException) { if (parserMessages == null) throw new ArgumentNullException(nameof(parserMessages)); ParserMessages = parserMessages; } public List<LogMessage> ParserMessages { get; } public override string ToString() { var messagesAsText = StringHelper.Join("\n", ParserMessages); return $"{base.ToString()} Parser messages:\n {messagesAsText}"; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Collections.Generic; using Scriban.Helpers; using Scriban.Parsing; namespace Scriban.Syntax { public class ScriptRuntimeException : Exception { private string _message; public ScriptRuntimeException(SourceSpan span, string message) : base(message) { Span = span; _message = message; } public ScriptRuntimeException(SourceSpan span, string message, Exception innerException) : base(message, innerException) { Span = span; _message = message; } public SourceSpan Span { get; } public override string Message { get { return ToString(); } } public override string ToString() { return new LogMessage(ParserMessageType.Error, Span, _message).ToString(); } } public class ScriptParserRuntimeException : ScriptRuntimeException { public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages) : this(span, message, parserMessages, null) { } public ScriptParserRuntimeException(SourceSpan span, string message, List<LogMessage> parserMessages, Exception innerException) : base(span, message, innerException) { if (parserMessages == null) throw new ArgumentNullException(nameof(parserMessages)); ParserMessages = parserMessages; } public List<LogMessage> ParserMessages { get; } public override string ToString() { var messagesAsText = StringHelper.Join("\n", ParserMessages); return $"{base.ToString()} Parser messages:\n {messagesAsText}"; } } }
bsd-2-clause
C#
465229fb39f4f49deb56f5eaec9822fcfb8f1553
Return PackageInstance as opposed to CreatedPackage in API responses
abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS
src/Umbraco.Web/Editors/PackageController.cs
src/Umbraco.Web/Editors/PackageController.cs
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using umbraco.cms.businesslogic.packager; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Editors { //TODO: Packager stuff still lives in business logic - YUK /// <summary> /// A controller used for installing packages and managing all of the data in the packages section in the back office /// </summary> [PluginController("UmbracoApi")] [UmbracoApplicationAuthorize(Core.Constants.Applications.Packages)] public class PackageController : UmbracoAuthorizedJsonController { [HttpGet] public List<PackageInstance> GetCreatedPackages() { //TODO: Could be too much data down the wire return CreatedPackage.GetAllCreatedPackages().Select(x => x.Data).ToList(); } [HttpGet] public PackageInstance GetCreatedPackageById(int id) { //TODO throw an error if cant find by ID return CreatedPackage.GetById(id).Data; } [HttpPost] public PackageInstance PostCreatePackage(PackageInstance model) { //TODO Validation on the model?! var newPackage = new CreatedPackage { Data = model }; //Save then publish newPackage.Save(); newPackage.Publish(); //We should have packagepath populated now return newPackage.Data; } [HttpDelete] public HttpResponseMessage DeleteCreatedPackageById(int id) { //TODO: Validation ensure can find it by ID var package = CreatedPackage.GetById(id); package.Delete(); //204 No Content return new HttpResponseMessage(HttpStatusCode.NoContent); } } }
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using umbraco.cms.businesslogic.packager; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Editors { //TODO: Packager stuff still lives in business logic - YUK /// <summary> /// A controller used for installing packages and managing all of the data in the packages section in the back office /// </summary> [PluginController("UmbracoApi")] [UmbracoApplicationAuthorize(Core.Constants.Applications.Packages)] public class PackageController : UmbracoAuthorizedJsonController { [HttpGet] public List<CreatedPackage> GetCreatedPackages() { //TODO: Could be too much data down the wire return CreatedPackage.GetAllCreatedPackages(); } [HttpGet] public CreatedPackage GetCreatedPackageById(int id) { return CreatedPackage.GetById(id); } [HttpPost] public CreatedPackage PostCreatePackage(PackageInstance model) { //TODO Validation on the model?! var newPackage = new CreatedPackage { Data = model }; //Save then publish newPackage.Save(); newPackage.Publish(); //We should have packagepath populated now return newPackage; } [HttpDelete] public HttpResponseMessage DeleteCreatedPackageById(int id) { var package = CreatedPackage.GetById(id); package.Delete(); //204 No Content return new HttpResponseMessage(HttpStatusCode.NoContent); } } }
mit
C#
394c370434ee286659dbcd563076080850bbd074
move CertificateValidationRemoteServer_EndToEnd_Ok to outerloop
ericstj/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx
src/System.Net.Security/tests/FunctionalTests/CertificateValidationRemoteServer.cs
src/System.Net.Security/tests/FunctionalTests/CertificateValidationRemoteServer.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.Net.Sockets; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class CertificateValidationRemoteServer { [Fact] [OuterLoop("Uses external servers")] public async Task CertificateValidationRemoteServer_EndToEnd_Ok() { using (var client = new TcpClient(AddressFamily.InterNetwork)) { await client.ConnectAsync(Configuration.Security.TlsServer.IdnHost, Configuration.Security.TlsServer.Port); using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null)) { await sslStream.AuthenticateAsClientAsync(Configuration.Security.TlsServer.IdnHost); } } } private bool RemoteHttpsCertValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Assert.Equal(SslPolicyErrors.None, sslPolicyErrors); return true; } } }
// 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.Net.Sockets; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class CertificateValidationRemoteServer { [Fact] public async Task CertificateValidationRemoteServer_EndToEnd_Ok() { using (var client = new TcpClient(AddressFamily.InterNetwork)) { await client.ConnectAsync(Configuration.Security.TlsServer.IdnHost, Configuration.Security.TlsServer.Port); using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null)) { await sslStream.AuthenticateAsClientAsync(Configuration.Security.TlsServer.IdnHost); } } } private bool RemoteHttpsCertValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Assert.Equal(SslPolicyErrors.None, sslPolicyErrors); return true; } } }
mit
C#
a3210f4e3ddd13c45f98c9067a629c87c49dc590
Access operator for array is now "item"
hahoyer/reni.cs,hahoyer/reni.cs,hahoyer/reni.cs
src/reni2/FeatureTest/Array/ElementAccess.cs
src/reni2/FeatureTest/Array/ElementAccess.cs
using System.Linq; using System.Collections.Generic; using System; using hw.UnitTest; using Reni.FeatureTest.Structure; namespace Reni.FeatureTest.Array { [TestFixture] [ArrayFromPieces] [TargetSet("((<<5)item (0)) dump_print", "5")] public sealed class ElementAccessSimple : CompilerTest {} [TestFixture] [ElementAccessSimple] [TargetSet("((<<5<<3<<5<<1<<3)item (3)) dump_print", "1")] public sealed class ElementAccess : CompilerTest {} [TestFixture] [ArrayFromPieces] [TwoStatements] [TargetSet("x: <<5<<3; x dump_print", "<<(5, 3)")] public sealed class ArrayVariable : CompilerTest {} [TestFixture] [ElementAccessVariable] [ArrayVariable] [TwoStatements] [TargetSet("x: <<:= 5; x item(0):= 2; x dump_print", "<<:=(2)")] public sealed class ElementAccessVariableSetterSimple : CompilerTest {} [TestFixture] [ElementAccessVariableSetterSimple] [TwoStatements] [TargetSet("x: <<5<<3<<5<<1<<:=3; x item(3) := 2; x dump_print", "<<:=(5, 3, 5, 2, 3)")] public sealed class ElementAccessVariableSetter : CompilerTest {} [TestFixture] [ElementAccess] [TwoStatements] [TargetSet("x: <<5<<3<<5<<1<<3; x item(3) dump_print", "1")] public sealed class ElementAccessVariable : CompilerTest {} }
using System.Linq; using System.Collections.Generic; using System; using hw.UnitTest; using Reni.FeatureTest.Structure; namespace Reni.FeatureTest.Array { [TestFixture] [ArrayFromPieces] [TargetSet("((<<5)item (0)) dump_print", "5")] public sealed class ElementAccessSimple : CompilerTest {} [TestFixture] [ElementAccessSimple] [TargetSet("((<<5<<3<<5<<1<<3)item (3)) dump_print", "1")] public sealed class ElementAccess : CompilerTest {} [TestFixture] [ArrayFromPieces] [TwoStatements] [TargetSet("x: <<5<<3; x dump_print", "<<(5, 3)")] public sealed class ArrayVariable : CompilerTest {} [TestFixture] [ElementAccessVariable] [ArrayVariable] [TwoStatements] [TargetSet("x: <<:= 5; xitem0 := 2; x dump_print", "<<:=(2)")] public sealed class ElementAccessVariableSetterSimple : CompilerTest {} [TestFixture] [ElementAccessVariableSetterSimple] [TwoStatements] [TargetSet("x: <<5<<3<<5<<1<<:=3; xitem3 := 2; x dump_print", "<<:=(5, 3, 5, 2, 3)")] public sealed class ElementAccessVariableSetter : CompilerTest {} [TestFixture] [ElementAccess] [TwoStatements] [TargetSet("x: <<5<<3<<5<<1<<3; (xitem3) dump_print", "1")] public sealed class ElementAccessVariable : CompilerTest {} }
mit
C#
9f5aa7067cd9e4a0a42b30cb71e67d4bc09cb742
remove change
os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos
Core.ApplicationServices/GDPR/DataProcessingRegistrationReadModelService.cs
Core.ApplicationServices/GDPR/DataProcessingRegistrationReadModelService.cs
using System.Linq; using Core.Abstractions.Types; using Core.ApplicationServices.Authorization; using Core.DomainModel.GDPR.Read; using Core.DomainServices.Authorization; using Core.DomainServices.Repositories.GDPR; namespace Core.ApplicationServices.GDPR { public class DataProcessingRegistrationReadModelService : IDataProcessingRegistrationReadModelService { private readonly IAuthorizationContext _authorizationContext; private readonly IDataProcessingRegistrationReadModelRepository _repository; public DataProcessingRegistrationReadModelService(IAuthorizationContext authorizationContext, IDataProcessingRegistrationReadModelRepository repository) { _authorizationContext = authorizationContext; _repository = repository; } public Result<IQueryable<DataProcessingRegistrationReadModel>, OperationError> GetByOrganizationId(int organizationId) { if (_authorizationContext.GetOrganizationReadAccessLevel(organizationId) != OrganizationDataReadAccessLevel.All) return new OperationError(OperationFailure.Forbidden); return Result<IQueryable<DataProcessingRegistrationReadModel>, OperationError>.Success(_repository.GetByOrganizationId(organizationId)); } } }
using System.Linq; using Core.Abstractions.Types; using Core.ApplicationServices.Authorization; using Core.DomainModel.GDPR.Read; using Core.DomainServices.Authorization; using Core.DomainServices.Repositories.GDPR; namespace Core.ApplicationServices.GDPR { public class DataProcessingRegistrationReadModelService : IDataProcessingRegistrationReadModelService { private readonly IAuthorizationContext _authorizationContext; private readonly IDataProcessingRegistrationReadModelRepository _repository; public DataProcessingRegistrationReadModelService(IAuthorizationContext authorizationContext, IDataProcessingRegistrationReadModelRepository repository) { _authorizationContext = authorizationContext; _repository = repository; } public Result<IQueryable<DataProcessingRegistrationReadModel>, OperationError> GetByOrganizationId(int organizationId) { if (_authorizationContext.GetOrganizationReadAccessLevel(organizationId) != OrganizationDataReadAccessLevel.All) return new OperationError(OperationFailure.Forbidden); return Result<IQueryable<DataProcessingRegistrationReadModel>, OperationError>.Success(_repository.GetByOrganizationId(organizationId)); } } }
mpl-2.0
C#
c1d6e9f4d4213d379d3233122ad2c524e767bcbd
Update comment
Archie-Yang/PcscDotNet
src/PcscDotNet/PcscProvider.cs
src/PcscDotNet/PcscProvider.cs
namespace PcscDotNet { /// <summary> /// Usage shared for IPcscProvider. /// </summary> public static class PcscProvider { /// <summary> /// Length designator for auto-allocation memory from the smart card resource manager. /// </summary> public const int SCardAutoAllocate = -1; } }
namespace PcscDotNet { /// <summary> /// Usage shared for IPcscProvider /// </summary> public static class PcscProvider { /// <summary> /// Length designator for auto-allocation memory from the smart card resource manager. /// </summary> public const int SCardAutoAllocate = -1; } }
mit
C#
fade1a69fcd83a7ced233725cb02aeb932a88dc8
Fix Mobile number from long to string (#1025)
JKorf/Binance.Net
Binance.Net/Objects/Models/Spot/SubAccountData/BinanceSubAccountStatus.cs
Binance.Net/Objects/Models/Spot/SubAccountData/BinanceSubAccountStatus.cs
using System; using CryptoExchange.Net.Converters; using Newtonsoft.Json; namespace Binance.Net.Objects.Models.Spot.SubAccountData { /// <summary> /// Sub-account Status on Margin/Futures /// </summary> public class BinanceSubAccountStatus { /// <summary> /// User email /// </summary> [JsonProperty("email")] public string Email { get; set; } = string.Empty; /// <summary> /// Sub account user enabled /// </summary> [JsonProperty("isSubUserEnabled")] public bool IsAccountEnabled { get; set; } /// <summary> /// Sub account user active /// </summary> [JsonProperty("isUserActive")] public bool IsActive { get; set; } /// <summary> /// The time the sub account was created /// </summary> [JsonProperty("insertTime"), JsonConverter(typeof(DateTimeConverter))] public DateTime CreateTime { get; set; } /// <summary> /// Is Margin enabled /// </summary> [JsonProperty("isMarginEnabled")] public bool IsMarginEnabled { get; set; } /// <summary> /// Is Futures enabled /// </summary> [JsonProperty("isFutureEnabled")] public bool IsFutureEnabled { get; set; } /// <summary> /// User mobile number /// </summary> [JsonProperty("mobile")] public string? MobileNumber { get; set; } } }
using System; using CryptoExchange.Net.Converters; using Newtonsoft.Json; namespace Binance.Net.Objects.Models.Spot.SubAccountData { /// <summary> /// Sub-account Status on Margin/Futures /// </summary> public class BinanceSubAccountStatus { /// <summary> /// User email /// </summary> [JsonProperty("email")] public string Email { get; set; } = string.Empty; /// <summary> /// Sub account user enabled /// </summary> [JsonProperty("isSubUserEnabled")] public bool IsAccountEnabled { get; set; } /// <summary> /// Sub account user active /// </summary> [JsonProperty("isUserActive")] public bool IsActive { get; set; } /// <summary> /// The time the sub account was created /// </summary> [JsonProperty("insertTime"), JsonConverter(typeof(DateTimeConverter))] public DateTime CreateTime { get; set; } /// <summary> /// Is Margin enabled /// </summary> [JsonProperty("isMarginEnabled")] public bool IsMarginEnabled { get; set; } /// <summary> /// Is Futures enabled /// </summary> [JsonProperty("isFutureEnabled")] public bool IsFutureEnabled { get; set; } /// <summary> /// User mobile number /// </summary> [JsonProperty("mobile")] public long MobileNumber { get; set; } } }
mit
C#
1c651dbb32b1a3254f23ad114fbb319df2e74037
Fix to ajax restoration of the cart.
bleroy/Nwazet.Commerce,bleroy/Nwazet.Commerce
Views/ShoppingCartWidget.cshtml
Views/ShoppingCartWidget.cshtml
@{ if (Layout.IsCartPage != true) { Script.Require("jQuery"); Script.Include("shoppingcart.js", "shoppingcart.min.js"); <div class="shopping-cart-container minicart" data-load="@Url.Action("NakedCart", "ShoppingCart", new {area="Nwazet.Commerce"})" data-update="@Url.Action("AjaxUpdate", "ShoppingCart", new {area="Nwazet.Commerce"})" data-token="@Html.AntiForgeryTokenValueOrchard()"></div> <script type="text/javascript"> var Nwazet = window.Nwazet || {}; Nwazet.WaitWhileWeRestoreYourCart = "@T("Please wait while we restore your shopping cart...")"; Nwazet.FailedToLoadCart = "@T("Failed to load the cart")"; </script> } }
@{ if (Layout.IsCartPage != true) { Script.Require("jQuery"); Script.Include("shoppingcart.js", "shoppingcart.min.js"); <div class="shopping-cart-container minicart" data-load="@Url.Action("NakedCart", "ShoppingCart", new {area="Nwazet.Commerce"})" data-update="@Url.Action("AjaxUpdate", "ShoppingCart", new {area="Nwazet.Commerce"})" data-token="@Html.AntiForgeryTokenValueOrchard()"></div> } }
bsd-3-clause
C#
f785dbf2b5649adcbc0431b2d9b04f31a8958a05
Change levy run date to 24th
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ImportLevyDeclarationsJob.cs
src/SFA.DAS.EmployerFinance.Jobs/ScheduledJobs/ImportLevyDeclarationsJob.cs
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 10 24 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }
mit
C#
292c215a4eb7182599634e128c9e2518f7def7db
Add MethodImplAttributes.AggressiveOptimization (#20274)
cshung/coreclr,krk/coreclr,mmitche/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,krk/coreclr,poizan42/coreclr,poizan42/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,krk/coreclr,poizan42/coreclr,wtgodbe/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,mmitche/coreclr,poizan42/coreclr,mmitche/coreclr,krk/coreclr,mmitche/coreclr,krk/coreclr,mmitche/coreclr,mmitche/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,krk/coreclr,cshung/coreclr
src/System.Private.CoreLib/shared/System/Reflection/MethodImplAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/MethodImplAttributes.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. namespace System.Reflection { // This Enum matchs the CorMethodImpl defined in CorHdr.h public enum MethodImplAttributes { // code impl mask CodeTypeMask = 0x0003, // Flags about code type. IL = 0x0000, // Method impl is IL. Native = 0x0001, // Method impl is native. OPTIL = 0x0002, // Method impl is OPTIL Runtime = 0x0003, // Method impl is provided by the runtime. // end code impl mask // managed mask ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged. Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed. Managed = 0x0000, // Method impl is managed. // end managed mask // implementation info and interop ForwardRef = 0x0010, // Indicates method is not defined; used primarily in merge scenarios. PreserveSig = 0x0080, // Indicates method sig is exported exactly as declared. InternalCall = 0x1000, // Internal Call... Synchronized = 0x0020, // Method is single threaded through the body. NoInlining = 0x0008, // Method may not be inlined. AggressiveInlining = 0x0100, // Method should be inlined if possible. NoOptimization = 0x0040, // Method may not be optimized. AggressiveOptimization = 0x0200, // Method may contain hot code and should be aggressively optimized. MaxMethodImplVal = 0xffff, } }
// 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. namespace System.Reflection { // This Enum matchs the CorMethodImpl defined in CorHdr.h public enum MethodImplAttributes { // code impl mask CodeTypeMask = 0x0003, // Flags about code type. IL = 0x0000, // Method impl is IL. Native = 0x0001, // Method impl is native. OPTIL = 0x0002, // Method impl is OPTIL Runtime = 0x0003, // Method impl is provided by the runtime. // end code impl mask // managed mask ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged. Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed. Managed = 0x0000, // Method impl is managed. // end managed mask // implementation info and interop ForwardRef = 0x0010, // Indicates method is not defined; used primarily in merge scenarios. PreserveSig = 0x0080, // Indicates method sig is exported exactly as declared. InternalCall = 0x1000, // Internal Call... Synchronized = 0x0020, // Method is single threaded through the body. NoInlining = 0x0008, // Method may not be inlined. AggressiveInlining = 0x0100, // Method should be inlined if possible. NoOptimization = 0x0040, // Method may not be optimized. MaxMethodImplVal = 0xffff, } }
mit
C#
2fd644a5c6e7534cb586003f8d5d3eafa85a6b4e
Add Cancel command
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/AddWallet/ConfirmRecoveryWordsViewModel.cs
WalletWasabi.Fluent/ViewModels/AddWallet/ConfirmRecoveryWordsViewModel.cs
using DynamicData; using DynamicData.Binding; using ReactiveUI; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Windows.Input; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Wallets; namespace WalletWasabi.Fluent.ViewModels.AddWallet { public class ConfirmRecoveryWordsViewModel : RoutableViewModel { private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords; private readonly SourceList<RecoveryWordViewModel> _confirmationWordsSourceList; public ConfirmRecoveryWordsViewModel(NavigationStateViewModel navigationState, List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager) : base(navigationState, NavigationTarget.Dialog) { _confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>(); var finishCommandCanExecute = _confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .WhenValueChanged(x => x.IsConfirmed) .Select(x => !_confirmationWordsSourceList.Items.Any(x => !x.IsConfirmed)); FinishCommand = ReactiveCommand.Create( () => { walletManager.AddWallet(keyManager); navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear(); }, finishCommandCanExecute); CancelCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear()); _confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .OnItemAdded(x => x.Reset()) .Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index)) .Bind(out _confirmationWords) .Subscribe(); SelectRandomConfirmationWords(mnemonicWords); } public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords; public ICommand FinishCommand { get; } public ICommand CancelCommand { get; } private void SelectRandomConfirmationWords(List<RecoveryWordViewModel> mnemonicWords) { var random = new Random(); while (_confirmationWordsSourceList.Count != 4) { var word = mnemonicWords[random.Next(0, 12)]; if (!_confirmationWordsSourceList.Items.Contains(word)) { _confirmationWordsSourceList.Add(word); } } } } }
using DynamicData; using DynamicData.Binding; using ReactiveUI; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Windows.Input; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Wallets; namespace WalletWasabi.Fluent.ViewModels.AddWallet { public class ConfirmRecoveryWordsViewModel : RoutableViewModel { private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords; private readonly SourceList<RecoveryWordViewModel> _confirmationWordsSourceList; public ConfirmRecoveryWordsViewModel(NavigationStateViewModel navigationState, List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager) : base(navigationState, NavigationTarget.Dialog) { _confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>(); var finishCommandCanExecute = _confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .WhenValueChanged(x => x.IsConfirmed) .Select(x => !_confirmationWordsSourceList.Items.Any(x => !x.IsConfirmed)); FinishCommand = ReactiveCommand.Create( () => { walletManager.AddWallet(keyManager); navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear(); }, finishCommandCanExecute); _confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .OnItemAdded(x => x.Reset()) .Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index)) .Bind(out _confirmationWords) .Subscribe(); SelectRandomConfirmationWords(mnemonicWords); } public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords; public ICommand FinishCommand { get; } private void SelectRandomConfirmationWords(List<RecoveryWordViewModel> mnemonicWords) { var random = new Random(); while (_confirmationWordsSourceList.Count != 4) { var word = mnemonicWords[random.Next(0, 12)]; if (!_confirmationWordsSourceList.Items.Contains(word)) { _confirmationWordsSourceList.Add(word); } } } } }
mit
C#
06a977e9dbf78ff4db5bad75369dbd18ea62d089
Read and write release files
rzhw/Squirrel.Windows,rzhw/Squirrel.Windows
src/NSync.Core/ReleaseEntry.cs
src/NSync.Core/ReleaseEntry.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Security.Cryptography; namespace NSync.Core { public class ReleaseEntry : IEnableLogger { public string SHA1 { get; protected set; } public string Filename { get; protected set; } public long Filesize { get; protected set; } public bool IsDelta { get; protected set; } protected ReleaseEntry(string sha1, string filename, long filesize, bool isDelta) { SHA1 = sha1; Filename = filename; Filesize = filesize; IsDelta = isDelta; } static readonly Regex entryRegex = new Regex(@"^([0-9a-fA-F]{40})\s+(\S+)\s+(\d+)$"); public static ReleaseEntry ParseReleaseEntry(string entry) { var m = entryRegex.Match(entry); if (!m.Success) { return null; } if (m.Groups.Count != 4) { return null; } long size = Int64.Parse(m.Groups[3].Value); bool isDelta = filenameIsDeltaFile(m.Groups[2].Value); return new ReleaseEntry(m.Groups[1].Value, m.Groups[2].Value, size, isDelta); } public static IEnumerable<ReleaseEntry> ParseReleaseFile(string file) { var ret = file.Split('\n').Select(ParseReleaseEntry).ToArray(); return ret.Any(x => x == null) ? null : ret; } public static void WriteReleaseFile(IEnumerable<ReleaseEntry> releaseEntries, string path) { File.WriteAllText(path, String.Join("\n", releaseEntries.Select(x => x.EntryAsString)), Encoding.UTF8); } public string EntryAsString { get { return String.Format("{0} {1} {2}", SHA1, Filename, Filesize); } } public static ReleaseEntry GenerateFromFile(Stream file, string filename) { var sha1 = System.Security.Cryptography.SHA1.Create(); var hash = BitConverter.ToString(sha1.ComputeHash(file)).Replace("-", String.Empty); return new ReleaseEntry(hash, filename, file.Length, filenameIsDeltaFile(filename)); } static bool filenameIsDeltaFile(string filename) { return filename.EndsWith(".delta", StringComparison.InvariantCultureIgnoreCase); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Security.Cryptography; namespace NSync.Core { public class ReleaseEntry : IEnableLogger { public string SHA1 { get; protected set; } public string Filename { get; protected set; } public long Filesize { get; protected set; } public bool IsDelta { get; protected set; } protected ReleaseEntry(string sha1, string filename, long filesize, bool isDelta) { SHA1 = sha1; Filename = filename; Filesize = filesize; IsDelta = isDelta; } static readonly Regex entryRegex = new Regex(@"^([0-9a-fA-F]{40})\s+(\S+)\s+(\d+)$"); public static ReleaseEntry ParseReleaseEntry(string entry) { var m = entryRegex.Match(entry); if (!m.Success) { return null; } if (m.Groups.Count != 4) { return null; } long size = Int64.Parse(m.Groups[3].Value); bool isDelta = filenameIsDeltaFile(m.Groups[2].Value); return new ReleaseEntry(m.Groups[1].Value, m.Groups[2].Value, size, isDelta); } public string EntryAsString { get { return String.Format("{0} {1} {2}", SHA1, Filename, Filesize); } } public static ReleaseEntry GenerateFromFile(Stream file, string filename) { var sha1 = System.Security.Cryptography.SHA1.Create(); var hash = BitConverter.ToString(sha1.ComputeHash(file)).Replace("-", String.Empty); return new ReleaseEntry(hash, filename, file.Length, filenameIsDeltaFile(filename)); } static bool filenameIsDeltaFile(string filename) { return filename.EndsWith(".delta", StringComparison.InvariantCultureIgnoreCase); } } }
mit
C#
ec39f41af1968c32dbf54fe52609ffc7f9bdc40c
Correct XML comment of `SubjectObjectExtensions`
atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata
src/Atata/DataProvision/SubjectObjectExtensions.cs
src/Atata/DataProvision/SubjectObjectExtensions.cs
namespace Atata { /// <summary> /// Provides a set of object extension methods that wrap the object with the <see cref="Subject{T}"/> class. /// </summary> public static class SubjectObjectExtensions { /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the <c>"sut"</c> provider name. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToSutSubject<T>(this T source) => source.ToSubject("sut"); /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the <c>"result"</c> provider name. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToResultSubject<T>(this T source) => source.ToSubject("result"); /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the default provider name. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToSubject<T>(this T source) => new Subject<T>(source); /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the specified <paramref name="providerName"/>. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <param name="providerName">Name of the provider.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToSubject<T>(this T source, string providerName) => new Subject<T>(source, providerName); } }
namespace Atata { /// <summary> /// Provides a set of object extension methods that wrap the object with the <see cref="Subject{TValue}"/> class. /// </summary> public static class SubjectObjectExtensions { /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the <c>"sut"</c> provider name. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToSutSubject<T>(this T source) => source.ToSubject("sut"); /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the <c>"result"</c> provider name. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToResultSubject<T>(this T source) => source.ToSubject("result"); /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the default provider name. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToSubject<T>(this T source) => new Subject<T>(source); /// <summary> /// Creates a new <see cref="Subject{T}"/> instance that wraps the <paramref name="source"/> with the specified <paramref name="providerName"/>. /// </summary> /// <typeparam name="T">The type of the source.</typeparam> /// <param name="source">The instance to wrap with <see cref="Subject{T}"/>.</param> /// <param name="providerName">Name of the provider.</param> /// <returns>A new <see cref="Subject{T}"/> instance.</returns> public static Subject<T> ToSubject<T>(this T source, string providerName) => new Subject<T>(source, providerName); } }
apache-2.0
C#
061012fc86784dbafa214aba76b6548974a94a3d
Fix concert edit form submission URL.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Views/Concerts/_ConcertEditForm.cshtml
src/CGO.Web/Views/Concerts/_ConcertEditForm.cshtml
@model CGO.Web.ViewModels.ConcertViewModel @{ Html.EnableClientValidation(); } @using (Html.BeginForm()) { @Html.ValidationSummary(false, "Oh dear, the violas made a boo-boo. Please go back and fix the following mistakes:") <fieldset> <legend>Concert details</legend> <h2>Basic Details</h2> <p></p> <p>@Html.TextBoxFor(c => c.Title, new { placeholder = "Enter title" }) @Html.ValidationMessageFor(c => c.Title)</p> <p> <label for="Date" style="display: inline">Start date and time:&nbsp;</label> @Html.EditorFor(c => c.Date, "Date") @Html.EditorFor(c => c.StartTime, "Time") @Html.ValidationMessageFor(c => c.Date) @Html.ValidationMessageFor(c => c.StartTime) </p> <p>@Html.TextBoxFor(c => c.Location, new { placeholder = "Enter venue " }) @Html.ValidationMessageFor(c => c.Location)</p> <script type="text/javascript"> //$("#Location").typeahead() </script> <h2>Marketing details</h2> <p></p> <div class="wmd-panel"> <div id="wmd-button-bar"></div> @Html.TextAreaFor(c => c.Description, new { id = "wmd-input", @class = "wmd-input", placeholder = "Provide a description of the concert, including things like the pieces being played, the composers, the soloists for the concert, etc." })<br /> </div> <div id="wmd-preview" class="wmd-panel wmd-preview"></div> <p>&nbsp;</p> <p> <label for="PosterImage" style="display: inline">Upload poster image: </label><input type="file" name="PosterImage" id="PosterImage" /> </p> <p>&nbsp;</p> <p> @Html.HiddenFor(c => c.IsPublished) <input type="submit" value="Publish Concert" class="btn btn-primary" onclick="$('#IsPublished').val(true);$(this).submit();" /> <input type="submit" value="Save for later" class="btn" onclick="$('#IsPublished').val(false);$(this).submit();" /> <input type="reset" value="Discard" class="btn" /> </p> </fieldset> } @Html.Partial("_MarkdownEditor")
@model CGO.Web.ViewModels.ConcertViewModel @{ Html.EnableClientValidation(); } @using (Html.BeginForm("Create", "Concerts", FormMethod.Post, new { id = "CreateConcert" })) { @Html.ValidationSummary(false, "Oh dear, the violas made a boo-boo. Please go back and fix the following mistakes:") <fieldset> <legend>Concert details</legend> <h2>Basic Details</h2> <p></p> <p>@Html.TextBoxFor(c => c.Title, new { placeholder = "Enter title" }) @Html.ValidationMessageFor(c => c.Title)</p> <p> <label for="Date" style="display: inline">Start date and time:&nbsp;</label> @Html.EditorFor(c => c.Date, "Date") @Html.EditorFor(c => c.StartTime, "Time") @Html.ValidationMessageFor(c => c.Date) @Html.ValidationMessageFor(c => c.StartTime) </p> <p>@Html.TextBoxFor(c => c.Location, new { placeholder = "Enter venue " }) @Html.ValidationMessageFor(c => c.Location)</p> <script type="text/javascript"> //$("#Location").typeahead() </script> <h2>Marketing details</h2> <p></p> <div class="wmd-panel"> <div id="wmd-button-bar"></div> @Html.TextAreaFor(c => c.Description, new { id = "wmd-input", @class = "wmd-input", placeholder = "Provide a description of the concert, including things like the pieces being played, the composers, the soloists for the concert, etc." })<br /> </div> <div id="wmd-preview" class="wmd-panel wmd-preview"></div> <p>&nbsp;</p> <p> <label for="PosterImage" style="display: inline">Upload poster image: </label><input type="file" name="PosterImage" id="PosterImage" /> </p> <p>&nbsp;</p> <p> @Html.HiddenFor(c => c.IsPublished) <input type="submit" value="Publish Concert" class="btn btn-primary" onclick="$('#IsPublished').val(true);$('#CreateConcert').submit();" /> <input type="submit" value="Save for later" class="btn" onclick="$('#IsPublished').val(false);$('#CreateConcert').submit();" /> <input type="reset" value="Discard" class="btn" /> </p> </fieldset> } @Html.Partial("_MarkdownEditor")
mit
C#
e4bbe05a2c1990f5aed4cfd213c5a00c8ec321ef
Bump version
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
configuration/SharedAssemblyInfo.cs
configuration/SharedAssemblyInfo.cs
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-alpha3")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-alpha2")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
mit
C#
af8bd7a5aa3fc1447860f1d1d6f46d6a32890560
Add MarkupExtensionReturnType when xdoc.
DotNetAnalyzers/WpfAnalyzers
WpfAnalyzers.Test/WPF0080MarkupExtensionDoesNotHaveAttributeTests/CodeFix.cs
WpfAnalyzers.Test/WPF0080MarkupExtensionDoesNotHaveAttributeTests/CodeFix.cs
namespace WpfAnalyzers.Test.WPF0080MarkupExtensionDoesNotHaveAttributeTests { using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; public static class CodeFix { private static readonly DiagnosticAnalyzer Analyzer = new WPF0080MarkupExtensionDoesNotHaveAttribute(); private static readonly CodeFixProvider Fix = new MarkupExtensionReturnTypeAttributeFix(); private static readonly ExpectedDiagnostic ExpectedDiagnostic = ExpectedDiagnostic.Create(Descriptors.WPF0080MarkupExtensionDoesNotHaveAttribute); [Test] public static void Message() { var code = @" namespace N { using System; using System.Windows.Markup; public class ↓FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; RoslynAssert.Diagnostics(Analyzer, ExpectedDiagnostic.WithMessage("Add MarkupExtensionReturnType attribute."), code); } [Test] public static void ReturnsThis() { var before = @" namespace N { using System; using System.Windows.Markup; public class ↓FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; var after = @" namespace N { using System; using System.Windows.Markup; [MarkupExtensionReturnType(typeof(FooExtension))] public class FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, before, after); } [Test] public static void WhenDocumented() { var before = @" namespace N { using System; using System.Windows.Markup; /// <summary> /// Text /// </summary> public class ↓FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; var after = @" namespace N { using System; using System.Windows.Markup; /// <summary> /// Text /// </summary> [MarkupExtensionReturnType(typeof(FooExtension))] public class FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, before, after); } } }
namespace WpfAnalyzers.Test.WPF0080MarkupExtensionDoesNotHaveAttributeTests { using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; public static class CodeFix { private static readonly DiagnosticAnalyzer Analyzer = new WPF0080MarkupExtensionDoesNotHaveAttribute(); private static readonly CodeFixProvider Fix = new MarkupExtensionReturnTypeAttributeFix(); private static readonly ExpectedDiagnostic ExpectedDiagnostic = ExpectedDiagnostic.Create(Descriptors.WPF0080MarkupExtensionDoesNotHaveAttribute); [Test] public static void Message() { var code = @" namespace N { using System; using System.Windows.Markup; public class ↓FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; RoslynAssert.Diagnostics(Analyzer, ExpectedDiagnostic.WithMessage("Add MarkupExtensionReturnType attribute."), code); } [Test] public static void DirectCastWrongSourceType() { var before = @" namespace N { using System; using System.Windows.Markup; public class ↓FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; var after = @" namespace N { using System; using System.Windows.Markup; [MarkupExtensionReturnType(typeof(FooExtension))] public class FooExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }"; RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, before, after); } } }
mit
C#
122943d131e768365a5867c158a4cac2c237c99c
Update ProtectingSpecificColumnInWorksheet.cs
aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Worksheets/Security/ProtectingSpecificColumnInWorksheet.cs
Examples/CSharp/Worksheets/Security/ProtectingSpecificColumnInWorksheet.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Security { public class ProtectingSpecificColumnInWorksheet { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); // Create a new workbook. Workbook wb = new Workbook(); // Create a worksheet object and obtain the first sheet. Worksheet sheet = wb.Worksheets[0]; // Define the style object. Style style; // Define the styleflag object. StyleFlag flag; // Loop through all the columns in the worksheet and unlock them. for (int i = 0; i <= 255; i++) { style = sheet.Cells.Columns[(byte)i].Style; style.IsLocked = false; flag = new StyleFlag(); flag.Locked = true; sheet.Cells.Columns[(byte)i].ApplyStyle(style, flag); } // Get the first column style. style = sheet.Cells.Columns[0].Style; // Lock it. style.IsLocked = true; // Instantiate the flag. flag = new StyleFlag(); // Set the lock setting. flag.Locked = true; // Apply the style to the first column. sheet.Cells.Columns[0].ApplyStyle(style, flag); // Protect the sheet. sheet.Protect(ProtectionType.All); // Save the excel file. wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Security { public class ProtectingSpecificColumnInWorksheet { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); // Create a new workbook. Workbook wb = new Workbook(); // Create a worksheet object and obtain the first sheet. Worksheet sheet = wb.Worksheets[0]; // Define the style object. Style style; // Define the styleflag object. StyleFlag flag; // Loop through all the columns in the worksheet and unlock them. for (int i = 0; i <= 255; i++) { style = sheet.Cells.Columns[(byte)i].Style; style.IsLocked = false; flag = new StyleFlag(); flag.Locked = true; sheet.Cells.Columns[(byte)i].ApplyStyle(style, flag); } // Get the first column style. style = sheet.Cells.Columns[0].Style; // Lock it. style.IsLocked = true; // Instantiate the flag. flag = new StyleFlag(); // Set the lock setting. flag.Locked = true; // Apply the style to the first column. sheet.Cells.Columns[0].ApplyStyle(style, flag); // Protect the sheet. sheet.Protect(ProtectionType.All); // Save the excel file. wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003); } } }
mit
C#
6a07078b1d28433feb12ec28603ad9ffdd611da4
Remove a skipped test.
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
LINQToTTree/LINQToTTreeLib.Tests/FileUtilsTest.MakeSureFileNotUpdated.g.cs
LINQToTTree/LINQToTTreeLib.Tests/FileUtilsTest.MakeSureFileNotUpdated.g.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Pex.Framework.Generated; // <auto-generated> // This file contains automatically generated unit tests. // Do NOT modify this file manually. // // When Pex is invoked again, // it might remove or update any previously generated unit tests. // // If the contents of this file becomes outdated, e.g. if it does not // compile anymore, you may delete this file and invoke Pex again. // </auto-generated> namespace LINQToTTreeLib.Utils { public partial class FileUtilsTest { [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated244() { this.MakeSureFileNotUpdated((string)null, (string)null); } [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated134() { this.MakeSureFileNotUpdated((string)null, ""); } [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated300() { this.MakeSureFileNotUpdated("", (string)null); } [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated580() { this.MakeSureFileNotUpdated((string)null, "\0\0"); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Pex.Framework.Generated; // <auto-generated> // This file contains automatically generated unit tests. // Do NOT modify this file manually. // // When Pex is invoked again, // it might remove or update any previously generated unit tests. // // If the contents of this file becomes outdated, e.g. if it does not // compile anymore, you may delete this file and invoke Pex again. // </auto-generated> namespace LINQToTTreeLib.Utils { public partial class FileUtilsTest { [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated244() { this.MakeSureFileNotUpdated((string)null, (string)null); } [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated134() { this.MakeSureFileNotUpdated((string)null, ""); } [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated300() { this.MakeSureFileNotUpdated("", (string)null); } [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] public void MakeSureFileNotUpdated580() { this.MakeSureFileNotUpdated((string)null, "\0\0"); } [TestMethod] [PexGeneratedBy(typeof(FileUtilsTest))] [Ignore] [PexDescription("the test state was: path bounds exceeded")] public void MakeSureFileNotUpdated584() { this.MakeSureFileNotUpdated((string)null, new string('\0', 1024)); } } }
lgpl-2.1
C#
6392bbc62c9468d6d1b5c8a74ade2d85641fb080
Tidy up
alastairs/BobTheBuilder
BobTheBuilder/DynamicBuilder.cs
BobTheBuilder/DynamicBuilder.cs
using BobTheBuilder.Activation; using BobTheBuilder.ArgumentStore; using BobTheBuilder.ArgumentStore.Queries; using BobTheBuilder.Syntax; using System; using System.Dynamic; namespace BobTheBuilder { public class DynamicBuilder<T> : DynamicObject where T : class { private readonly IParser parser; private readonly IArgumentStore argumentStore; public DynamicBuilder(IParser parser, IArgumentStore argumentStore) { if (parser == null) { throw new ArgumentNullException("parser"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.parser = parser; this.argumentStore = argumentStore; } public T Build() { new ReportingMissingArgumentsQuery(new MissingArgumentsQuery(argumentStore)).Execute(typeof(T)); var instance = new InstanceCreator(new ConstructorArgumentsQuery(argumentStore)).CreateInstanceOf<T>(); new PropertySetter(new PropertyValuesQuery(argumentStore)).PopulatePropertiesOn(instance); return instance; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = this; return parser.Parse(binder, args); } public static implicit operator T(DynamicBuilder<T> builder) { return builder.Build(); } } }
using BobTheBuilder.Activation; using BobTheBuilder.ArgumentStore; using BobTheBuilder.ArgumentStore.Queries; using BobTheBuilder.Syntax; using System; using System.Collections.Generic; using System.Dynamic; namespace BobTheBuilder { public class DynamicBuilder<T> : DynamicObject where T : class { private readonly IParser parser; private readonly IArgumentStore argumentStore; public DynamicBuilder(IParser parser, IArgumentStore argumentStore) { if (parser == null) { throw new ArgumentNullException("parser"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.parser = parser; this.argumentStore = argumentStore; } public T Build() { var destinationType = typeof(T); new ReportingMissingArgumentsQuery(new MissingArgumentsQuery(argumentStore)).Execute(destinationType); var instance = new InstanceCreator(new ConstructorArgumentsQuery(argumentStore)).CreateInstanceOf<T>(); new PropertySetter(new PropertyValuesQuery(argumentStore)).PopulatePropertiesOn(instance); return instance; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = this; return parser.Parse(binder, args); } public static implicit operator T(DynamicBuilder<T> builder) { return builder.Build(); } } }
apache-2.0
C#
cb114f88f2327c1fe0202e5b44e458b8b3fa4dc7
Update comments
Minesweeper-6-Team-Project-Telerik/Minesweeper-6
src2/ConsoleMinesweeper/Interfaces/IConsoleView.cs
src2/ConsoleMinesweeper/Interfaces/IConsoleView.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IConsoleView.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // The ConsoleView interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleMinesweeper.Interfaces { using Minesweeper.Models; using Minesweeper.Views; /// <summary> /// The ConsoleView interface. /// </summary> public interface IConsoleView : IMinesweeperView { /// <summary> /// The request score list. /// </summary> /// <param name="type"> /// The type. /// </param> void RequestScoreList(MinesweeperDifficultyType type); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IConsoleView.cs" company=""> // // </copyright> // <summary> // The ConsoleView interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleMinesweeper.Interfaces { using Minesweeper.Models; using Minesweeper.Views; /// <summary> /// The ConsoleView interface. /// </summary> public interface IConsoleView : IMinesweeperView { /// <summary> /// The request score list. /// </summary> /// <param name="type"> /// The type. /// </param> void RequestScoreList(MinesweeperDifficultyType type); } }
mit
C#
a8636cf55c877fcc7da478d1164b635309fa093f
Remove Application Insights modules and initializers
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
tests/LondonTravel.Site.Tests/Integration/IServiceCollectionExtensions.cs
tests/LondonTravel.Site.Tests/Integration/IServiceCollectionExtensions.cs
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using Microsoft.ApplicationInsights.DependencyCollector; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; internal static class IServiceCollectionExtensions { internal static void DisableApplicationInsights(this IServiceCollection services) { // Disable dependency tracking to work around https://github.com/Microsoft/ApplicationInsights-dotnet-server/pull/1006 services.Configure<TelemetryConfiguration>((p) => p.DisableTelemetry = true); services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>( (module, _) => { module.DisableDiagnosticSourceInstrumentation = true; module.DisableRuntimeInstrumentation = true; module.SetComponentCorrelationHttpHeaders = false; module.IncludeDiagnosticSourceActivities.Clear(); }); services.RemoveAll<ITelemetryInitializer>(); services.RemoveAll<ITelemetryModule>(); } } }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using Microsoft.ApplicationInsights.DependencyCollector; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; internal static class IServiceCollectionExtensions { internal static void DisableApplicationInsights(this IServiceCollection services) { // Disable dependency tracking to work around https://github.com/Microsoft/ApplicationInsights-dotnet-server/pull/1006 services.Configure<TelemetryConfiguration>((p) => p.DisableTelemetry = true); services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>( (module, _) => { module.DisableDiagnosticSourceInstrumentation = true; module.DisableRuntimeInstrumentation = true; module.SetComponentCorrelationHttpHeaders = false; module.IncludeDiagnosticSourceActivities.Clear(); }); } } }
apache-2.0
C#
c0340961d7c8ef36e3a76d3a17d964c21904a968
Fix compile flag
jamesmontemagno/MediaPlugin,jamesmontemagno/MediaPlugin
src/Media.Plugin/CrossMedia.cs
src/Media.Plugin/CrossMedia.cs
using Plugin.Media.Abstractions; using System; namespace Plugin.Media { /// <summary> /// Cross platform Media implemenations /// </summary> public class CrossMedia { static Lazy<IMedia> Implementation = new Lazy<IMedia>(() => CreateMedia(), System.Threading.LazyThreadSafetyMode.PublicationOnly); /// <summary> /// Current settings to use /// </summary> public static IMedia Current { get { var ret = Implementation.Value; if (ret == null) { throw NotImplementedInReferenceAssembly(); } return ret; } } static IMedia CreateMedia() { #if NETSTANDARD1_0 return null; #else return new MediaImplementation(); #endif } internal static Exception NotImplementedInReferenceAssembly() { return new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."); } } }
using Plugin.Media.Abstractions; using System; namespace Plugin.Media { /// <summary> /// Cross platform Media implemenations /// </summary> public class CrossMedia { static Lazy<IMedia> Implementation = new Lazy<IMedia>(() => CreateMedia(), System.Threading.LazyThreadSafetyMode.PublicationOnly); /// <summary> /// Current settings to use /// </summary> public static IMedia Current { get { var ret = Implementation.Value; if (ret == null) { throw NotImplementedInReferenceAssembly(); } return ret; } } static IMedia CreateMedia() { #if PORTABLE return null; #else return new MediaImplementation(); #endif } internal static Exception NotImplementedInReferenceAssembly() { return new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."); } } }
mit
C#
b1b65e94aa8c6a6128b7c86ab985f142a3b6a06e
Update AssemblyInfo.cs
cyotek/Md5
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Cyotek Simple MD5")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cyotek Ltd")] [assembly: AssemblyProduct("Cyotek Simple MD5")] [assembly: AssemblyCopyright("Copyright © 2015-2021 Cyotek Ltd. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: Guid("6c4b8feb-6199-4d1f-908f-1665161ec7f3")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.2.1.0")]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Cyotek Simple MD5")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cyotek Ltd")] [assembly: AssemblyProduct("Cyotek Simple MD5")] [assembly: AssemblyCopyright("Copyright © 2015-2021 Cyotek Ltd. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: Guid("6c4b8feb-6199-4d1f-908f-1665161ec7f3")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
mit
C#
961a351592b37164b21305d1a94cc344f7cccc63
Remove auto-generated warning from handwritten file
u255436/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,txdv/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,Samana/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,pacificIT/cxxi,ktopouzi/CppSharp,txdv/CppSharp,zillemarco/CppSharp,nalkaro/CppSharp,mohtamohit/CppSharp,xistoso/CppSharp,mono/cxxi,mydogisbox/CppSharp,SonyaSa/CppSharp,pacificIT/cxxi,mohtamohit/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,corngood/cxxi,nalkaro/CppSharp,imazen/CppSharp,xistoso/CppSharp,mono/CppSharp,inordertotest/CppSharp,txdv/CppSharp,Samana/CppSharp,txdv/CppSharp,mono/CppSharp,mono/cxxi,genuinelucifer/CppSharp,SonyaSa/CppSharp,corngood/cxxi,zillemarco/CppSharp,imazen/CppSharp,imazen/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,xistoso/CppSharp,genuinelucifer/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,SonyaSa/CppSharp,Samana/CppSharp,mono/cxxi,inordertotest/CppSharp,ddobrev/CppSharp,SonyaSa/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp,nalkaro/CppSharp,KonajuGames/CppSharp,txdv/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,mono/cxxi,imazen/CppSharp,xistoso/CppSharp,mono/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,mono/CppSharp,inordertotest/CppSharp,u255436/CppSharp,zillemarco/CppSharp,mydogisbox/CppSharp,genuinelucifer/CppSharp,pacificIT/cxxi,zillemarco/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,mono/CppSharp,ktopouzi/CppSharp,mono/CppSharp,corngood/cxxi,inordertotest/CppSharp,nalkaro/CppSharp,genuinelucifer/CppSharp,KonajuGames/CppSharp,ddobrev/CppSharp,nalkaro/CppSharp,ddobrev/CppSharp
qt/src/QSize.cs
qt/src/QSize.cs
using System; using System.Runtime.InteropServices; using Mono.Cxxi; namespace Qt.Gui { [StructLayout (LayoutKind.Sequential)] public struct QSize { public int wd; public int ht; public QSize (int w, int h) { wd = w; ht = h; } } }
// ------------------------------------------------------------------------- // Managed wrapper for QSize // Generated from qt-gui.xml on 07/24/2011 11:57:03 // // This file was auto generated. Do not edit. // ------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using Mono.Cxxi; namespace Qt.Gui { [StructLayout (LayoutKind.Sequential)] public struct QSize { public int wd; public int ht; public QSize (int w, int h) { wd = w; ht = h; } } }
mit
C#
279b9db85f01cd57ee6e3c770d935c4137bc1941
Remove using
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
samples/BehaviorsTestApplication/ViewModels/MainWindowViewModel.cs
samples/BehaviorsTestApplication/ViewModels/MainWindowViewModel.cs
using System; using System.Reactive.Linq; using System.Windows.Input; using BehaviorsTestApplication.ViewModels.Core; namespace BehaviorsTestApplication.ViewModels { public class MainWindowViewModel : ViewModelBase { private int _value; private int _count; private double _position; public int Count { get => _count; set => Update(ref _count, value); } public double Position { get => _position; set => Update(ref _position, value); } public IObservable<int> Values { get; } public ICommand MoveLeftCommand { get; set; } public ICommand MoveRightCommand { get; set; } public ICommand ResetMoveCommand { get; set; } public MainWindowViewModel() { Count = 0; Position = 100.0; MoveLeftCommand = new Command((param) => Position -= 5.0); MoveRightCommand = new Command((param) => Position += 5.0); ResetMoveCommand = new Command((param) => Position = 100.0); Values = Observable.Interval(TimeSpan.FromSeconds(1)).Select(_ => _value++); } public void IncrementCount() => Count++; public void DecrementCount(object? sender, object parameter) => Count--; } }
using System; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Windows.Input; using BehaviorsTestApplication.ViewModels.Core; namespace BehaviorsTestApplication.ViewModels { public class MainWindowViewModel : ViewModelBase { private int _value; private int _count; private double _position; public int Count { get => _count; set => Update(ref _count, value); } public double Position { get => _position; set => Update(ref _position, value); } public IObservable<int> Values { get; } public ICommand MoveLeftCommand { get; set; } public ICommand MoveRightCommand { get; set; } public ICommand ResetMoveCommand { get; set; } public MainWindowViewModel() { Count = 0; Position = 100.0; MoveLeftCommand = new Command((param) => Position -= 5.0); MoveRightCommand = new Command((param) => Position += 5.0); ResetMoveCommand = new Command((param) => Position = 100.0); Values = Observable.Interval(TimeSpan.FromSeconds(1)).Select(_ => _value++); } public void IncrementCount() => Count++; public void DecrementCount(object? sender, object parameter) => Count--; } }
mit
C#
d8e2d84609e1d121bbf6ed94ca3813972893401d
Change the names to be in line with the problem at hand.
jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes
ConsoleApps/FunWithSpikes/FunWithNinject/OpenGenerics/OpenGenericsTests.cs
ConsoleApps/FunWithSpikes/FunWithNinject/OpenGenerics/OpenGenericsTests.cs
using Ninject; using NUnit.Framework; using System; namespace FunWithNinject.OpenGenerics { [TestFixture] public class OpenGenericsTests { [Test] public void OpenGenericBinding() { using (var k = new StandardKernel()) { // Assemble k.Bind(typeof(IAutoCache<>)).To(typeof(AutoCache<>)); // Act var dependsOn = k.Get<DependsOnLogger>(); // Assert Assert.AreEqual(typeof(int), dependsOn.CacheType); } } #region Types public interface IAutoCache<T> { Type CacheType { get; } } public class AutoCache<T> : IAutoCache<T> { public Type CacheType { get { return typeof(T); } } } public class DependsOnLogger { public DependsOnLogger(IAutoCache<int> intCacher) { CacheType = intCacher.CacheType; } public Type CacheType { get; set; } } #endregion } }
using Ninject; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FunWithNinject.OpenGenerics { [TestFixture] public class OpenGenericsTests { public interface ILogger<T> { Type GenericParam { get; } } public class Logger<T> : ILogger<T> { public Type GenericParam { get { return typeof(T); } } } public class DependsOnLogger { public DependsOnLogger(ILogger<int> intLogger) { GenericParam = intLogger.GenericParam; } public Type GenericParam { get; set; } } [Test] public void OpenGenericBinding() { using (var k = new StandardKernel()) { // Assemble k.Bind(typeof(ILogger<>)).To(typeof(Logger<>)); // Act var dependsOn = k.Get<DependsOnLogger>(); // Assert Assert.AreEqual(typeof(int), dependsOn.GenericParam); } } } }
mit
C#
f0414cfb025d9606dbad1d699c652eecd4e4b565
fix invalid codegen in AutoDetect
robinrodricks/FluentFTP,robinrodricks/FluentFTP,robinrodricks/FluentFTP
FluentFTP/Helpers/FtpProfile.cs
FluentFTP/Helpers/FtpProfile.cs
using System; using System.Collections.Generic; using System.Net; using System.Security.Authentication; using System.Text; namespace FluentFTP { public class FtpProfile { /// <summary> /// The host IP address or URL of the FTP server /// </summary> public string Host; /// <summary> /// The FTP username and password used to login /// </summary> public NetworkCredential Credentials; /// <summary> /// A working Encryption Mode found for this profile /// </summary> public FtpEncryptionMode Encryption = FtpEncryptionMode.None; /// <summary> /// A working Ssl Protocol setting found for this profile /// </summary> public SslProtocols Protocols = SslProtocols.None; /// <summary> /// A working Data Connection Type found for this profile /// </summary> public FtpDataConnectionType DataConnection = FtpDataConnectionType.PASV; /// <summary> /// A working Encoding setting found for this profile /// </summary> public Encoding Encoding; /// <summary> /// Generates valid C# code for this connection profile. /// </summary> /// <returns></returns> public string ToCode() { var sb = new StringBuilder(); sb.AppendLine("// add this above your namespace declaration"); sb.AppendLine("using FluentFTP;"); sb.AppendLine("using System.Text;"); sb.AppendLine("using System.Net;"); sb.AppendLine("using System.Security.Authentication;"); sb.AppendLine(); sb.AppendLine("// add this to create and configure the FTP client"); sb.AppendLine("var client = new FtpClient();"); sb.AppendLine("client.Host = " + Host.EscapeStringLiteral() + ";"); sb.AppendLine("client.Credentials = new NetworkCredential(" + Credentials.UserName.EscapeStringLiteral() + ", " + Credentials.Password.EscapeStringLiteral() + ");"); sb.Append("client.EncryptionMode = FtpEncryptionMode."); sb.Append(Encryption.ToString()); sb.AppendLine(";"); sb.Append("client.SslProtocols = SslProtocols."); sb.Append(Protocols.ToString()); sb.AppendLine(";"); sb.Append("client.DataConnectionType = FtpDataConnectionType."); sb.Append(DataConnection.ToString()); sb.AppendLine(";"); sb.Append("client.Encoding = "); // Fix #468 - Invalid code generated: Encoding = System.Text.UTF8Encoding+UTF8EncodingSealed var encoding = Encoding.ToString(); sb.Append(encoding.Contains("+") ? encoding.Substring(0, encoding.IndexOf('+')) : encoding); sb.AppendLine(";"); if (Encryption != FtpEncryptionMode.None) { sb.AppendLine("// if you want to accept any certificate then set ValidateAnyCertificate=true and delete the following event handler"); sb.AppendLine("client.ValidateCertificate += new FtpSslValidation(delegate (FtpClient control, FtpSslValidationEventArgs e) {"); sb.AppendLine(" // add your logic to test if the SSL certificate is valid (see the FAQ for examples)"); sb.AppendLine(" e.Accept = true;"); sb.AppendLine("});"); } sb.AppendLine("client.Connect();"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Net; using System.Security.Authentication; using System.Text; namespace FluentFTP { public class FtpProfile { /// <summary> /// The host IP address or URL of the FTP server /// </summary> public string Host; /// <summary> /// The FTP username and password used to login /// </summary> public NetworkCredential Credentials; /// <summary> /// A working Encryption Mode found for this profile /// </summary> public FtpEncryptionMode Encryption = FtpEncryptionMode.None; /// <summary> /// A working Ssl Protocol setting found for this profile /// </summary> public SslProtocols Protocols = SslProtocols.None; /// <summary> /// A working Data Connection Type found for this profile /// </summary> public FtpDataConnectionType DataConnection = FtpDataConnectionType.PASV; /// <summary> /// A working Encoding setting found for this profile /// </summary> public Encoding Encoding; /// <summary> /// Generates valid C# code for this connection profile. /// </summary> /// <returns></returns> public string ToCode() { var sb = new StringBuilder(); sb.AppendLine("// add this above your namespace declaration"); sb.AppendLine("using FluentFTP;"); sb.AppendLine("using System.Text;"); sb.AppendLine("using System.Net;"); sb.AppendLine("using System.Security.Authentication;"); sb.AppendLine(); sb.AppendLine("// add this to create and configure the FTP client"); sb.AppendLine("var client = new FtpClient();"); sb.AppendLine("client.Host = " + Host.EscapeStringLiteral() + ";"); sb.AppendLine("client.Credentials = new NetworkCredential(" + Credentials.UserName.EscapeStringLiteral() + ", " + Credentials.Password.EscapeStringLiteral() + ");"); sb.Append("client.EncryptionMode = FtpEncryptionMode."); sb.Append(Encryption.ToString()); sb.AppendLine(";"); sb.Append("client.SslProtocols = SslProtocols."); sb.Append(Protocols.ToString()); sb.AppendLine(";"); sb.Append("client.DataConnectionType = FtpDataConnectionType."); sb.Append(DataConnection.ToString()); sb.AppendLine(";"); sb.Append("client.Encoding = "); sb.Append(Encoding.ToString()); sb.AppendLine(";"); if (Encryption != FtpEncryptionMode.None) { sb.AppendLine("client.ValidateCertificate += new FtpSslValidation(delegate (FtpClient control, FtpSslValidationEventArgs e) {"); sb.AppendLine(" // add your logic to test if the SSL certificate is valid (see the FAQ for examples)"); sb.AppendLine(" e.Accept = true;"); sb.AppendLine("});"); } sb.AppendLine("client.Connect();"); return sb.ToString(); } } }
mit
C#
c8049d7ef83d2eccfceab0152d4650059dfef90d
Add test for the Abstract schema.
boumenot/lezen,boumenot/lezen
test/Lezen.Core.Test/Search/DocumentFactoryTest.cs
test/Lezen.Core.Test/Search/DocumentFactoryTest.cs
using Lezen.Core.Search; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace Lezen.Core.Test.Search { public class DocumentFactoryTest { [Fact] public void DocumentShouldHaveCorrectFieldNames() { var searchItem = new SearchItem { Abstract = "--abstract--", Keywords = new[] { "keyword1", "keyword2", "keyword3" }, Text = "--text--", }; var testSubject = new DocumentFactory(); var document = testSubject.Create(searchItem); var fields = document.GetFields(); var names = String.Join(",", fields.Select(x => x.Name).ToArray()); //names.Should().Be("donkey"); fields.Any(x => x.Name == "Abstract").Should().BeTrue(); fields.Any(x => x.Name == "Text").Should().BeTrue(); fields.Count(x => x.Name == "Keyword").Should().Be(3); document.Get("Abstract").Should().Be("--abstract--"); document.Get("Text").Should().Be("--text--"); document.GetValues("Keyword").Should().HaveCount(3); document.GetValues("Keyword").Should().Contain("keyword1", "keyword2", "keyword3"); } [Fact] public void AbstractShouldBeAnalyzedField() { var searchItem = new SearchItem { Abstract = "--abstract--", Keywords = new[] { "keyword1", "keyword2", "keyword3" }, Text = "--text--", }; var testSubject = new DocumentFactory(); var document = testSubject.Create(searchItem); var abstractField = document.GetField("Abstract"); abstractField.IsBinary.Should().BeFalse(); abstractField.IsIndexed.Should().BeTrue(); abstractField.IsLazy.Should().BeFalse(); abstractField.IsStored.Should().BeTrue(); abstractField.IsStoreOffsetWithTermVector.Should().BeTrue(); abstractField.IsStorePositionWithTermVector.Should().BeTrue(); abstractField.IsTermVectorStored.Should().BeTrue(); abstractField.IsTokenized.Should().BeTrue(); abstractField.OmitNorms.Should().BeFalse(); abstractField.OmitTermFreqAndPositions.Should().BeFalse(); } } }
using Lezen.Core.Search; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace Lezen.Core.Test.Search { public class DocumentFactoryTest { [Fact] public void Test() { var searchItem = new SearchItem { Abstract = "--abstract--", Keywords = new[] { "keyword1", "keyword2", "keyword3" }, Text = "--text--", }; var testSubject = new DocumentFactory(); var document = testSubject.Create(searchItem); var fields = document.GetFields(); var names = String.Join(",", fields.Select(x => x.Name).ToArray()); //names.Should().Be("donkey"); fields.Any(x => x.Name == "Abstract").Should().BeTrue(); fields.Any(x => x.Name == "Text").Should().BeTrue(); fields.Count(x => x.Name == "Keyword").Should().Be(3); document.Get("Abstract").Should().Be("--abstract--"); document.Get("Text").Should().Be("--text--"); document.GetValues("Keyword").Should().HaveCount(3); document.GetValues("Keyword").Should().Contain("keyword1", "keyword2", "keyword3"); } } }
apache-2.0
C#
040272f9ca870d8b4c3a1495b2f40bae04535969
rename duration metric on telemetry button so it can be filtered more specifically in App Insights dashboard
bc3tech/DesktopApplicationInsights
DesktopApplicationInsights/TelemetryButton.cs
DesktopApplicationInsights/TelemetryButton.cs
 using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.ApplicationInsights.DataContracts; namespace DesktopApplicationInsights { /// <summary>A <c>Button</c> class that automatically logs telemetry data when clicked</summary> [DesignTimeVisible] public class TelemetryButton : Button { /// <summary> /// Gets or sets the Event Name to use when logging the Button's execution /// </summary> [EditorBrowsable] public string EventName { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is timed. <c>true</c> to attach execution /// duration to the logged event. <c>false</c> otherwise. /// </summary> [EditorBrowsable] public bool IsTimed { get; set; } /// <summary> /// Raises the <see cref="E:Click" /> event. /// </summary> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected override void OnClick(EventArgs e) { var startTime = DateTime.UtcNow; base.OnClick(e); if (!string.IsNullOrWhiteSpace(this.EventName)) { var telemetryData = new EventTelemetry(this.EventName); telemetryData.Timestamp = startTime; if (this.IsTimed) { telemetryData.Metrics.Add(string.Concat(this.EventName, "_Duration"), (DateTime.UtcNow - startTime).TotalMilliseconds); } Telemetry.Client.TrackEvent(telemetryData); } } } }
 using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.ApplicationInsights.DataContracts; namespace DesktopApplicationInsights { /// <summary>A <c>Button</c> class that automatically logs telemetry data when clicked</summary> [DesignTimeVisible] public class TelemetryButton : Button { /// <summary> /// Gets or sets the Event Name to use when logging the Button's execution /// </summary> [EditorBrowsable] public string EventName { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is timed. <c>true</c> to attach execution /// duration to the logged event. <c>false</c> otherwise. /// </summary> [EditorBrowsable] public bool IsTimed { get; set; } /// <summary> /// Raises the <see cref="E:Click" /> event. /// </summary> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected override void OnClick(EventArgs e) { var startTime = DateTime.UtcNow; base.OnClick(e); if (!string.IsNullOrWhiteSpace(this.EventName)) { var telemetryData = new EventTelemetry(this.EventName); telemetryData.Timestamp = startTime; if (this.IsTimed) { telemetryData.Metrics.Add("Duration", (DateTime.UtcNow - startTime).TotalMilliseconds); } Telemetry.Client.TrackEvent(telemetryData); } } } }
mit
C#
c042c8b5fcdf03ff23737229e59b1c50c82f6b7c
Set up references for event command unit tests
DavidMGardner/sogeti.capstone,DavidMGardner/sogeti.capstone,DavidMGardner/sogeti.capstone
Sogeti.Capstone.Web/Sogeti.Capstone.CQS.Integration.Tests/EventCommands.cs
Sogeti.Capstone.Web/Sogeti.Capstone.CQS.Integration.Tests/EventCommands.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sogeti.Capstone.CQS.Integration.Tests { [TestClass] public class EventCommands { [TestMethod] public void CreateEventCommand() { } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sogeti.Capstone.CQS.Integration.Tests { [TestClass] public class EventCommands { [TestMethod] public void CreateEventCommand() { } } }
mit
C#
1217fecb170052e2cee355e76992c4919f36793a
check if null before trying to dispose
Willster419/RelhaxModpack,Willster419/RelhaxModpack,Willster419/RelicModManager
RelhaxModpack/RelhaxModpack/Database/Trigger.cs
RelhaxModpack/RelhaxModpack/Database/Trigger.cs
using RelhaxModpack.Database; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RelhaxModpack.Database { /// <summary> /// Represents a trigger object used in the installer as an event starter. /// For example, a contour icon trigger exists to start the building of contour icons /// </summary> public class Trigger : IDisposable { public Trigger() : base() { } public Trigger(Trigger triggerToCopy) { this.Name = triggerToCopy.Name; } /// <summary> /// The name of the trigger /// </summary> public string Name { get; set; } /// <summary> /// The total number of instances that this trigger exists in the selected packages to install /// </summary> public int Total { get; set; } /// <summary> /// The number of processed triggers for this trigger type. Prevents the trigger from firing early /// </summary> public int NumberProcessed { get; set; } /// <summary> /// Flag to determine if the trigger task has started /// </summary> public bool Fired { get; set; } /// <summary> /// The reference for the task that the trigger should perform /// </summary> public Task TriggerTask { get; set; } public void Dispose() { if (TriggerTask != null) TriggerTask.Dispose(); } } }
using RelhaxModpack.Database; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RelhaxModpack.Database { /// <summary> /// Represents a trigger object used in the installer as an event starter. /// For example, a contour icon trigger exists to start the building of contour icons /// </summary> public class Trigger : IDisposable { public Trigger() : base() { } public Trigger(Trigger triggerToCopy) { this.Name = triggerToCopy.Name; } /// <summary> /// The name of the trigger /// </summary> public string Name { get; set; } /// <summary> /// The total number of instances that this trigger exists in the selected packages to install /// </summary> public int Total { get; set; } /// <summary> /// The number of processed triggers for this trigger type. Prevents the trigger from firing early /// </summary> public int NumberProcessed { get; set; } /// <summary> /// Flag to determine if the trigger task has started /// </summary> public bool Fired { get; set; } /// <summary> /// The reference for the task that the trigger should perform /// </summary> public Task TriggerTask { get; set; } public void Dispose() { TriggerTask.Dispose(); } } }
apache-2.0
C#
32a601a3ac1f99302c0f77a51058cf5b43d62524
Update state to be used after redirect
projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,fashaikh/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS
SimpleWAWS/Authentication/GoogleAuthProvider.cs
SimpleWAWS/Authentication/GoogleAuthProvider.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()|| context.IsFunctionsPortalRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }
apache-2.0
C#
012596e5ca88b2f46a3e485f50b9c614ab3b4e20
Add Rank to returned scores
brentstineman/nether,brentstineman/nether,brentstineman/nether,krist00fer/nether,navalev/nether,vflorusso/nether,brentstineman/nether,stuartleeks/nether,brentstineman/nether,MicrosoftDX/nether,vflorusso/nether,navalev/nether,stuartleeks/nether,stuartleeks/nether,vflorusso/nether,navalev/nether,ankodu/nether,stuartleeks/nether,stuartleeks/nether,ankodu/nether,navalev/nether,ankodu/nether,vflorusso/nether,ankodu/nether,vflorusso/nether,oliviak/nether
src/Nether.Web/Features/Leaderboard/LeaderboardGetResponseModel.cs
src/Nether.Web/Features/Leaderboard/LeaderboardGetResponseModel.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Nether.Data.Leaderboard; namespace Nether.Web.Features.Leaderboard { public class LeaderboardGetResponseModel { public List<LeaderboardEntry> Entries { get; set; } public class LeaderboardEntry { public static implicit operator LeaderboardEntry(GameScore score) { return new LeaderboardEntry { Gamertag = score.Gamertag, Score = score.Score, Rank = score.Rank }; } /// <summary> /// Gamertag /// </summary> public string Gamertag { get; set; } /// <summary> /// Scores /// </summary> public int Score { get; set; } public long Rank { get; set; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Nether.Data.Leaderboard; namespace Nether.Web.Features.Leaderboard { public class LeaderboardGetResponseModel { public List<LeaderboardEntry> Entries { get; set; } public class LeaderboardEntry { public static implicit operator LeaderboardEntry(GameScore score) { return new LeaderboardEntry { Gamertag = score.Gamertag, Score = score.Score }; } /// <summary> /// Gamertag /// </summary> public string Gamertag { get; set; } /// <summary> /// Scores /// </summary> public int Score { get; set; } } } }
mit
C#
6d666c7d8199a488c2e43d5115e8f8982a5df422
Remove unneded test
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/SpecialTests/DbCastTests.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/SpecialTests/DbCastTests.cs
using System.Data; using FakeItEasy; using NUnit.Framework; using Smooth.IoC.Repository.UnitOfWork.Tests.TestHelpers; using Smooth.IoC.UnitOfWork; namespace Smooth.IoC.Repository.UnitOfWork.Tests.SpecialTests { [TestFixture] public class DbCastTests { [Test, Category("Integration")] public static void ISession_Is_IDbConnectionAndIsConnected() { using (var session = new TestSessionMemory(A.Fake<IDbFactory>())) { Assert.That(session.State, Is.EqualTo(ConnectionState.Open)); var connection = (IDbConnection) session; Assert.That(connection.State, Is.EqualTo(ConnectionState.Open)); } using (IDbConnection session = new TestSessionMemory(A.Fake<IDbFactory>())) { Assert.That(session.State, Is.EqualTo(ConnectionState.Open)); } } } }
using System.Data; using FakeItEasy; using NUnit.Framework; using Smooth.IoC.Repository.UnitOfWork.Tests.TestHelpers; using Smooth.IoC.UnitOfWork; namespace Smooth.IoC.Repository.UnitOfWork.Tests.SpecialTests { [TestFixture] public class DbCastTests { [Test, Category("Integration")] public static void ISession_Is_IDbConnectionAndIsConnected() { using (var session = new TestSessionMemory(A.Fake<IDbFactory>())) { Assert.That(session.State, Is.EqualTo(ConnectionState.Open)); var connection = (IDbConnection) session; Assert.That(connection.State, Is.EqualTo(ConnectionState.Open)); } using (IDbConnection session = new TestSessionMemory(A.Fake<IDbFactory>())) { Assert.That(session.State, Is.EqualTo(ConnectionState.Open)); } } [Test, Category("Integration")] public static void IUnitOfWork_Is_IDbTransactionAndIsConnected() { var factory = A.Fake<IDbFactory>(); var session = new TestSessionMemory(factory); using (var uow = new IoC.UnitOfWork.UnitOfWork(factory, session, IsolationLevel.Serializable)) { Assert.That(uow.Connection.State, Is.EqualTo(ConnectionState.Open)); var transaction = (IDbTransaction)uow; Assert.That(transaction.Connection.State, Is.EqualTo(ConnectionState.Open)); } using (var uow = new IoC.UnitOfWork.UnitOfWork(factory, session, IsolationLevel.Serializable)) { Assert.That(uow.Connection.State, Is.EqualTo(ConnectionState.Open)); } } } }
mit
C#
0bee819f72023b33d68151e315edf5a586526a76
Use IETF language tag for culture component of cache key
roman-yagodin/R7.Documents,roman-yagodin/R7.Documents,roman-yagodin/R7.Documents
R7.Documents/components/ModuleSynchronizer.cs
R7.Documents/components/ModuleSynchronizer.cs
// // ModuleSynchronizer.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // 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 DotNetNuke.UI.Utilities; using DotNetNuke.Entities.Modules; using System.Globalization; namespace R7.Documents { public static class ModuleSynchronizer { public static string GetDataCacheKey (int moduleId, int tabModuleId) { return "//r7_Documents?ModuleId=" + moduleId + "&Culture=" + CultureInfo.CurrentCulture.IetfLanguageTag; } public static void Synchronize (int moduleId, int tabModuleId) { ModuleController.SynchronizeModule (moduleId); DataCache.RemoveCache (GetDataCacheKey (moduleId, tabModuleId)); } } }
// // ModuleSynchronizer.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2016 Roman M. Yagodin // // 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 DotNetNuke.UI.Utilities; using DotNetNuke.Entities.Modules; using System.Threading; namespace R7.Documents { public static class ModuleSynchronizer { public static string GetDataCacheKey (int moduleId, int tabModuleId) { return "//r7_Documents?ModuleId=" + moduleId + "&Culture=" + Thread.CurrentThread.CurrentCulture; } public static void Synchronize (int moduleId, int tabModuleId) { ModuleController.SynchronizeModule (moduleId); DataCache.RemoveCache (GetDataCacheKey (moduleId, tabModuleId)); } } }
mit
C#
9996f3662ae05e4704ae9929d56b325a46d8cf5c
update to 2.7
dwmkerr/sharpshell,dwmkerr/sharpshell,dwmkerr/sharpshell,dwmkerr/sharpshell
SharpShell/SharedAssemblyInfo.cs
SharpShell/SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Shared Assembly Information for all projects in SharpShell. [assembly: AssemblyCompany("Dave Kerr")] [assembly: AssemblyProduct("SharpShell")] [assembly: AssemblyCopyright("Copyright © Dave Kerr 2018")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.7.0.0")] [assembly: AssemblyFileVersion("2.7.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Shared Assembly Information for all projects in SharpShell. [assembly: AssemblyCompany("Dave Kerr")] [assembly: AssemblyProduct("SharpShell")] [assembly: AssemblyCopyright("Copyright © Dave Kerr 2018")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.6.1.0")] [assembly: AssemblyFileVersion("2.6.1.0")]
mit
C#
e9ed2263a208cf0c1b443773d64e147164247101
Change "RSS Feed" "Font Size" default value
danielchalmers/DesktopWidgets
DesktopWidgets/Widgets/RSSFeed/Settings.cs
DesktopWidgets/Widgets/RSSFeed/Settings.cs
using System; using System.Collections.Generic; using System.ComponentModel; using DesktopWidgets.Classes; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.RSSFeed { public class Settings : WidgetSettingsBase { public Settings() { Style.FontSettings.FontSize = 16; } [Category("Style")] [DisplayName("Max Headlines")] public int MaxHeadlines { get; set; } = 5; [Category("General")] [DisplayName("Refresh Interval")] public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromHours(1); [Category("Feed")] [DisplayName("URL")] public string RssFeedUrl { get; set; } [Category("Feed (Filter)")] [DisplayName("Title Whitelist")] public List<string> TitleWhitelist { get; set; } = new List<string>(); [Category("Feed (Filter)")] [DisplayName("Title Blacklist")] public List<string> TitleBlacklist { get; set; } = new List<string>(); [Category("Feed (Filter)")] [DisplayName("Category Whitelist")] public List<string> CategoryWhitelist { get; set; } = new List<string>(); [Category("Style")] [DisplayName("Show Publish Date")] public bool ShowPublishDate { get; set; } [Category("Style")] [DisplayName("Publish Date Font Settings")] public FontSettings PublishDateFontSettings { get; set; } = new FontSettings {FontSize = 11}; [Category("Style")] [DisplayName("Publish Date Format")] public string PublishDateFormat { get; set; } = ""; [Category("Style")] [DisplayName("Publish Date Time Offset")] public TimeSpan PublishDateTimeOffset { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using DesktopWidgets.Classes; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.RSSFeed { public class Settings : WidgetSettingsBase { [Category("Style")] [DisplayName("Max Headlines")] public int MaxHeadlines { get; set; } = 5; [Category("General")] [DisplayName("Refresh Interval")] public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromHours(1); [Category("Feed")] [DisplayName("URL")] public string RssFeedUrl { get; set; } [Category("Feed (Filter)")] [DisplayName("Title Whitelist")] public List<string> TitleWhitelist { get; set; } = new List<string>(); [Category("Feed (Filter)")] [DisplayName("Title Blacklist")] public List<string> TitleBlacklist { get; set; } = new List<string>(); [Category("Feed (Filter)")] [DisplayName("Category Whitelist")] public List<string> CategoryWhitelist { get; set; } = new List<string>(); [Category("Style")] [DisplayName("Show Publish Date")] public bool ShowPublishDate { get; set; } [Category("Style")] [DisplayName("Publish Date Font Settings")] public FontSettings PublishDateFontSettings { get; set; } = new FontSettings {FontSize = 11}; [Category("Style")] [DisplayName("Publish Date Format")] public string PublishDateFormat { get; set; } = ""; [Category("Style")] [DisplayName("Publish Date Time Offset")] public TimeSpan PublishDateTimeOffset { get; set; } } }
apache-2.0
C#
de9f0f4a12679f8945a0c9209f194ac898d36c5a
add argument validation to !ird
RPCS3/discord-bot
CompatBot/Commands/Ird.cs
CompatBot/Commands/Ird.cs
using System.Threading.Tasks; using CompatBot.Commands.Attributes; using CompatBot.Utils; using CompatBot.Utils.ResultFormatters; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using IrdLibraryClient; namespace CompatBot.Commands { internal sealed class Ird: BaseCommandModuleCustom { private static readonly IrdClient Client = new IrdClient(); [Command("ird"), TriggersTyping] [Description("Searches IRD Library for the matching .ird files")] public async Task Search(CommandContext ctx, [RemainingText, Description("Product code or game title to look up")] string query) { if (string.IsNullOrEmpty(query)) { await ctx.ReactWithAsync(Config.Reactions.Failure, "Can't search for nothing, boss").ConfigureAwait(false); return; } var result = await Client.SearchAsync(query, Config.Cts.Token).ConfigureAwait(false); var embed = result.AsEmbed(); await ctx.RespondAsync(embed: embed).ConfigureAwait(false); } } }
using System.Threading.Tasks; using CompatBot.Commands.Attributes; using CompatBot.Utils.ResultFormatters; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using IrdLibraryClient; namespace CompatBot.Commands { internal sealed class Ird: BaseCommandModuleCustom { private static readonly IrdClient Client = new IrdClient(); [Command("ird"), TriggersTyping] [Description("Searches IRD Library for the matching .ird files")] public async Task Search(CommandContext ctx, [RemainingText, Description("Product code or game title to look up")] string query) { var result = await Client.SearchAsync(query, Config.Cts.Token).ConfigureAwait(false); var embed = result.AsEmbed(); await ctx.RespondAsync(embed: embed).ConfigureAwait(false); } } }
lgpl-2.1
C#
173fd82255624147fdbcdadbe495da359d95f7a3
Add correct JSON serialization for enum type
stoiveyp/Alexa.NET.Management
Alexa.NET.Management/Api/CustomApiEndpoint.cs
Alexa.NET.Management/Api/CustomApiEndpoint.cs
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Text; namespace Alexa.NET.Management.Api { public class CustomApiEndpoint { [JsonProperty("uri")] public string Uri { get; set; } [JsonProperty("sslCertificateType"), JsonConverter(typeof(StringEnumConverter))] public SslCertificateType SslCertificateType { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Alexa.NET.Management.Api { public class CustomApiEndpoint { [JsonProperty("uri")] public string Uri { get; set; } [JsonProperty("sslCertificateType")] public SslCertificateType SslCertificateType { get; set; } } }
mit
C#
e666ffa1db62a24c046a26271a1c4ddda69ab0b7
Add ssh support to DockerUri
mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker
Ductus.FluentDocker/Model/Common/DockerUri.cs
Ductus.FluentDocker/Model/Common/DockerUri.cs
using System; using Ductus.FluentDocker.Common; using Ductus.FluentDocker.Extensions; namespace Ductus.FluentDocker.Model.Common { public sealed class DockerUri : Uri { private const string DockerHost = "DOCKER_HOST"; private const string DockerHostUrlWindowsNative = "npipe://./pipe/docker_engine"; private const string DockerHostUrlLegacy = "tcp://localhost:2375"; private const string DockerHostUrlMacOrLinux = "unix:///var/run/docker.sock"; public DockerUri(string uriString) : base(uriString) { } public static string GetDockerHostEnvironmentPathOrDefault() { var env = Environment.GetEnvironmentVariable(DockerHost); if (null != env) { return env; } if (FdOs.IsWindows()) { return CommandExtensions.IsToolbox() ? DockerHostUrlLegacy : DockerHostUrlWindowsNative; } return CommandExtensions.IsToolbox() ? DockerHostUrlLegacy : DockerHostUrlMacOrLinux; } public override string ToString() { var baseString = base.ToString(); if (Scheme == "ssh") return baseString.TrimEnd('/'); if (Scheme == "npipe") return baseString.Substring(0, 6) + "//" + baseString.Substring(6); return baseString; } } }
using System; using Ductus.FluentDocker.Common; using Ductus.FluentDocker.Extensions; namespace Ductus.FluentDocker.Model.Common { public sealed class DockerUri : Uri { private const string DockerHost = "DOCKER_HOST"; private const string DockerHostUrlWindowsNative = "npipe://./pipe/docker_engine"; private const string DockerHostUrlLegacy = "tcp://localhost:2375"; private const string DockerHostUrlMacOrLinux = "unix:///var/run/docker.sock"; public DockerUri(string uriString) : base(uriString) { } public static string GetDockerHostEnvironmentPathOrDefault() { var env = Environment.GetEnvironmentVariable(DockerHost); if (null != env) { return env; } if (FdOs.IsWindows()) { return CommandExtensions.IsToolbox() ? DockerHostUrlLegacy : DockerHostUrlWindowsNative; } return CommandExtensions.IsToolbox() ? DockerHostUrlLegacy : DockerHostUrlMacOrLinux; } public override string ToString() { if (Scheme != "npipe") return base.ToString(); var s = base.ToString(); return s.Substring(0, 6) + "//" + s.Substring(6); } } }
apache-2.0
C#
687c19fce5843edf06464fb3f7d40f9d9ad6a848
Add MdiTabPage and use IDockableControl.CaptionText as tab header text.
PenguinF/sandra-three
Eutherion/Win.MdiAppTemplate/MdiTabControl.cs
Eutherion/Win.MdiAppTemplate/MdiTabControl.cs
#region License /********************************************************************************* * MdiTabControl.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using Eutherion.Win.Controls; using System; using System.Windows.Forms; namespace Eutherion.Win.MdiAppTemplate { /// <summary> /// Represents a control with <see cref="TabControl"/>-like capabilities, that hosts a <see cref="IDockableControl"/> /// in each of its tab pages. Its tab headers cannot receive focus, instead the control exposes keyboard shortcuts /// to navigate between tab pages. /// </summary> public class MdiTabControl : GlyphTabControl, IDockableControl { public DockProperties DockProperties { get; } = new DockProperties(); public event Action DockPropertiesChanged; public void OnClosing(CloseReason closeReason, ref bool cancel) { } } public abstract class MdiTabPage : GlyphTabControl.TabPage { public IDockableControl DockedControl { get; } private protected MdiTabPage(IDockableControl dockedControl, Control clientControl) : base(clientControl) { DockedControl = dockedControl; } } public class MdiTabPage<TDockableControl> : MdiTabPage where TDockableControl : Control, IDockableControl { public MdiTabPage(TDockableControl clientControl) : base(clientControl, clientControl) { UpdateFromDockProperties(DockedControl.DockProperties); DockedControl.DockPropertiesChanged += () => UpdateFromDockProperties(DockedControl.DockProperties); } private void UpdateFromDockProperties(DockProperties dockProperties) { Text = dockProperties.CaptionText; } } }
#region License /********************************************************************************* * MdiTabControl.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using Eutherion.Win.Controls; using System; using System.Windows.Forms; namespace Eutherion.Win.MdiAppTemplate { /// <summary> /// Represents a control with <see cref="TabControl"/>-like capabilities, that hosts a <see cref="IDockableControl"/> /// in each of its tab pages. Its tab headers cannot receive focus, instead the control exposes keyboard shortcuts /// to navigate between tab pages. /// </summary> public class MdiTabControl : GlyphTabControl, IDockableControl { public DockProperties DockProperties { get; } = new DockProperties(); public event Action DockPropertiesChanged; public void OnClosing(CloseReason closeReason, ref bool cancel) { } } }
apache-2.0
C#
69eb597bc929cc4194fedce532b973e7a748d53b
Use BigInteger.One
martincostello/project-euler
src/ProjectEuler/Puzzles/Puzzle025.cs
src/ProjectEuler/Puzzles/Puzzle025.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System.Collections.Generic; using System.Globalization; using System.Numerics; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=25</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle025 : Puzzle { /// <summary> /// The <see cref="BigInteger"/> that is the first number with 1,000 digits. This field is read-only. /// </summary> private static readonly BigInteger Limit = BigInteger.Parse("1" + new string('0', 999), CultureInfo.InvariantCulture); /// <inheritdoc /> public override string Question => "What is the number of the first term in the Fibonacci sequence to contain 1,000 digits?"; /// <summary> /// Returns an <see cref="IEnumerable{T}"/> of <see cref="BigInteger"/> that enumerates the Fibonacci sequence. /// </summary> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="BigInteger"/> that enumerates the Fibonacci sequence. /// </returns> internal static IEnumerable<BigInteger> Fibonacci() { var x = BigInteger.One; var y = BigInteger.One; yield return x; yield return y; while (true) { BigInteger next = x + y; yield return next; x = y; y = next; } } /// <inheritdoc /> protected override int SolveCore(string[] args) { int index = 0; foreach (BigInteger value in Fibonacci()) { index++; if (value >= Limit) { Answer = index; break; } } return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System.Collections.Generic; using System.Globalization; using System.Numerics; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=25</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle025 : Puzzle { /// <summary> /// The <see cref="BigInteger"/> that is the first number with 1,000 digits. This field is read-only. /// </summary> private static readonly BigInteger Limit = BigInteger.Parse("1" + new string('0', 999), CultureInfo.InvariantCulture); /// <inheritdoc /> public override string Question => "What is the number of the first term in the Fibonacci sequence to contain 1,000 digits?"; /// <summary> /// Returns an <see cref="IEnumerable{T}"/> of <see cref="BigInteger"/> that enumerates the Fibonacci sequence. /// </summary> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="BigInteger"/> that enumerates the Fibonacci sequence. /// </returns> internal static IEnumerable<BigInteger> Fibonacci() { BigInteger x = 1; BigInteger y = 1; yield return x; yield return y; while (true) { BigInteger next = x + y; yield return next; x = y; y = next; } } /// <inheritdoc /> protected override int SolveCore(string[] args) { int index = 0; foreach (BigInteger value in Fibonacci()) { index++; if (value >= Limit) { Answer = index; break; } } return 0; } } }
apache-2.0
C#
6989e2769b14f14415920133b138ee47d359e09a
test push to nuget again
DimensionDataCBUSydney/Compute.Api.Client
ComputeClient/Compute.Contracts/Image20/CleanCustomerImageIdType.cs
ComputeClient/Compute.Contracts/Image20/CleanCustomerImageIdType.cs
namespace DD.CBU.Compute.Api.Contracts.Image20 { /// <remarks/> [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types")] [System.Xml.Serialization.XmlRootAttribute("cleanCustomerImage", Namespace = "urn:didata.com:api:cloud:types", IsNullable = false)] public partial class CleanCustomerImageIdType { /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string id; } }
namespace DD.CBU.Compute.Api.Contracts.Image20 { /// <remarks/> [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types")] [System.Xml.Serialization.XmlRootAttribute("cleanCustomerImage", Namespace = "urn:didata.com:api:cloud:types", IsNullable = false)] public partial class CleanCustomerImageIdType { /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string id; } }
mit
C#
03270f329fcfa617c4dabb0bf87d0ab3936fccea
Enable test parallelization
Maxwe11/NModbus4,NModbus/NModbus,NModbus4/NModbus4
NModbus4.UnitTests/Properties/AssemblyInfo.cs
NModbus4.UnitTests/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; using Xunit; [assembly: AssemblyTitle("Modbus.UnitTests")] [assembly: AssemblyProduct("NModbus")] [assembly: AssemblyCopyright("Licensed under MIT License.")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: Guid("244bb5c5-2aec-437a-b1c3-4b312ace54fc")] [assembly: AssemblyVersion("1.11.0.0")] [assembly: AssemblyFileVersion("1.11.0.0")]
using System; using System.Reflection; using System.Runtime.InteropServices; using Xunit; [assembly: AssemblyTitle("Modbus.UnitTests")] [assembly: AssemblyProduct("NModbus")] [assembly: AssemblyCopyright("Licensed under MIT License.")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: Guid("244bb5c5-2aec-437a-b1c3-4b312ace54fc")] [assembly: AssemblyVersion("1.11.0.0")] [assembly: AssemblyFileVersion("1.11.0.0")] [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)]
mit
C#
796127df2470cb8139660b371690a7423e9575d8
Fix SubModel name
overtools/OWLib,kerzyte/OWLib
OWLib/Types/STUD/Binding/SubModelRecord.cs
OWLib/Types/STUD/Binding/SubModelRecord.cs
using System.IO; using System.Runtime.InteropServices; namespace OWLib.Types.STUD.Binding { public class SubModelRecord : ISTUDInstance { public uint Id => 0xEC23FFFD; public string Name => "Binding:SubModel"; [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct SubModel { public STUDInstanceInfo instance; public OWRecord binding; public OWRecord unk; public long offset; public ulong unk1; public long offset2; public ulong unk2; } [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct SubModelEntry { public ulong zero1; public OWRecord binding; public OWRecord virt1; public OWRecord virt2; public ulong zero2; } private SubModel header; public SubModel Header => header; private SubModelEntry[] entries; public SubModelEntry[] Entries => entries; public void Read(Stream input) { using(BinaryReader reader = new BinaryReader(input, System.Text.Encoding.Default, true)) { header = reader.Read<SubModel>(); if(header.offset > 0) { input.Position = header.offset; STUDArrayInfo info = reader.Read<STUDArrayInfo>(); entries = new SubModelEntry[info.count]; input.Position = (long)info.offset; for(ulong i = 0; i < info.count; ++i) { entries[i] = reader.Read<SubModelEntry>(); } } else { entries = new SubModelEntry[0]; } } } } }
using System.IO; using System.Runtime.InteropServices; namespace OWLib.Types.STUD.Binding { public class SubModelRecord : ISTUDInstance { public uint Id => 0xEC23FFFD; public string Name => "Binding:ProjectileModel"; [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct SubModel { public STUDInstanceInfo instance; public OWRecord binding; public OWRecord unk; public long offset; public ulong unk1; public long offset2; public ulong unk2; } [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct SubModelEntry { public ulong zero1; public OWRecord binding; public OWRecord virt1; public OWRecord virt2; public ulong zero2; } private SubModel header; public SubModel Header => header; private SubModelEntry[] entries; public SubModelEntry[] Entries => entries; public void Read(Stream input) { using(BinaryReader reader = new BinaryReader(input, System.Text.Encoding.Default, true)) { header = reader.Read<SubModel>(); if(header.offset > 0) { input.Position = header.offset; STUDArrayInfo info = reader.Read<STUDArrayInfo>(); entries = new SubModelEntry[info.count]; input.Position = (long)info.offset; for(ulong i = 0; i < info.count; ++i) { entries[i] = reader.Read<SubModelEntry>(); } } else { entries = new SubModelEntry[0]; } } } } }
mit
C#
7430408e615e628ba6ed8b6c065ff5a19b49b6a6
Fix issue with injection;
KonH/UDBase
Scripts/Controllers/Scene/AsyncSceneLoader.cs
Scripts/Controllers/Scene/AsyncSceneLoader.cs
using System; using UnityEngine; using UnityEngine.SceneManagement; using UDBase.Controllers.EventSystem; namespace UDBase.Controllers.SceneSystem { /// <summary> /// Asynchronous scene loader /// </summary> public sealed class AsyncSceneLoader : IScene { /// <summary> /// Base settings for AsyncSceneLoader, when you need to custom loading scene /// </summary> public class BaseSettings { public virtual ISceneInfo LoadingSceneInfo { get; } } /// <summary> /// Settings. /// </summary> [Serializable] public class Settings : BaseSettings { /// <summary> /// Loading scene name /// </summary> [Tooltip("Loading scene name")] public string LoadingScene; public override ISceneInfo LoadingSceneInfo { get { return GetSceneInfoByName(LoadingScene); } } ISceneInfo GetSceneInfoByName(string sceneName) { if (!string.IsNullOrEmpty(sceneName)) { return new SceneName(sceneName); } return null; } } public ISceneInfo CurrentScene { get; private set; } readonly ISceneInfo _loadingScene; AsyncLoadHelper _helper; IEvent _events; public AsyncSceneLoader(IEvent events, Settings settings, AsyncLoadHelper helper) { _events = events; _loadingScene = settings.LoadingSceneInfo; _helper = helper; } public void LoadScene(ISceneInfo sceneInfo) { var sceneName = sceneInfo.Name; TryOpenLoadingScene(); _helper.LoadScene(sceneName, () => { CurrentScene = sceneInfo; _events.Fire(new Scene_Loaded(sceneInfo)); }); } public void LoadScene(string sceneName) { LoadScene(new SceneName(sceneName)); } public void LoadScene<T>(T type) { LoadScene(SceneInfo.Get(type)); } public void LoadScene<T>(T type, string param) { LoadScene(SceneInfo.Get(type, param)); } public void LoadScene<T>(T type, params string[] parameters) { LoadScene(SceneInfo.Get(type, parameters)); } public void ReloadScene() { if( CurrentScene == null ) { CurrentScene = new SceneName(SceneManager.GetActiveScene().name); } LoadScene(CurrentScene); } void TryOpenLoadingScene() { var sceneName = GetLoadingSceneName(); if( !string.IsNullOrEmpty(sceneName) ) { SceneManager.LoadScene(sceneName); } } string GetLoadingSceneName() { return (_loadingScene != null) ? _loadingScene.Name : ""; } } }
using System; using UnityEngine; using UnityEngine.SceneManagement; using UDBase.Controllers.EventSystem; namespace UDBase.Controllers.SceneSystem { /// <summary> /// Asynchronous scene loader /// </summary> public sealed class AsyncSceneLoader : IScene { /// <summary> /// Base settings for AsyncSceneLoader, when you need to custom loading scene /// </summary> public class BaseSettings { public virtual ISceneInfo LoadingSceneInfo { get; } } /// <summary> /// Settings. /// </summary> [Serializable] public class Settings : BaseSettings { /// <summary> /// Loading scene name /// </summary> [Tooltip("Loading scene name")] public string LoadingScene; public override ISceneInfo LoadingSceneInfo { get { return GetSceneInfoByName(LoadingScene); } } ISceneInfo GetSceneInfoByName(string sceneName) { if (!string.IsNullOrEmpty(sceneName)) { return new SceneName(sceneName); } return null; } } public ISceneInfo CurrentScene { get; private set; } readonly ISceneInfo _loadingScene; AsyncLoadHelper _helper; IEvent _events; public AsyncSceneLoader(IEvent events, BaseSettings settings, AsyncLoadHelper helper) { _events = events; _loadingScene = settings.LoadingSceneInfo; _helper = helper; } public void LoadScene(ISceneInfo sceneInfo) { var sceneName = sceneInfo.Name; TryOpenLoadingScene(); _helper.LoadScene(sceneName, () => { CurrentScene = sceneInfo; _events.Fire(new Scene_Loaded(sceneInfo)); }); } public void LoadScene(string sceneName) { LoadScene(new SceneName(sceneName)); } public void LoadScene<T>(T type) { LoadScene(SceneInfo.Get(type)); } public void LoadScene<T>(T type, string param) { LoadScene(SceneInfo.Get(type, param)); } public void LoadScene<T>(T type, params string[] parameters) { LoadScene(SceneInfo.Get(type, parameters)); } public void ReloadScene() { if( CurrentScene == null ) { CurrentScene = new SceneName(SceneManager.GetActiveScene().name); } LoadScene(CurrentScene); } void TryOpenLoadingScene() { var sceneName = GetLoadingSceneName(); if( !string.IsNullOrEmpty(sceneName) ) { SceneManager.LoadScene(sceneName); } } string GetLoadingSceneName() { return (_loadingScene != null) ? _loadingScene.Name : ""; } } }
mit
C#
db860fa7747a875c7cf7063be2ad9e7fbc8fff0a
remove activated instead of type in table header
AlexEndris/regtesting,hotelde/regtesting
RegTesting.Mvc/Views/Testcase/Index.cshtml
RegTesting.Mvc/Views/Testcase/Index.cshtml
@model IEnumerable<RegTesting.Mvc.Models.TestcaseModel> @{ ViewBag.Title = "Testfälle - RegTesting"; } <h2>Testcases</h2> <table class="table"> <tr> <th> Name </th> <th> Type </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Type) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Html.ActionLink("Delete", "Delete", new { id=item.ID }) </td> </tr> } </table> <br/> <div> @Html.ActionLink("Zurück", "Index","Settings") </div>
@model IEnumerable<RegTesting.Mvc.Models.TestcaseModel> @{ ViewBag.Title = "Testfälle - RegTesting"; } <h2>Testcases</h2> <table class="table"> <tr> <th> Name </th> <th> Activated </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Type) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Html.ActionLink("Delete", "Delete", new { id=item.ID }) </td> </tr> } </table> <br/> <div> @Html.ActionLink("Zurück", "Index","Settings") </div>
apache-2.0
C#
05bf81a7fbcda22b184814740ac811cf0f951176
Update Implement1904DateSystem.cs
aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Articles/Implement1904DateSystem.cs
Examples/CSharp/Articles/Implement1904DateSystem.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Articles { public class Implement1904DateSystem { public static void Main() { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize a new Workbook //Open an excel file Workbook workbook = new Workbook(dataDir+ "book1.xlsx"); //Implement 1904 date system workbook.Settings.Date1904 = true; //Save the excel file workbook.Save(dataDir+ "Mybook.out.xlsx"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Articles { public class Implement1904DateSystem { public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize a new Workbook //Open an excel file Workbook workbook = new Workbook(dataDir+ "book1.xlsx"); //Implement 1904 date system workbook.Settings.Date1904 = true; //Save the excel file workbook.Save(dataDir+ "Mybook.out.xlsx"); } } }
mit
C#
f7e6bebe8253df79afe082156fb654f364ca05c1
Create directory if non existent prior to uploading
mcartoixa/Common.FileTransfer,mcartoixa/Common.FileTransfer
FileTransfer/FileSystem/FileSystemTransferClient.cs
FileTransfer/FileSystem/FileSystemTransferClient.cs
using System; using System.IO; using System.Threading.Tasks; namespace Common.FileTransfer.FileSystem { //////////////////////////////////////////////////////////////////////////// /// /// <summary>A file system implementation of a file transfer client.</summary> /// //////////////////////////////////////////////////////////////////////////// public class FileSystemTransferClient: FileTransferClient { /// <summary>Creates a new instance of the <see cref="FileSystemTransferClient" /> class.</summary> /// <param name="baseAddress"></param> public FileSystemTransferClient(Uri baseAddress): base(baseAddress) { } /// <summary>Deletes the file referenced by the specified <paramref name="path" />.</summary> /// <param name="path">The URI to the file to be deleted.</param> protected override Task DoDeleteAsync(Uri path) { string localPath=path.LocalPath; var fi=new FileInfo(localPath); fi.Delete(); var tcs=new TaskCompletionSource<object>(); tcs.SetResult(null); return tcs.Task; } /// <summary>Downloads the file referenced by the specified <paramref name="path" />.</summary> /// <param name="path">The absolute URI to the file to be downloaded.</param> /// <returns>The file.</returns> protected override Task<ITransferableFile> DoDownloadAsync(Uri path) { string localPath=path.LocalPath; var fi=new FileInfo(localPath); var ret=new FileSystemTransferableFile(fi); return Task.FromResult(ret as ITransferableFile); } /// <summary>Uploads the specified file.</summary> /// <param name="file">The file to upload.</param> /// <returns>The URI that will be used to <see cref="FileTransferClient.DownloadAsync">download</see> the file.</returns> protected override async Task<Uri> DoUploadAsync(ITransferableFile file) { var path=Path.Combine(BaseAddress.LocalPath, file.Name); var dir=Path.GetDirectoryName(path); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); using (var dfs=File.Create(path, 1024, FileOptions.Asynchronous | FileOptions.WriteThrough)) using (var sfs=await file.GetContentAsync()) await sfs.CopyToAsync(dfs); return new Uri(path); } } }
using System; using System.IO; using System.Threading.Tasks; namespace Common.FileTransfer.FileSystem { //////////////////////////////////////////////////////////////////////////// /// /// <summary>A file system implementation of a file transfer client.</summary> /// //////////////////////////////////////////////////////////////////////////// public class FileSystemTransferClient: FileTransferClient { /// <summary>Creates a new instance of the <see cref="FileSystemTransferClient" /> class.</summary> /// <param name="baseAddress"></param> public FileSystemTransferClient(Uri baseAddress): base(baseAddress) { } /// <summary>Deletes the file referenced by the specified <paramref name="path" />.</summary> /// <param name="path">The URI to the file to be deleted.</param> protected override Task DoDeleteAsync(Uri path) { string localPath=path.LocalPath; var fi=new FileInfo(localPath); fi.Delete(); var tcs=new TaskCompletionSource<object>(); tcs.SetResult(null); return tcs.Task; } /// <summary>Downloads the file referenced by the specified <paramref name="path" />.</summary> /// <param name="path">The absolute URI to the file to be downloaded.</param> /// <returns>The file.</returns> protected override Task<ITransferableFile> DoDownloadAsync(Uri path) { string localPath=path.LocalPath; var fi=new FileInfo(localPath); var ret=new FileSystemTransferableFile(fi); return Task.FromResult(ret as ITransferableFile); } /// <summary>Uploads the specified file.</summary> /// <param name="file">The file to upload.</param> /// <returns>The URI that will be used to <see cref="FileTransferClient.DownloadAsync">download</see> the file.</returns> protected override async Task<Uri> DoUploadAsync(ITransferableFile file) { var path=Path.Combine(BaseAddress.LocalPath, file.Name); using (var dfs=File.Create(path, 1024, FileOptions.Asynchronous | FileOptions.WriteThrough)) using (var sfs=await file.GetContentAsync()) await sfs.CopyToAsync(dfs); return new Uri(path); } } }
mit
C#
0ba6cc9b053033567cd5e56eb999cabcf202e0fe
fix converter
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Converters/DurationLabelConverter.cs
TCC.Core/Converters/DurationLabelConverter.cs
using System; using System.Globalization; using System.Windows.Data; namespace TCC.Converters { public class DurationLabelConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var val = 0U; if (value != null) val = System.Convert.ToUInt32(value); var seconds = val / 1000; var minutes = seconds / 60; var hours = minutes / 60; var days = hours / 24; if (minutes < 3) return seconds.ToString(); if (hours < 3) return minutes + "m"; if (days < 1) return hours + "h"; return days + "d"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Globalization; using System.Windows.Data; namespace TCC.Converters { public class DurationLabelConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var val = 0; if (value != null) val = System.Convert.ToInt32(value); var seconds = val / 1000; var minutes = seconds / 60; var hours = minutes / 60; var days = hours / 24; if (minutes < 3) return seconds.ToString(); if (hours < 3) return minutes + "m"; if (days < 1) return hours + "h"; return days + "d"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
mit
C#
bf09b9c313365d0ad207bd178258863d0f6df0da
Update CaptchaNeededException.cs
vknet/vk,Soniclev/vk,vknet/vk
VkNet.UWP/Exception/CaptchaNeededException.cs
VkNet.UWP/Exception/CaptchaNeededException.cs
using System.Runtime.Serialization; using VkNet.Utils; namespace VkNet.Exception { using System; /// <summary> /// Исключение, выбрасываемое при необходимости ввода капчи для вызова метода /// Код ошибки - 14 /// </summary> [DataContract] public class CaptchaNeededException : VkApiMethodInvokeException { /// <summary> /// Идентификатор капчи /// </summary> public long Sid { get; private set; } /// <summary> /// Uri-адрес изображения с капчей /// </summary> public Uri Img { get; private set; } /// <summary> /// Создания экземпляра CaptchaNeededException /// </summary> /// <param name="sid">Сид</param> /// <param name="img">Uri-адрес изображения с капчей</param> public CaptchaNeededException(long sid, string img) : this(sid, string.IsNullOrEmpty(img) ? null : new Uri(img)) { } /// <summary> /// Создания экземпляра CaptchaNeededException /// </summary> /// <param name="sid">Сид</param> /// <param name="img">Uri-адрес изображения с капчей</param> public CaptchaNeededException(long sid, Uri img) { Sid = sid; Img = img; } /// <summary> /// Инициализирует новый экземпляр класса VkApiException /// </summary> /// <param name="response">Ответ от сервера vk</param> public CaptchaNeededException(VkResponse response) : base(response["error_msg"]) { ErrorCode = response["error_code"]; Sid = response["captcha_sid"]; Img = response["captcha_img"]; } } }
using System.Runtime.Serialization; using VkNet.Utils; namespace VkNet.Exception { using System; /// <summary> /// Исключение, выбрасываемое при необходимости ввода капчи для вызова метода /// Код ошибки - 14 /// </summary> [DataContract] public class CaptchaNeededException : VkApiException { /// <summary> /// Идентификатор капчи /// </summary> public long Sid { get; private set; } /// <summary> /// Uri-адрес изображения с капчей /// </summary> public Uri Img { get; private set; } /// <summary> /// Создания экземпляра CaptchaNeededException /// </summary> /// <param name="sid">Сид</param> /// <param name="img">Uri-адрес изображения с капчей</param> public CaptchaNeededException(long sid, string img) : this(sid, string.IsNullOrEmpty(img) ? null : new Uri(img)) { } /// <summary> /// Создания экземпляра CaptchaNeededException /// </summary> /// <param name="sid">Сид</param> /// <param name="img">Uri-адрес изображения с капчей</param> public CaptchaNeededException(long sid, Uri img) { Sid = sid; Img = img; } /// <summary> /// Инициализирует новый экземпляр класса VkApiException /// </summary> /// <param name="response">Ответ от сервера vk</param> public CaptchaNeededException(VkResponse response) : base(response["error_msg"]) { ErrorCode = response["error_code"]; Sid = response["captcha_sid"]; Img = response["captcha_img"]; } } }
mit
C#
17cf0c674a2e64c2a4763faebe07534caa5fadeb
修复启动与退出应用程序的逻辑问题。
Zongsoft/Zongsoft.Web.Launcher
Global.asax.cs
Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Zongsoft.Web.Launcher { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { Zongsoft.Plugins.Application.Started += Application_Started; Zongsoft.Plugins.Application.Start(Zongsoft.Web.Plugins.ApplicationContext.Current, null); } protected void Application_End(object sender, EventArgs e) { Zongsoft.Plugins.Application.Exit(); } private void Application_Started(object sender, Zongsoft.Plugins.ApplicationEventArgs e) { Application["ApplicationContext"] = Zongsoft.Plugins.Application.Context; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Zongsoft.Web.Launcher { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { Zongsoft.Plugins.Application.Start(Zongsoft.Web.Plugins.ApplicationContext.Current, null); } } }
mit
C#
66cc475d9f46f3479bb4f4ca6c556a0fea4d7063
Fix grass seed drop
flibitijibibo/TrueCraft,illblew/TrueCraft,illblew/TrueCraft,SirCmpwn/TrueCraft,illblew/TrueCraft,flibitijibibo/TrueCraft,SirCmpwn/TrueCraft,SirCmpwn/TrueCraft,flibitijibibo/TrueCraft
TrueCraft.Core/Logic/Blocks/TallGrassBlock.cs
TrueCraft.Core/Logic/Blocks/TallGrassBlock.cs
using System; using TrueCraft.API.Logic; using TrueCraft.Core.Logic.Items; using TrueCraft.API; namespace TrueCraft.Core.Logic.Blocks { public class TallGrassBlock : BlockProvider { public enum TallGrassType { DeadBush = 0, TallGrass = 1, Fern = 2 } public static readonly byte BlockID = 0x1F; public override byte ID { get { return 0x1F; } } public override double BlastResistance { get { return 0; } } public override double Hardness { get { return 0; } } public override byte Luminance { get { return 0; } } public override bool Opaque { get { return false; } } public override string DisplayName { get { return "Tall Grass"; } } public override SoundEffectClass SoundEffect { get { return SoundEffectClass.Grass; } } public override bool Flammable { get { return true; } } public override BoundingBox? BoundingBox { get { return null; } } public override BoundingBox? InteractiveBoundingBox { get { return new BoundingBox(new Vector3(4 / 16.0), Vector3.One); } } public override Coordinates3D GetSupportDirection(BlockDescriptor descriptor) { return Coordinates3D.Down; } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(7, 2); } protected override ItemStack[] GetDrop(BlockDescriptor descriptor, ItemStack item) { if (MathHelper.Random.Next (1, 24) == 1) { return new[] { new ItemStack (SeedsItem.ItemID, (sbyte)1) }; } else { return new[] { new ItemStack(-1) }; } } } }
using System; using TrueCraft.API.Logic; using TrueCraft.Core.Logic.Items; using TrueCraft.API; namespace TrueCraft.Core.Logic.Blocks { public class TallGrassBlock : BlockProvider { public enum TallGrassType { DeadBush = 0, TallGrass = 1, Fern = 2 } public static readonly byte BlockID = 0x1F; public override byte ID { get { return 0x1F; } } public override double BlastResistance { get { return 0; } } public override double Hardness { get { return 0; } } public override byte Luminance { get { return 0; } } public override bool Opaque { get { return false; } } public override string DisplayName { get { return "Tall Grass"; } } public override SoundEffectClass SoundEffect { get { return SoundEffectClass.Grass; } } public override bool Flammable { get { return true; } } public override BoundingBox? BoundingBox { get { return null; } } public override BoundingBox? InteractiveBoundingBox { get { return new BoundingBox(new Vector3(4 / 16.0), Vector3.One); } } public override Coordinates3D GetSupportDirection(BlockDescriptor descriptor) { return Coordinates3D.Down; } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(7, 2); } protected override ItemStack[] GetDrop(BlockDescriptor descriptor, ItemStack item) { return new[] { new ItemStack(SeedsItem.ItemID, (sbyte)MathHelper.Random.Next(2)) }; } } }
mit
C#
b6f56c221a3f6ecf910e2dc0278b9491c5585ab4
use safer remove method
aloisdeniel/Mvvmicro
Sources/Mvvmicro/Dependencies/Container.cs
Sources/Mvvmicro/Dependencies/Container.cs
namespace Mvvmicro { using System; using System.Collections.Generic; public class Container : IContainer { #region Default private static Lazy<IContainer> instance = new Lazy<IContainer>(() => new Container()); /// <summary> /// Gets the default container. /// </summary> /// <value>The default.</value> public static IContainer Default => instance.Value; #endregion #region Fields private Dictionary<Type, object> instances = new Dictionary<Type, object>(); private Dictionary<Type, Tuple<bool, Func<object>>> factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); #endregion #region Methods public T Get<T>() { var factory = this.factories[typeof(T)]; if (factory.Item1) { if (instances.TryGetValue(typeof(T), out object instance)) { return (T)instance; } var newInstance = factory.Item2(); instances[typeof(T)] = newInstance; return (T)newInstance; } return (T)factory.Item2(); } public void Register<T>(Func<IContainer, T> factory, bool isInstance = false) { this.factories[typeof(T)] = new Tuple<bool, Func<object>>(isInstance, () => factory(this)); } public bool IsRegistered<T>() => factories.ContainsKey(typeof(T)); public void Unregister<T>() { if (this.IsRegistered<T>()) { instances.Remove(typeof(T)); factories.Remove(typeof(T)); } } public void WipeContainer() { this.instances = new Dictionary<Type, object>(); this.factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); } public T New<T>() => (T)this.factories[typeof(T)].Item2(); #endregion } }
namespace Mvvmicro { using System; using System.Collections.Generic; public class Container : IContainer { #region Default private static Lazy<IContainer> instance = new Lazy<IContainer>(() => new Container()); /// <summary> /// Gets the default container. /// </summary> /// <value>The default.</value> public static IContainer Default => instance.Value; #endregion #region Fields private Dictionary<Type, object> instances = new Dictionary<Type, object>(); private Dictionary<Type, Tuple<bool, Func<object>>> factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); #endregion #region Methods public T Get<T>() { var factory = this.factories[typeof(T)]; if (factory.Item1) { if (instances.TryGetValue(typeof(T), out object instance)) { return (T)instance; } var newInstance = factory.Item2(); instances[typeof(T)] = newInstance; return (T)newInstance; } return (T)factory.Item2(); } public void Register<T>(Func<IContainer, T> factory, bool isInstance = false) { this.factories[typeof(T)] = new Tuple<bool, Func<object>>(isInstance, () => factory(this)); } public bool IsRegistered<T>() => factories.ContainsKey(typeof(T)); public void Unregister<T>() { if (this.IsRegistered<T>()) { instances[typeof(T)] = null; factories[typeof(T)] = null; } } public void WipeContainer() { this.instances = new Dictionary<Type, object>(); this.factories = new Dictionary<Type, Tuple<bool, Func<object>>>(); } public T New<T>() => (T)this.factories[typeof(T)].Item2(); #endregion } }
mit
C#
9f2d813f44af584c5dba5a7ebe9ced152aa9d3b2
Add current site mock to WorkContextMock
Proligence/OrchardTesting
Proligence.Orchard.Testing/Mocks/WorkContextMock.cs
Proligence.Orchard.Testing/Mocks/WorkContextMock.cs
namespace Proligence.Orchard.Testing.Mocks { using System; using System.Collections.Generic; using Moq; using global::Orchard; using global::Orchard.Security; using global::Orchard.Settings; public class WorkContextMock : WorkContext { private readonly Dictionary<string, object> _state = new Dictionary<string, object>(); public WorkContextMock() { CurrentSiteMock = new Mock<ISite>(); CurrentSite = CurrentSiteMock.Object; CurrentUserMock = new Mock<IUser>(); CurrentUser = CurrentUserMock.Object; CurrentTimeZone = TimeZoneInfo.Utc; } public WorkContextMock(MockBehavior mockBehavior) { CurrentUserMock = new Mock<IUser>(mockBehavior); CurrentUser = CurrentUserMock.Object; CurrentSiteMock = new Mock<ISite>(mockBehavior); CurrentSite = CurrentSiteMock.Object; } public Mock<ISite> CurrentSiteMock { get; private set; } public Mock<IUser> CurrentUserMock { get; private set; } public Func<Type, object> ResolveFunc { get; set; } public override T Resolve<T>() { if (ResolveFunc != null) { return (T)ResolveFunc(typeof(T)); } return default(T); } public override bool TryResolve<T>(out T service) { service = default(T); if (ResolveFunc != null) { service = (T)ResolveFunc(typeof(T)); return (service != null); } return false; } public override T GetState<T>(string name) { if (!_state.ContainsKey(name)) { return default(T); } return (T)_state[name]; } public override void SetState<T>(string name, T value) { _state[name] = value; } } }
namespace Proligence.Orchard.Testing.Mocks { using System; using System.Collections.Generic; using Moq; using global::Orchard; using global::Orchard.Security; public class WorkContextMock : WorkContext { private readonly Dictionary<string, object> _state = new Dictionary<string, object>(); public WorkContextMock() { CurrentUserMock = new Mock<IUser>(); CurrentUser = CurrentUserMock.Object; CurrentTimeZone = TimeZoneInfo.Utc; } public WorkContextMock(MockBehavior mockBehavior) { CurrentUserMock = new Mock<IUser>(mockBehavior); CurrentUser = CurrentUserMock.Object; } public Mock<IUser> CurrentUserMock { get; private set; } public Func<Type, object> ResolveFunc { get; set; } public override T Resolve<T>() { if (ResolveFunc != null) { return (T)ResolveFunc(typeof(T)); } return default(T); } public override bool TryResolve<T>(out T service) { service = default(T); if (ResolveFunc != null) { service = (T)ResolveFunc(typeof(T)); return (service != null); } return false; } public override T GetState<T>(string name) { if (!_state.ContainsKey(name)) { return default(T); } return (T)_state[name]; } public override void SetState<T>(string name, T value) { _state[name] = value; } } }
mit
C#
43ada1ee3df06549bd0f649796a75e3d890d77fc
Increment minor -> 0.4.0
awseward/restivus
AssemblyInfo.sln.cs
AssemblyInfo.sln.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyFileVersion("0.4.0.0")] [assembly: AssemblyInformationalVersion("0.4.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.3.0.0")] [assembly: AssemblyFileVersion("0.3.0.0")] [assembly: AssemblyInformationalVersion("0.3.0")]
mit
C#
8e8fcdac7d6a9eff62e3f87d285a99c6c93731f4
Update Stripe test API key from their docs
nberardi/stripe-dotnet
test/Stripe.Tests/Constants.cs
test/Stripe.Tests/Constants.cs
using System; using System.Linq; namespace Stripe.Tests { static class Constants { public const string ApiKey = @"sk_test_BQokikJOvBiI2HlWgH4olfQ2"; } }
using System; using System.Linq; namespace Stripe.Tests { static class Constants { public const string ApiKey = @"8GSx9IL9MA0iJ3zcitnGCHonrXWiuhMf"; } }
mit
C#
32410239ca4b4b7097c7ff733e2ec188319f3c83
Fix hardcoded catalog
peopleware/net-ppwcode-vernacular-nhibernate
src/II.SqlServer/Implementations/DbConstraint/PpwSqlServerDbConstraints.cs
src/II.SqlServer/Implementations/DbConstraint/PpwSqlServerDbConstraints.cs
// Copyright 2018 by PeopleWare n.v.. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using PPWCode.Vernacular.NHibernate.II.Implementations.DbConstraint; namespace PPWCode.Vernacular.NHibernate.II.SqlServer.Implementations.DbConstraint { /// <inheritdoc cref="InformationSchemaBasedDbConstraints" /> public class PpwSqlServerDbConstraints : InformationSchemaBasedDbConstraints { /// <inheritdoc /> protected override IEnumerable<string> Schemas { get { yield return "dbo"; } } /// <inheritdoc /> protected override DbProviderFactory DbProviderFactory => SqlClientFactory.Instance; /// <inheritdoc /> protected override string SqlCommand => @" select tc.CONSTRAINT_NAME, tc.TABLE_NAME, tc.TABLE_SCHEMA, tc.CONSTRAINT_TYPE from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc where tc.CONSTRAINT_CATALOG = @catalog and tc.CONSTRAINT_SCHEMA in ('dbo') union all select i.[name] as CONSTRAINT_NAME, o.[name] as TABLE_NAME, schema_name(o.schema_id) as TABLE_SCHEMA, 'UNIQUE' as CONSTRAINT_TYPE from sys.indexes i join sys.objects o on i.object_id = o.object_id where i.is_unique = 1 and i.is_unique_constraint = 0 and i.is_primary_key = 0 and o.type = 'U'"; } }
// Copyright 2018 by PeopleWare n.v.. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using PPWCode.Vernacular.NHibernate.II.Implementations.DbConstraint; namespace PPWCode.Vernacular.NHibernate.II.SqlServer.Implementations.DbConstraint { /// <inheritdoc cref="InformationSchemaBasedDbConstraints" /> public class PpwSqlServerDbConstraints : InformationSchemaBasedDbConstraints { /// <inheritdoc /> protected override IEnumerable<string> Schemas { get { yield return "dbo"; } } /// <inheritdoc /> protected override DbProviderFactory DbProviderFactory => SqlClientFactory.Instance; /// <inheritdoc /> protected override string SqlCommand => @" select tc.CONSTRAINT_NAME, tc.TABLE_NAME, tc.TABLE_SCHEMA, tc.CONSTRAINT_TYPE from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc where tc.CONSTRAINT_CATALOG = 'Phoenix' and tc.CONSTRAINT_SCHEMA in ('dbo') union all select i.[name] as CONSTRAINT_NAME, o.[name] as TABLE_NAME, schema_name(o.schema_id) as TABLE_SCHEMA, 'UNIQUE' as CONSTRAINT_TYPE from sys.indexes i join sys.objects o on i.object_id = o.object_id where i.is_unique = 1 and i.is_unique_constraint = 0 and i.is_primary_key = 0 and o.type = 'U'"; } }
apache-2.0
C#
5981a14209f69e0ecfc6cff4e58aa967ec9b09a3
add work listing of candidates with checkboxes
KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem
VotingSystem.Web/Areas/User/Views/Votes/Vote.cshtml
VotingSystem.Web/Areas/User/Views/Votes/Vote.cshtml
@model VotingSystem.Web.Areas.User.ViewModels.VoteWithCandidatesInputModel @{ ViewBag.Title = "Vote"; } <h1>@Model.Title</h1> @using (Html.BeginForm("Vote", "Votes", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(x => x.Id) @Html.EditorFor(c => c.Candidates) <input type="submit" value="submit"/> }
@model List<VotingSystem.Web.Areas.User.ViewModels.CandidateViewModel> @{ ViewBag.Title = "Vote"; } @using (Html.BeginForm("Vote", "Votes", FormMethod.Post)) { @Html.AntiForgeryToken() foreach (var candidate in Model) { <input type="checkbox" name="cancicates" value="@candidate.Id" id="@candidate.Id"/> <label for="@candidate.Id"> <div class="well"> <div class="row"> <div class="col-md-4"> <h2>@candidate.Name</h2> </div> <div class="col-md-8"> <p>@candidate.Description</p> </div> </div> </div> </label> } <input type="submit" value="submit"/> }
mit
C#
3dc6833e28848a822569408c1dd3d748a2e49f82
Move to constructor - start listening as early as possible
larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl
MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs
MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class HomePrinterPage : WizardPage { public HomePrinterPage(ISetupWizard setupWizard, string instructionsText) : base(setupWizard, "Homing the printer".Localize(), instructionsText) { // Register listeners printer.Connection.DetailedPrintingStateChanged += Connection_DetailedPrintingStateChanged; } public override void OnClosed(EventArgs e) { // Unregister listeners printer.Connection.DetailedPrintingStateChanged -= Connection_DetailedPrintingStateChanged; base.OnClosed(e); } public override void OnLoad(EventArgs args) { printer.Connection.HomeAxis(PrinterConnection.Axis.XYZ); if(!printer.Settings.GetValue<bool>(SettingsKey.z_homes_to_max)) { // move so we don't heat the printer while the nozzle is touching the bed printer.Connection.MoveAbsolute(PrinterConnection.Axis.Z, 10, printer.Settings.Helpers.ManualMovementSpeeds().Z); } NextButton.Enabled = false; base.OnLoad(args); } private void Connection_DetailedPrintingStateChanged(object sender, EventArgs e) { if (printer.Connection.DetailedPrintingState != DetailedPrintingState.HomingAxis) { NextButton.Enabled = true; UiThread.RunOnIdle(() => NextButton.InvokeClick()); } } } }
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class HomePrinterPage : WizardPage { public HomePrinterPage(ISetupWizard setupWizard, string instructionsText) : base(setupWizard, "Homing the printer".Localize(), instructionsText) { } public override void OnClosed(EventArgs e) { // Unregister listeners printer.Connection.DetailedPrintingStateChanged -= Connection_DetailedPrintingStateChanged; base.OnClosed(e); } public override void OnLoad(EventArgs args) { printer.Connection.DetailedPrintingStateChanged += Connection_DetailedPrintingStateChanged; printer.Connection.HomeAxis(PrinterConnection.Axis.XYZ); if(!printer.Settings.GetValue<bool>(SettingsKey.z_homes_to_max)) { // move so we don't heat the printer while the nozzle is touching the bed printer.Connection.MoveAbsolute(PrinterConnection.Axis.Z, 10, printer.Settings.Helpers.ManualMovementSpeeds().Z); } NextButton.Enabled = false; base.OnLoad(args); } private void Connection_DetailedPrintingStateChanged(object sender, EventArgs e) { if (printer.Connection.DetailedPrintingState != DetailedPrintingState.HomingAxis) { NextButton.Enabled = true; UiThread.RunOnIdle(() => NextButton.InvokeClick()); } } } }
bsd-2-clause
C#
149dfcc9bc222e77ba3fc65c73fbf15d2e63618f
Migrate from ASP.NET Core 2.0 to 2.1
JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK
Samples/Senparc.Weixin.MP.Sample.vs2017/Senparc.Weixin.MP.CoreSample/Program.cs
Samples/Senparc.Weixin.MP.Sample.vs2017/Senparc.Weixin.MP.CoreSample/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Senparc.Weixin.MP.CoreSample { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Senparc.Weixin.MP.CoreSample { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
apache-2.0
C#
30baf726cd753508187a0c869da7a4a91e250a63
Add project description
xt0rted/Nancy.Validation.DataAnnotations.Extensions
src/Nancy.Validation.DataAnnotations.Extensions/Properties/AssemblyInfo.cs
src/Nancy.Validation.DataAnnotations.Extensions/Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Nancy.Validation.DataAnnotations.Extensions")] [assembly: AssemblyDescription(".NET 4.5 Data Annotation support for Nancy")]
using System.Reflection; [assembly: AssemblyTitle("Nancy.Validation.DataAnnotations.Extensions")] [assembly: AssemblyDescription("")]
mit
C#
409691d7809d966304263845fb94ef77a95c0552
Add new OSX versions to MacSystemInformation
hwthomas/xwt,residuum/xwt,lytico/xwt,hamekoz/xwt,antmicro/xwt,mono/xwt,cra0zy/xwt,TheBrainTech/xwt,akrisiun/xwt
Xwt.XamMac/Xwt.Mac/MacSystemInformation.cs
Xwt.XamMac/Xwt.Mac/MacSystemInformation.cs
// // MacSystemInformation.cs // // Author: // Alan McGovern <alan@xamarin.com> // // Copyright (c) 2011, Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Text; namespace Xwt.Mac { class MacSystemInformation { public static readonly Version Sierra = new Version (10, 12); public static readonly Version ElCapitan = new Version (10, 11); public static readonly Version Yosemite = new Version (10, 10); public static readonly Version Mavericks = new Version (10, 9); public static readonly Version MountainLion = new Version (10, 8); public static readonly Version Lion = new Version (10, 7); public static readonly Version SnowLeopard = new Version (10, 6); static Version version; [System.Runtime.InteropServices.DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] static extern int Gestalt (int selector, out int result); //TODO: there are other gestalt selectors that return info we might want to display //mac API for obtaining info about the system static int Gestalt (string selector) { System.Diagnostics.Debug.Assert (selector != null && selector.Length == 4); int cc = selector[3] | (selector[2] << 8) | (selector[1] << 16) | (selector[0] << 24); int result; int ret = Gestalt (cc, out result); if (ret != 0) throw new Exception (string.Format ("Error reading gestalt for selector '{0}': {1}", selector, ret)); return result; } static MacSystemInformation () { version = new Version (Gestalt ("sys1"), Gestalt ("sys2"), Gestalt ("sys3")); } public static Version OsVersion { get { return version; } } } }
// // MacSystemInformation.cs // // Author: // Alan McGovern <alan@xamarin.com> // // Copyright (c) 2011, Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Text; namespace Xwt.Mac { class MacSystemInformation { public static readonly Version MountainLion = new Version (10, 8); public static readonly Version Lion = new Version (10, 7); public static readonly Version SnowLeopard = new Version (10, 6); static Version version; [System.Runtime.InteropServices.DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] static extern int Gestalt (int selector, out int result); //TODO: there are other gestalt selectors that return info we might want to display //mac API for obtaining info about the system static int Gestalt (string selector) { System.Diagnostics.Debug.Assert (selector != null && selector.Length == 4); int cc = selector[3] | (selector[2] << 8) | (selector[1] << 16) | (selector[0] << 24); int result; int ret = Gestalt (cc, out result); if (ret != 0) throw new Exception (string.Format ("Error reading gestalt for selector '{0}': {1}", selector, ret)); return result; } static MacSystemInformation () { version = new Version (Gestalt ("sys1"), Gestalt ("sys2"), Gestalt ("sys3")); } public static Version OsVersion { get { return version; } } } }
mit
C#
848d9215e9e6969980720062f3d38ec15c942c25
Simplify string interpolation.
PenguinF/sandra-three
Eutherion/Win/Storage/OpaqueColorType.cs
Eutherion/Win/Storage/OpaqueColorType.cs
#region License /********************************************************************************* * OpaqueColorType.cs * * Copyright (c) 2004-2021 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using Eutherion.Text; using System; using System.Drawing; using System.Globalization; namespace Eutherion.Win.Storage { /// <summary> /// Type that accepts strings in the HTML color format "#xxxxxx" where all x'es are hexadecimal characters, /// and converts those values to and from opaque colors. /// </summary> public sealed class OpaqueColorType : PType.Derived<string, Color> { public static readonly PTypeErrorBuilder OpaqueColorTypeError = new PTypeErrorBuilder(new StringKey<ForFormattedText>(nameof(OpaqueColorTypeError))); public static readonly OpaqueColorType Instance = new OpaqueColorType(); private OpaqueColorType() : base(PType.CLR.String) { } public override Union<ITypeErrorBuilder, Color> TryGetTargetValue(string value) { if (value != null && value.Length == 7 && value[0] == '#') { string hexString = value.Substring(1); if (int.TryParse(hexString, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out int rgb)) { return Color.FromArgb(255, Color.FromArgb(rgb)); } } return InvalidValue(OpaqueColorTypeError); } public override string GetBaseValue(Color value) => $"#{value.R:X2}{value.G:X2}{value.B:X2}"; } }
#region License /********************************************************************************* * OpaqueColorType.cs * * Copyright (c) 2004-2021 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using Eutherion.Text; using System; using System.Drawing; using System.Globalization; namespace Eutherion.Win.Storage { /// <summary> /// Type that accepts strings in the HTML color format "#xxxxxx" where all x'es are hexadecimal characters, /// and converts those values to and from opaque colors. /// </summary> public sealed class OpaqueColorType : PType.Derived<string, Color> { public static readonly PTypeErrorBuilder OpaqueColorTypeError = new PTypeErrorBuilder(new StringKey<ForFormattedText>(nameof(OpaqueColorTypeError))); public static readonly OpaqueColorType Instance = new OpaqueColorType(); private OpaqueColorType() : base(PType.CLR.String) { } public override Union<ITypeErrorBuilder, Color> TryGetTargetValue(string value) { if (value != null && value.Length == 7 && value[0] == '#') { string hexString = value.Substring(1); if (int.TryParse(hexString, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out int rgb)) { return Color.FromArgb(255, Color.FromArgb(rgb)); } } return InvalidValue(OpaqueColorTypeError); } public override string GetBaseValue(Color value) => $"#{value.R.ToString("X2")}{value.G.ToString("X2")}{value.B.ToString("X2")}"; } }
apache-2.0
C#
7a3513c36ff14597fffc808c212d7448fde1926f
Fix model.
robinsedlaczek/ModelR
WaveDev.ModelR.Shared/Models/UserInfoModel.cs
WaveDev.ModelR.Shared/Models/UserInfoModel.cs
using Newtonsoft.Json; namespace WaveDev.ModelR.Shared.Models { public class UserInfoModel { public UserInfoModel(string userName, string connectionId, byte[] image) { UserName = userName; ConnectionId = connectionId; Image = image; } [JsonIgnore] public string ConnectionId { get; private set; } public string UserName { get; private set; } public byte[] Image { get; private set; } } }
namespace WaveDev.ModelR.Shared.Models { public class UserInfoModel { public UserInfoModel(string userName, byte[] image) { UserName = userName; Image = image; } public string UserName { get; private set; } public byte[] Image { get; private set; } } }
mit
C#
127d738d2fed7acd792197c905edb4dc7689352a
Update AssemblyInfo.cs
lust4life/WebApiProxy,faniereynders/WebApiProxy
WebApiProxy.Server/Properties/AssemblyInfo.cs
WebApiProxy.Server/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebApi Proxy Provider")] [assembly: AssemblyDescription("Provides an endpoint for ASP.NET Web Api services to serve a JavaScript proxy and metadata")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("WebApiProxy")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bc78cf80-1cf9-46e7-abdd-88e9c49d656c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyInformationalVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebApi Proxy Provider")] [assembly: AssemblyDescription("Provides an endpoint for ASP.NET Web Api services to serve a JavaScript proxy and metadata")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("WebApiProxy")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bc78cf80-1cf9-46e7-abdd-88e9c49d656c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyInformationalVersion("1.*")] [assembly: AssemblyVersion("1.*")]
mit
C#
4b701e8eb3fdc214bea8963e64d48fd8f4e79c23
Fix namespace
martijn00/XamarinItemTouchHelper
XamarinItemTouchHelper/TouchListenerHelper.cs
XamarinItemTouchHelper/TouchListenerHelper.cs
using System; using Android.Views; using Android.Support.V4.View; using Android.Support.V7.Widget; namespace XamarinItemTouchHelper { public class TouchListenerHelper : Java.Lang.Object, View.IOnTouchListener { private RecyclerView.ViewHolder _itemHolder; private IOnStartDragListener _mDragStartListener; public TouchListenerHelper(RecyclerView.ViewHolder holder, IOnStartDragListener mDragStartListener) { _itemHolder = holder; _mDragStartListener = mDragStartListener; } public bool OnTouch (View v, MotionEvent e) { if (e.Action == MotionEventActions.Down) { _mDragStartListener.OnStartDrag(_itemHolder); } return false; } } }
using System; using Android.Views; using Android.Support.V4.View; using Android.Support.V7.Widget; namespace XamarinItemTouchHelper.Sample { public class TouchListenerHelper : Java.Lang.Object, View.IOnTouchListener { private RecyclerView.ViewHolder _itemHolder; private IOnStartDragListener _mDragStartListener; public TouchListenerHelper(RecyclerView.ViewHolder holder, IOnStartDragListener mDragStartListener) { _itemHolder = holder; _mDragStartListener = mDragStartListener; } public bool OnTouch (View v, MotionEvent e) { if (e.Action == MotionEventActions.Down) { _mDragStartListener.OnStartDrag(_itemHolder); } return false; } } }
mit
C#
03f7cb388592dd4449d8dc67736e2381519c6451
Add {FullName} placeholder to paste templates
Gl0/CasualMeter
CasualMeter.Common/Formatters/PlayerStatsFormatter.cs
CasualMeter.Common/Formatters/PlayerStatsFormatter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CasualMeter.Common.Helpers; using Tera.DamageMeter; namespace CasualMeter.Common.Formatters { public class PlayerStatsFormatter : Formatter { public PlayerStatsFormatter(PlayerInfo playerInfo, FormatHelpers formatHelpers) { var placeHolders = new List<KeyValuePair<string, object>>(); placeHolders.Add(new KeyValuePair<string, object>("Name", playerInfo.Name)); placeHolders.Add(new KeyValuePair<string, object>("FullName", playerInfo.FullName)); placeHolders.Add(new KeyValuePair<string, object>("Class", playerInfo.Class)); placeHolders.Add(new KeyValuePair<string, object>("Crits", playerInfo.Dealt.Crits)); placeHolders.Add(new KeyValuePair<string, object>("Hits", playerInfo.Dealt.Hits)); placeHolders.Add(new KeyValuePair<string, object>("DamagePercent", formatHelpers.FormatPercent(playerInfo.Dealt.DamageFraction) ?? "NaN")); placeHolders.Add(new KeyValuePair<string, object>("CritPercent", formatHelpers.FormatPercent((double)playerInfo.Dealt.Crits / playerInfo.Dealt.Hits) ?? "NaN")); placeHolders.Add(new KeyValuePair<string, object>("Damage", formatHelpers.FormatValue(playerInfo.Dealt.Damage))); placeHolders.Add(new KeyValuePair<string, object>("DamageReceived", formatHelpers.FormatValue(playerInfo.Received.Damage))); placeHolders.Add(new KeyValuePair<string, object>("DPS", $"{formatHelpers.FormatValue(SettingsHelper.Instance.Settings.ShowPersonalDps ? playerInfo.Dealt.PersonalDps : playerInfo.Dealt.Dps)}/s")); Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value); FormatProvider = formatHelpers.CultureInfo; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CasualMeter.Common.Helpers; using Tera.DamageMeter; namespace CasualMeter.Common.Formatters { public class PlayerStatsFormatter : Formatter { public PlayerStatsFormatter(PlayerInfo playerInfo, FormatHelpers formatHelpers) { var placeHolders = new List<KeyValuePair<string, object>>(); placeHolders.Add(new KeyValuePair<string, object>("Name", playerInfo.Name)); placeHolders.Add(new KeyValuePair<string, object>("Class", playerInfo.Class)); placeHolders.Add(new KeyValuePair<string, object>("Crits", playerInfo.Dealt.Crits)); placeHolders.Add(new KeyValuePair<string, object>("Hits", playerInfo.Dealt.Hits)); placeHolders.Add(new KeyValuePair<string, object>("DamagePercent", formatHelpers.FormatPercent(playerInfo.Dealt.DamageFraction) ?? "NaN")); placeHolders.Add(new KeyValuePair<string, object>("CritPercent", formatHelpers.FormatPercent((double)playerInfo.Dealt.Crits / playerInfo.Dealt.Hits) ?? "NaN")); placeHolders.Add(new KeyValuePair<string, object>("Damage", formatHelpers.FormatValue(playerInfo.Dealt.Damage))); placeHolders.Add(new KeyValuePair<string, object>("DamageReceived", formatHelpers.FormatValue(playerInfo.Received.Damage))); placeHolders.Add(new KeyValuePair<string, object>("DPS", $"{formatHelpers.FormatValue(SettingsHelper.Instance.Settings.ShowPersonalDps ? playerInfo.Dealt.PersonalDps : playerInfo.Dealt.Dps)}/s")); Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value); FormatProvider = formatHelpers.CultureInfo; } } }
mit
C#
ed73c0d67c087c037d4c44d7731981694b283365
Remove laziness from edges' GetHashCode method
MSayfullin/Basics
Basics.Structures/Graphs/Edge.cs
Basics.Structures/Graphs/Edge.cs
using System; using System.Collections.Generic; using System.Diagnostics; namespace Basics.Structures.Graphs { [DebuggerDisplay("{Source}->{Target}")] public class Edge<T> : IEquatable<Edge<T>> where T : IEquatable<T> { public Edge(T source, T target) { Source = source; Target = target; } public T Source { get; private set; } public T Target { get; private set; } public bool IsSelfLooped { get { return Source.Equals(Target); } } public static bool operator ==(Edge<T> a, Edge<T> b) { return a.Equals(b); } public static bool operator !=(Edge<T> a, Edge<T> b) { return !a.Equals(b); } public bool Equals(Edge<T> other) { return !Object.ReferenceEquals(other, null) && this.Source.Equals(other.Source) && this.Target.Equals(other.Target); } public override bool Equals(object obj) { return Equals(obj as Edge<T>); } public override int GetHashCode() { var sourceHashCode = Source.GetHashCode(); return ((sourceHashCode << 5) + sourceHashCode) ^ Target.GetHashCode(); } public override string ToString() { return Source + "->" + Target; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Basics.Structures.Graphs { [DebuggerDisplay("{Source}->{Target}")] public class Edge<T> : IEquatable<Edge<T>> where T : IEquatable<T> { private readonly Lazy<int> _hashCode; public Edge(T source, T target) { Source = source; Target = target; _hashCode = new Lazy<int>(() => { var sourceHashCode = Source.GetHashCode(); return ((sourceHashCode << 5) + sourceHashCode) ^ Target.GetHashCode(); }); } public T Source { get; private set; } public T Target { get; private set; } public bool IsSelfLooped { get { return Source.Equals(Target); } } public static bool operator ==(Edge<T> a, Edge<T> b) { return a.Equals(b); } public static bool operator !=(Edge<T> a, Edge<T> b) { return !a.Equals(b); } public bool Equals(Edge<T> other) { return !Object.ReferenceEquals(other, null) && this.Source.Equals(other.Source) && this.Target.Equals(other.Target); } public override bool Equals(object obj) { return Equals(obj as Edge<T>); } public override int GetHashCode() { return _hashCode.Value; } public override string ToString() { return Source + "->" + Target; } } }
mit
C#
b34e1c619893186e850cb4d603821e04b42c703b
remove unused variable
the-gigi/XamarinPlayground
iOS/ViewController.cs
iOS/ViewController.cs
using System; using UIKit; namespace XamarinPlayground.iOS { public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. Button.AccessibilityIdentifier = "myButton"; Button.TouchUpInside += async delegate { Button.SetTitle ("Fetching...", UIControlState.Normal); var featureFetcher = new FeatureFetcher(); await featureFetcher.Fetch(); TitleField.Text = featureFetcher.Title; UrlField.Text = featureFetcher.Url; Button.SetTitle("Fetch #1 HackerNews Article", UIControlState.Normal); }; } } }
using System; using UIKit; namespace XamarinPlayground.iOS { public partial class ViewController : UIViewController { int count = 1; public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. Button.AccessibilityIdentifier = "myButton"; Button.TouchUpInside += async delegate { Button.SetTitle ("Fetching...", UIControlState.Normal); var featureFetcher = new FeatureFetcher(); await featureFetcher.Fetch(); TitleField.Text = featureFetcher.Title; UrlField.Text = featureFetcher.Url; Button.SetTitle("Fetch #1 HackerNews Article", UIControlState.Normal); }; } } }
mit
C#
71100ca062cac128390ffa1eb35952477a59e8f0
Add simple method to read back in a Post from disk
VenusInterns/BlogTemplate,VenusInterns/BlogTemplate,VenusInterns/BlogTemplate
BlogTemplate/Models/BlogDataStore.cs
BlogTemplate/Models/BlogDataStore.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace BlogTemplate.Models { public class BlogDataStore { const string StorageFolder = "BlogFiles"; public void SavePost(Post post) { Directory.CreateDirectory(StorageFolder); string outputFilePath = $"{StorageFolder}\\{post.Slug}.xml"; XmlDocument doc = new XmlDocument(); XmlElement rootNode = doc.CreateElement("Post"); doc.AppendChild(rootNode); rootNode.AppendChild(doc.CreateElement("Slug")).InnerText = post.Slug; rootNode.AppendChild(doc.CreateElement("Title")).InnerText = post.Title; rootNode.AppendChild(doc.CreateElement("Body")).InnerText = post.Body; doc.Save(outputFilePath); } public Post GetPost(string slug) { string expectedFilePath = $"{StorageFolder}\\{slug}.xml"; if(File.Exists(expectedFilePath)) { string fileContent = File.ReadAllText(expectedFilePath); XmlDocument doc = new XmlDocument(); doc.LoadXml(fileContent); Post post = new Post(); post.Slug = doc.GetElementsByTagName("Slug").Item(0).InnerText; post.Title = doc.GetElementsByTagName("Title").Item(0).InnerText; post.Body = doc.GetElementsByTagName("Body").Item(0).InnerText; return post; } return null; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace BlogTemplate.Models { public class BlogDataStore { const string StorageFolder = "BlogFiles"; public void SavePost(Post post) { Directory.CreateDirectory(StorageFolder); string outputFilePath = $"{StorageFolder}\\{post.Slug}.xml"; XmlDocument doc = new XmlDocument(); XmlElement rootNode = doc.CreateElement("Post"); doc.AppendChild(rootNode); rootNode.AppendChild(doc.CreateElement("Slug")).InnerText = post.Slug; rootNode.AppendChild(doc.CreateElement("Title")).InnerText = post.Title; rootNode.AppendChild(doc.CreateElement("Body")).InnerText = post.Body; doc.Save(outputFilePath); } } }
mit
C#
36b88871e44eef713e5ca2bf03aa393e4872a6e6
Update MetXGeneratorsExeTests_FromScratch.cs
willrawls/xlg,willrawls/xlg
MetX/MetX.Tests/Standard/Generation/CSharp/Project/MetXGeneratorsExeTests_FromScratch.cs
MetX/MetX.Tests/Standard/Generation/CSharp/Project/MetXGeneratorsExeTests_FromScratch.cs
using System; using System.IO; using MetX.Aspects; using MetX.Standard.Generation.CSharp.Project; using MetX.Standard.Generators; using MetX.Standard.Generators.GenGen; using MetX.Standard.Library; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MetX.Tests.Standard.Generation.CSharp.Project { [TestClass] public class MetXGeneratorsExeTests { [TestMethod] public void DefaultParametersGenerateWithDefaultTemplatesNamesAndLocations() { Assert.IsTrue(Directory.Exists("Templates")); var worker = new GenGenWorker(); var workerOptions = new GenGenOptions(); worker.Go(workerOptions); Assert.IsTrue(Directory.Exists("net5.0-windows.Aspects")); Assert.IsTrue(File.Exists(@"net5.0-windows.Aspects\net5.0-windows.Aspects.csproj")); Assert.IsTrue(File.Exists(@"net5.0-windows.Aspects\GenerateFromTemplate.cs")); Assert.IsTrue(Directory.Exists("net5.0-windows.Client")); Assert.IsTrue(File.Exists(@"net5.0-windows.Client\net5.0-windows.Client.csproj")); Assert.IsTrue(Directory.Exists("net5.0-windows.Generators")); Assert.IsTrue(File.Exists(@"net5.0-windows.Generators\net5.0-windows.Generators.csproj")); Assert.IsTrue(File.Exists(@"net5.0-windows.Generators\FromTemplateGenerator.cs")); } [TestMethod] public void xDefaultParametersGenerateWithDefaultTemplatesNamesAndLocations() { var worker = new GenGenWorker(); var workerOptions = new GenGenOptions { GeneratorName = "Fred", AttributeName = "George", Namespace = "Mary.Kay", RootFolder = Path.Combine(".", Guid.NewGuid().AsString()), Build = false, Operation = Operation.Create, TemplatesPath = "Templates", Verbose = true, }; worker.Go(workerOptions); } } }
using System; using System.IO; using MetX.Aspects; using MetX.Standard.Generation.CSharp.Project; using MetX.Standard.Generators; using MetX.Standard.Generators.GenGen; using MetX.Standard.Library; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MetX.Tests.Standard.Generation.CSharp.Project { [TestClass] public class MetXGeneratorsExeTests { [TestMethod] public void DefaultParametersGenerateWithDefaultTemplatesNamesAndLocations() { Assert.IsTrue(Directory.Exists("Templates")); var worker = new GenGenWorker(); var workerOptions = new GenGenOptions(); worker.Go(workerOptions); Assert.IsTrue(Directory.Exists("netstandard2_0.Aspects")); Assert.IsTrue(File.Exists(@"netstandard2_0.Aspects\netstandard2_0.Aspects.csproj")); Assert.IsTrue(File.Exists(@"netstandard2_0.Aspects\GenerateFromTemplate.cs")); Assert.IsTrue(Directory.Exists("netstandard2_0.Client")); Assert.IsTrue(File.Exists(@"netstandard2_0.Client\netstandard2_0.Client.csproj")); Assert.IsTrue(Directory.Exists("netstandard2_0.Generators")); Assert.IsTrue(File.Exists(@"netstandard2_0.Generators\netstandard2_0.Generators.csproj")); Assert.IsTrue(File.Exists(@"netstandard2_0.Generators\FromTemplateGenerator.cs")); } [TestMethod] public void xDefaultParametersGenerateWithDefaultTemplatesNamesAndLocations() { var worker = new GenGenWorker(); var workerOptions = new GenGenOptions { GeneratorName = "Fred", AttributeName = "George", Namespace = "Mary.Kay", RootFolder = Path.Combine(".", Guid.NewGuid().AsString()), Build = false, Operation = Operation.Create, TemplatesPath = "Templates", Verbose = true, }; worker.Go(workerOptions); } } }
mit
C#
38d9added37a3a50af920faded516e96647d2c6e
Include by default if there are no rules.
CamTechConsultants/CvsntGitImporter
InclusionMatcher.cs
InclusionMatcher.cs
/* * John Hall <john.hall@xjtag.com> * Copyright (c) Midas Yellow Ltd. All rights reserved. */ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace CvsGitConverter { /// <summary> /// Manages a list of include/exclude rules. /// </summary> class InclusionMatcher { private readonly List<Rule> m_rules = new List<Rule>(); /// <summary> /// Add a rule that includes items if it matches. /// </summary> public void AddIncludeRule(string regex) { if (m_rules.Count == 0) m_rules.Add(new Rule(new Regex("."), false)); m_rules.Add(new Rule(new Regex(regex), true)); } /// <summary> /// Add a rule that excludes items if it matches. /// </summary> public void AddExcludeRule(string regex) { if (m_rules.Count == 0) m_rules.Add(new Rule(new Regex("."), true)); m_rules.Add(new Rule(new Regex(regex), false)); } /// <summary> /// Matches an item. /// </summary> public bool Match(string item) { return m_rules.Aggregate(true, (isMatched, rule) => rule.Match(item, isMatched)); } private class Rule { private readonly Regex m_regex; private readonly bool m_include; public Rule(Regex regex, bool include) { m_regex = regex; m_include = include; } public bool Match(string item, bool isMatched) { if (m_regex.IsMatch(item)) return m_include; else return isMatched; } public override string ToString() { return String.Format("{0} ({1})", m_regex, m_include ? "include" : "exclude"); } } } }
/* * John Hall <john.hall@xjtag.com> * Copyright (c) Midas Yellow Ltd. All rights reserved. */ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace CvsGitConverter { /// <summary> /// Manages a list of include/exclude rules. /// </summary> class InclusionMatcher { private readonly List<Rule> m_rules = new List<Rule>(); /// <summary> /// Add a rule that includes items if it matches. /// </summary> public void AddIncludeRule(string regex) { if (m_rules.Count == 0) m_rules.Add(new Rule(new Regex("."), false)); m_rules.Add(new Rule(new Regex(regex), true)); } /// <summary> /// Add a rule that excludes items if it matches. /// </summary> public void AddExcludeRule(string regex) { if (m_rules.Count == 0) m_rules.Add(new Rule(new Regex("."), true)); m_rules.Add(new Rule(new Regex(regex), false)); } /// <summary> /// Matches an item. /// </summary> public bool Match(string item) { return m_rules.Aggregate(false, (isMatched, rule) => rule.Match(item, isMatched)); } private class Rule { private readonly Regex m_regex; private readonly bool m_include; public Rule(Regex regex, bool include) { m_regex = regex; m_include = include; } public bool Match(string item, bool isMatched) { if (m_regex.IsMatch(item)) return m_include; else return isMatched; } public override string ToString() { return String.Format("{0} ({1})", m_regex, m_include ? "include" : "exclude"); } } } }
mit
C#
48d662f306bbd9d19accb7e379d5cf0d99ae2701
Fix incorrect whitespace in ColoreException.cs
CoraleStudios/Colore,WolfspiritM/Colore
Corale.Colore/ColoreException.cs
Corale.Colore/ColoreException.cs
// --------------------------------------------------------------------------------------- // <copyright file="ColoreException.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore { using System; using System.Runtime.Serialization; /// <summary> /// Generic Colore library exception. /// </summary> [Serializable] public class ColoreException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ColoreException" /> class. /// </summary> /// <param name="message">Exception message.</param> /// <param name="innerException">Inner exception object.</param> internal ColoreException(string message = null, Exception innerException = null) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="ColoreException" /> class /// from serialization data. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> protected ColoreException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// --------------------------------------------------------------------------------------- // <copyright file="ColoreException.cs" company="Corale"> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Corale.Colore { using System; using System.Runtime.Serialization; /// <summary> /// Generic Colore library exception. /// </summary> [Serializable] public class ColoreException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ColoreException" /> class. /// </summary> /// <param name="message">Exception message.</param> /// <param name="innerException">Inner exception object.</param> internal ColoreException(string message = null, Exception innerException = null) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="ColoreException" /> class /// from serialization data. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> protected ColoreException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
C#
aa58ac9591954e3229b06a7f647fce776e7c05f2
remove comment
TeoVincent/Event-Aggregator-Through-net.pipe
TeoVincent.EventAggregator.Client/PublishSwitherPartials/PublishSwitcher.cs
TeoVincent.EventAggregator.Client/PublishSwitherPartials/PublishSwitcher.cs
using System; using TeoVincent.EA.Common; using TeoVincent.EA.Common.Events; namespace TeoVincent.EA.Client.PublishSwitherPartials { public partial class PublishSwitcher : IPublishSwitcher { private readonly IEventAggregator internalEventAggregator; public PublishSwitcher(IEventAggregator internalEventAggregator) { this.internalEventAggregator = internalEventAggregator; } public bool PublishKnowType(AEvent e) { try { return internalEventAggregator.Publish(e); } catch (Exception ex) { Console.WriteLine(string.Format("Exception during: IEventPublisher >> Publish({0}); MyMessage: {1}; Message: {2}", e, "This may be due to erroneous implement the constructor of the event. This event will no longer redistributed!", ex.Message), ex); return false; } } } }
using System; using TeoVincent.EA.Common; using TeoVincent.EA.Common.Events; namespace TeoVincent.EA.Client.PublishSwitherPartials { public partial class PublishSwitcher : IPublishSwitcher { private readonly IEventAggregator internalEventAggregator; public PublishSwitcher(IEventAggregator internalEventAggregator) { this.internalEventAggregator = internalEventAggregator; } public bool PublishKnowType(AEvent e) { try { // TODO: Is the switcher necessary at all? return internalEventAggregator.Publish(e); } catch (Exception ex) { Console.WriteLine(string.Format("Exception during: IEventPublisher >> Publish({0}); MyMessage: {1}; Message: {2}", e, "This may be due to erroneous implement the constructor of the event. This event will no longer redistributed!", ex.Message), ex); return false; } } } }
mit
C#
415870bb301ccb6027d89d32010b63f1834d05c6
Add missing calling convention
gstreamer-sharp/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp
sources/custom/Message.cs
sources/custom/Message.cs
// Copyright (C) 2013 Stephan Sundermann <stephansundermann@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA namespace Gst { using System; using System.Runtime.InteropServices; partial class Message { [DllImport ("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gst_message_parse_error (IntPtr msg, out IntPtr err, out IntPtr debug); public void ParseError (out GLib.GException error, out string debug) { if (Type != MessageType.Error) throw new ArgumentException (); IntPtr err; IntPtr dbg; gst_message_parse_error (Handle, out err, out dbg); if (dbg != IntPtr.Zero) debug = GLib.Marshaller.Utf8PtrToString (dbg); else debug = null; if (err == IntPtr.Zero) throw new Exception (); error = new GLib.GException (err); } [DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gst_message_get_stream_status_object(IntPtr raw); [DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gst_message_set_stream_status_object(IntPtr raw, IntPtr value); public GLib.Value StreamStatusObject { get { if(Type != MessageType.StreamStatus) throw new ArgumentException (); IntPtr raw_ret = gst_message_get_stream_status_object(Handle); GLib.Value ret = (GLib.Value) Marshal.PtrToStructure (raw_ret, typeof (GLib.Value)); return ret; } set { if(Type != MessageType.StreamStatus) throw new ArgumentException (); IntPtr native_value = GLib.Marshaller.StructureToPtrAlloc (value); gst_message_set_stream_status_object(Handle, native_value); value = (GLib.Value) Marshal.PtrToStructure (native_value, typeof (GLib.Value)); Marshal.FreeHGlobal (native_value); } } } }
// Copyright (C) 2013 Stephan Sundermann <stephansundermann@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA namespace Gst { using System; using System.Runtime.InteropServices; partial class Message { [DllImport ("libgstreamer-1.0-0.dll") ] static extern void gst_message_parse_error (IntPtr msg, out IntPtr err, out IntPtr debug); public void ParseError (out GLib.GException error, out string debug) { if (Type != MessageType.Error) throw new ArgumentException (); IntPtr err; IntPtr dbg; gst_message_parse_error (Handle, out err, out dbg); if (dbg != IntPtr.Zero) debug = GLib.Marshaller.Utf8PtrToString (dbg); else debug = null; if (err == IntPtr.Zero) throw new Exception (); error = new GLib.GException (err); } [DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gst_message_get_stream_status_object(IntPtr raw); [DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern void gst_message_set_stream_status_object(IntPtr raw, IntPtr value); public GLib.Value StreamStatusObject { get { if(Type != MessageType.StreamStatus) throw new ArgumentException (); IntPtr raw_ret = gst_message_get_stream_status_object(Handle); GLib.Value ret = (GLib.Value) Marshal.PtrToStructure (raw_ret, typeof (GLib.Value)); return ret; } set { if(Type != MessageType.StreamStatus) throw new ArgumentException (); IntPtr native_value = GLib.Marshaller.StructureToPtrAlloc (value); gst_message_set_stream_status_object(Handle, native_value); value = (GLib.Value) Marshal.PtrToStructure (native_value, typeof (GLib.Value)); Marshal.FreeHGlobal (native_value); } } } }
lgpl-2.1
C#