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
b6a1e5eca322d903017f7b79483d5f66b24bebb3
Add information to AssemblyInfo
Xcodo/atom-launcher
AtomLauncher/Properties/AssemblyInfo.cs
AtomLauncher/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("Atom Launcher")] [assembly: AssemblyDescription("Windows Explorer-friendly launcher for Atom")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AtomLauncher")] [assembly: AssemblyCopyright("Copyright © Mark Brett 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("9d6bc081-0c75-4dcb-be3d-dcf859c3a420")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyFileVersion("0.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("AtomLauncher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AtomLauncher")] [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("9d6bc081-0c75-4dcb-be3d-dcf859c3a420")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
4cc9e37df0153f8746607aea2ff0c03883fa3857
Reset kind enum broken (#2)
svrooij/DirectAdmin
DirectAdmin.Client/ResetPasswordKind.cs
DirectAdmin.Client/ResetPasswordKind.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DirectAdmin.Client { /// <summary> /// Use this to specify what kind of password need to be reset. /// </summary> [Flags] public enum ResetPasswordKind { /// <summary>Default value, will not work on newer versions of DA</summary> NotSpecified = 0, /// <summary>Reset everything</summary> All = System | Ftp | Database, /// <summary>DirectAdmin account</summary> System = 1, /// <summary>FTP account</summary> Ftp = 2, /// <summary>Mysql database account</summary> Database = 4 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DirectAdmin.Client { /// <summary> /// Use this to specify what kind of password need to be reset. /// </summary> [Flags] public enum ResetPasswordKind { /// <summary>Default value, will not work on newer versions of DA</summary> NotSpecified = 0, /// <summary>Reset everything</summary> All = 2 & 4 & 8, /// <summary>DirectAdmin account</summary> System = 2, /// <summary>FTP account</summary> Ftp = 4, /// <summary>Mysql database account</summary> Database = 8 } }
mit
C#
ce424b6ece604f8ea65d754d00051bc1ddb2971d
Fix wrong target
c0nnex/7dtdmanager
7DTDManager/7DTDManager/Commands/cmdClearCooldown.cs
7DTDManager/7DTDManager/Commands/cmdClearCooldown.cs
using _7DTDManager.Interfaces; using _7DTDManager.Interfaces.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DTDManager.Commands { public class cmdClearCooldown : AdminCommandBase { public cmdClearCooldown() { CommandName = "clearcooldown"; CommandHelp = "Clear cooldowns of a player."; } public override bool Execute(IServerConnection server, IPlayer p, params string[] args) { if ( args.Length < 2) { return false; } IPlayer target = server.allPlayers.FindPlayerByName(args[1]); if ((target == null) || (!target.IsOnline)) { p.Message("Targetplayer '{0}' was not found or is not online.", args[1]); return false; } target.ClearCooldowns(); p.Message("You cleared {0}'s cooldowns.", target.Name); target.Message("{0} cleared your cooldowns.", p.Name); server.allPlayers.Save(); return true; } } }
using _7DTDManager.Interfaces; using _7DTDManager.Interfaces.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DTDManager.Commands { public class cmdClearCooldown : AdminCommandBase { public cmdClearCooldown() { CommandName = "clearcooldown"; CommandHelp = "Clear cooldowns of a player."; } public override bool Execute(IServerConnection server, IPlayer p, params string[] args) { if ( args.Length < 2) { return false; } IPlayer target = server.allPlayers.FindPlayerByName(args[1]); if ((target == null) || (!target.IsOnline)) { p.Message("Targetplayer '{0}' was not found or is not online.", args[1]); return false; } p.ClearCooldowns(); p.Message("You cleared {0}'s cooldowns.", target.Name); target.Message("{0} cleared your cooldowns.", p.Name); server.allPlayers.Save(); return true; } } }
bsd-3-clause
C#
41b79a707967bb189c9d2a2833be3d61555c114b
Upgrade version
mbwtepaske/Community
Community.Spatial/Properties/AssemblyInfo.Version.cs
Community.Spatial/Properties/AssemblyInfo.Version.cs
using System.Reflection; [assembly: AssemblyVersion("0.1.0.7454")] [assembly: AssemblyFileVersion("0.1.0.7454")]
using System.Reflection; [assembly: AssemblyVersion("0.1.0.7019")] [assembly: AssemblyFileVersion("0.1.0.7019")]
mit
C#
926bc5d5d808bb1bfc8d548e2b3ea375bce69e0b
Use strings for IDs (for flexibility)
IWBWbiz/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner
MultiMiner.Win/Notifications/NotificationsControl.cs
MultiMiner.Win/Notifications/NotificationsControl.cs
using System; using System.Windows.Forms; namespace MultiMiner.Win.Notifications { public partial class NotificationsControl : UserControl { //events //delegate declarations public delegate void NotificationsChangedHandler(object sender); //event declarations public event NotificationsChangedHandler NotificationsChanged; public NotificationsControl() { InitializeComponent(); } public void AddNotification(string id, string text, Action clickHandler, string informationUrl = "") { NotificationControl notificationControl; foreach (Control control in containerPanel.Controls) { notificationControl = (NotificationControl)control; if ((string)notificationControl.Tag == id) return; } notificationControl = new NotificationControl(text, clickHandler, (nc) => { nc.Parent = null; if (NotificationsChanged != null) NotificationsChanged(this); }, informationUrl); notificationControl.Height = 28; notificationControl.Parent = containerPanel; notificationControl.Top = Int16.MaxValue; notificationControl.Tag = (object)id; notificationControl.BringToFront(); notificationControl.Dock = DockStyle.Top; containerPanel.ScrollControlIntoView(notificationControl); if (NotificationsChanged != null) NotificationsChanged(this); } public int NotificationCount() { return containerPanel.Controls.Count; } } }
using System; using System.Windows.Forms; namespace MultiMiner.Win.Notifications { public partial class NotificationsControl : UserControl { //events //delegate declarations public delegate void NotificationsChangedHandler(object sender); //event declarations public event NotificationsChangedHandler NotificationsChanged; public NotificationsControl() { InitializeComponent(); } public void AddNotification(int id, string text, Action clickHandler, string informationUrl = "") { NotificationControl notificationControl; foreach (Control control in containerPanel.Controls) { notificationControl = (NotificationControl)control; if ((int)notificationControl.Tag == id) return; } notificationControl = new NotificationControl(text, clickHandler, (nc) => { nc.Parent = null; if (NotificationsChanged != null) NotificationsChanged(this); }, informationUrl); notificationControl.Height = 28; notificationControl.Parent = containerPanel; notificationControl.Top = Int16.MaxValue; notificationControl.Tag = (object)id; notificationControl.BringToFront(); notificationControl.Dock = DockStyle.Top; containerPanel.ScrollControlIntoView(notificationControl); if (NotificationsChanged != null) NotificationsChanged(this); } public int NotificationCount() { return containerPanel.Controls.Count; } } }
mit
C#
4b97ee208e5e32124a95ea5e28042c7234159ee4
Update assembly version
LaylaLiu/lab
ODataConnectedService/src/Properties/AssemblyInfo.cs
ODataConnectedService/src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Contoso.Samples.ConnectedServices.UITemplates.Wizard")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Contoso.Samples.ConnectedServices.UITemplates.Wizard")] [assembly: AssemblyCopyright("")] [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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Contoso.Samples.ConnectedServices.UITemplates.Wizard")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Contoso.Samples.ConnectedServices.UITemplates.Wizard")] [assembly: AssemblyCopyright("")] [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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
d4b7835a4c60ab05610dae794203b265f6c49f7f
fix race condition
rob-somerville/serilog-sinks-http
test/Serilog.Sinks.Http.Tests/Sinks/Http/HttpSinkTest.cs
test/Serilog.Sinks.Http.Tests/Sinks/Http/HttpSinkTest.cs
using System; using System.Net.Http; using Moq; using Serilog.Sinks.Http.Tests.Support; using Xunit; namespace Serilog.Sinks.Http.Tests.Sinks.Http { public class HttpSinkTest { private readonly Mock<IHttpClient> client; private readonly string requestUri; private readonly HttpSink sink; public HttpSinkTest() { client = new Mock<IHttpClient>(); requestUri = "www.mylogs.com"; sink = new HttpSink( client.Object, requestUri, HttpSink.DefaultBatchPostingLimit, HttpSink.DefaultPeriod, null); } [Fact] public void RequestUri() { // Arrange var counter = new Counter(1); client .Setup(mock => mock.PostAsync(requestUri, It.IsAny<HttpContent>())) .Callback(() => counter.Increment()); // Act sink.Emit(Some.DebugEvent()); // Assert counter.Wait(TimeSpan.FromSeconds(10)); } } }
using System.Net.Http; using Moq; using Serilog.Sinks.Http.Tests.Support; using Xunit; namespace Serilog.Sinks.Http.Tests.Sinks.Http { public class HttpSinkTest { private readonly Mock<IHttpClient> client; private readonly string requestUri; private readonly HttpSink sink; public HttpSinkTest() { client = new Mock<IHttpClient>(); requestUri = "www.mylogs.com"; sink = new HttpSink( client.Object, requestUri, HttpSink.DefaultBatchPostingLimit, HttpSink.DefaultPeriod, null); } [Fact] public void RequestUri() { // Act sink.Emit(Some.DebugEvent()); // Assert client.Verify( mock => mock.PostAsync( requestUri, It.IsAny<HttpContent>()), Times.Once); } } }
apache-2.0
C#
174f7525b7108e67838f631b714ff804648f6fce
add BackgroundColor to ImageSharpConverter
signumsoftware/framework,signumsoftware/framework
Signum.Engine.Extensions/Word/ImageSharpConverter.cs
Signum.Engine.Extensions/Word/ImageSharpConverter.cs
using DocumentFormat.OpenXml.Packaging; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Processing; using System.IO; #pragma warning disable CA1416 // Validate platform compatibility namespace Signum.Engine.Word; public class ImageSharpConverter : IImageConverter<Image> { public static readonly ImageSharpConverter Instance = new ImageSharpConverter(); public Image FromStream(Stream stream) { return Image.Load(stream); } public (int width, int height) GetSize(Image image) { var size = image.Size(); return (size.Width, size.Height); } public Image Resize(Image image, int maxWidth, int maxHeight) { return image.Clone(x => { x.Resize(new ResizeOptions { Size = new Size(maxWidth, maxHeight), Mode = ResizeMode.Max, }) .BackgroundColor(Color.White); }); } public void Save(Image image, Stream str, ImagePartType imagePartType) { image.Save(str, ToImageFormat(imagePartType)); } private static IImageEncoder ToImageFormat(ImagePartType imagePartType) { switch (imagePartType) { case ImagePartType.Bmp: return new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder(); case ImagePartType.Emf: throw new NotSupportedException(imagePartType.ToString()); case ImagePartType.Gif: return new SixLabors.ImageSharp.Formats.Gif.GifEncoder(); case ImagePartType.Icon: throw new NotSupportedException(imagePartType.ToString()); case ImagePartType.Jpeg: return new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder(); case ImagePartType.Png: return new SixLabors.ImageSharp.Formats.Png.PngEncoder(); case ImagePartType.Tiff: return new SixLabors.ImageSharp.Formats.Tiff.TiffEncoder(); case ImagePartType.Wmf: throw new NotSupportedException(imagePartType.ToString()); } throw new InvalidOperationException("Unexpected {0}".FormatWith(imagePartType)); } }
using DocumentFormat.OpenXml.Packaging; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Processing; using System.IO; #pragma warning disable CA1416 // Validate platform compatibility namespace Signum.Engine.Word; public class ImageSharpConverter : IImageConverter<Image> { public static readonly ImageSharpConverter Instance = new ImageSharpConverter(); public Image FromStream(Stream stream) { return Image.Load(stream); } public (int width, int height) GetSize(Image image) { var size = image.Size(); return (size.Width, size.Height); } public Image Resize(Image image, int maxWidth, int maxHeight) { return image.Clone(x => { x.Resize(new ResizeOptions { Size = new Size(maxWidth, maxHeight), Mode = ResizeMode.Max, }); }); } public void Save(Image image, Stream str, ImagePartType imagePartType) { image.Save(str, ToImageFormat(imagePartType)); } private static IImageEncoder ToImageFormat(ImagePartType imagePartType) { switch (imagePartType) { case ImagePartType.Bmp: return new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder(); case ImagePartType.Emf: throw new NotSupportedException(imagePartType.ToString()); case ImagePartType.Gif: return new SixLabors.ImageSharp.Formats.Gif.GifEncoder(); case ImagePartType.Icon: throw new NotSupportedException(imagePartType.ToString()); case ImagePartType.Jpeg: return new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder(); case ImagePartType.Png: return new SixLabors.ImageSharp.Formats.Png.PngEncoder(); case ImagePartType.Tiff: return new SixLabors.ImageSharp.Formats.Tiff.TiffEncoder(); case ImagePartType.Wmf: throw new NotSupportedException(imagePartType.ToString()); } throw new InvalidOperationException("Unexpected {0}".FormatWith(imagePartType)); } }
mit
C#
e0c47c17c9490e4a4fdbedf052700814c4aaf409
Fix typo
hubuk/CodeContracts,danielcweber/CodeContracts,Microsoft/CodeContracts,hubuk/CodeContracts,hubuk/CodeContracts,Microsoft/CodeContracts,Microsoft/CodeContracts,danielcweber/CodeContracts,huoxudong125/CodeContracts,ndykman/CodeContracts,huoxudong125/CodeContracts,ndykman/CodeContracts,SergeyTeplyakov/CodeContracts,hubuk/CodeContracts,huoxudong125/CodeContracts,hubuk/CodeContracts,ndykman/CodeContracts,SergeyTeplyakov/CodeContracts,huoxudong125/CodeContracts,Microsoft/CodeContracts,ndykman/CodeContracts,SergeyTeplyakov/CodeContracts,SergeyTeplyakov/CodeContracts,hubuk/CodeContracts,huoxudong125/CodeContracts,huoxudong125/CodeContracts,Microsoft/CodeContracts,danielcweber/CodeContracts,SergeyTeplyakov/CodeContracts,Microsoft/CodeContracts,ndykman/CodeContracts,danielcweber/CodeContracts,Microsoft/CodeContracts,ndykman/CodeContracts,danielcweber/CodeContracts,hubuk/CodeContracts,ndykman/CodeContracts,SergeyTeplyakov/CodeContracts,SergeyTeplyakov/CodeContracts,danielcweber/CodeContracts,huoxudong125/CodeContracts,danielcweber/CodeContracts
System.Compiler/PDBreader/PdbDebugException.cs
System.Compiler/PDBreader/PdbDebugException.cs
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //----------------------------------------------------------------------------- // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //----------------------------------------------------------------------------- using System; using System.IO; namespace Microsoft.Cci.Pdb { public class PdbDebugException : IOException { internal PdbDebugException(String format, params object[] args) : base(String.Format(format, args)) { } } /// <summary> /// The exception that is thrown when pdb does not contains /names stream. /// </summary> /// <remarks> /// Not all pdb-s contains all possible streams required for debugging. For instance, 'stripped pdb' (see /PDBSTRIPPED at msdn) /// does not have /names stream and should be handled the same way if the pdb is absent. /// </remarks> public class NoNameStreamPdbException : PdbDebugException { internal NoNameStreamPdbException() : base("No '/names' stream was found in the specified pdb") {} } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //----------------------------------------------------------------------------- // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //----------------------------------------------------------------------------- using System; using System.IO; namespace Microsoft.Cci.Pdb { public class PdbDebugException : IOException { internal PdbDebugException(String format, params object[] args) : base(String.Format(format, args)) { } } /// <summary> /// The exception that is thrown when pdb does not contains /names stream. /// </summary> /// <remarks> /// Not all pdb-s contains all possible streams required for debugging. For instnace, 'stripped pdb' (see /PDBSTRIPPED at msdn) /// does not have /names stream and should be handled the same way if the pdb is absent. /// </remarks> public class NoNameStreamPdbException : PdbDebugException { internal NoNameStreamPdbException() : base("No '/names' stream was found in the specified pdb") {} } }
mit
C#
00728741f1bef2dcdaccb0114f987d4f7d6cfefd
Add option for poof sound effect
Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare
Assets/Microgames/KagerouCut/Scripts/FurBallController.cs
Assets/Microgames/KagerouCut/Scripts/FurBallController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FurBallController : MonoBehaviour { [SerializeField] GameObject sprite; public float speed = 0.3f; public float particleRate = 0.1f; public bool shouldExplode = false; public AudioClip poofSound; private float particleTimer = 0.0f; private bool shouldShrink = false; private bool hasMoved = false; private bool finished = false; private Transform t; private ParticleSystem hairEmitter; void Start(){ t = sprite.transform; hairEmitter = GetComponent<ParticleSystem>(); } void Update(){ if (!hasMoved && (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))){ hasMoved = true; } if (finished && t.localScale.x > 0) { float s = Time.deltaTime*speed*3; t.localScale -= new Vector3(s, s, s); if (t.localScale.x <= 0){ gameObject.tag = "Finish"; sprite.GetComponent<Renderer>().enabled = false; t.localScale = new Vector3(0f, 0f, 0f); } } else if (gameObject.tag != "Finish" && shouldShrink && hasMoved){ particleTimer += Time.deltaTime; if (particleTimer > particleRate){ hairEmitter.Play(false); particleTimer = 0.0f; } float s = Time.deltaTime*speed; t.localScale -= new Vector3(s, s, s); if (t.localScale.x <= 0.06){ finished = true; MicrogameController.instance.playSFX(poofSound); if (shouldExplode){ hairEmitter.Play(true); } } } } void OnTriggerEnter2D (Collider2D collider) { if (collider.gameObject.tag == "Player") shouldShrink = true; } void OnTriggerExit2D (Collider2D collider) { if (collider.gameObject.tag == "Player") shouldShrink = false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FurBallController : MonoBehaviour { [SerializeField] GameObject sprite; public float speed = 0.3f; public float particleRate = 0.1f; public bool shouldExplode = false; private float particleTimer = 0.0f; private bool shouldShrink = false; private bool hasMoved = false; private bool finished = false; private Transform t; private ParticleSystem hairEmitter; void Start(){ t = sprite.transform; hairEmitter = GetComponent<ParticleSystem>(); } void Update(){ if (!hasMoved && (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))){ hasMoved = true; } if (finished && t.localScale.x > 0) { float s = Time.deltaTime*speed*3; t.localScale -= new Vector3(s, s, s); if (t.localScale.x <= 0){ gameObject.tag = "Finish"; sprite.GetComponent<Renderer>().enabled = false; t.localScale = new Vector3(0f, 0f, 0f); } } else if (gameObject.tag != "Finish" && shouldShrink && hasMoved){ particleTimer += Time.deltaTime; if (particleTimer > particleRate){ hairEmitter.Play(false); particleTimer = 0.0f; } float s = Time.deltaTime*speed; t.localScale -= new Vector3(s, s, s); if (t.localScale.x <= 0.06){ finished = true; if (shouldExplode){ hairEmitter.Play(true); } } } } void OnTriggerEnter2D (Collider2D collider) { if (collider.gameObject.tag == "Player") shouldShrink = true; } void OnTriggerExit2D (Collider2D collider) { if (collider.gameObject.tag == "Player") shouldShrink = false; } }
mit
C#
1383bdd1e86adc9154aad631d3b67e523a834ad5
Remove unused member variable
tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Client/Components/InstanceClient.cs
src/Tgstation.Server.Client/Components/InstanceClient.cs
using System; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Client.Components { /// <inheritdoc /> sealed class InstanceClient : IInstanceClient { /// <inheritdoc /> public Instance Metadata { get; } /// <inheritdoc /> public IByondClient Byond { get; } /// <inheritdoc /> public IRepositoryClient Repository { get; } /// <inheritdoc /> public IDreamDaemonClient DreamDaemon { get; } /// <inheritdoc /> public IConfigurationClient Configuration { get; } /// <inheritdoc /> public IInstanceUserClient Users { get; } /// <inheritdoc /> public IChatBotsClient ChatBots { get; } /// <inheritdoc /> public IDreamMakerClient DreamMaker { get; } /// <inheritdoc /> public IJobsClient Jobs { get; } /// <summary> /// Construct a <see cref="InstanceClient"/> /// </summary> /// <param name="apiClient">The <see cref="IApiClient"/> used to construct component clients.</param> /// <param name="instance">The value of <see cref="Metadata"/></param> public InstanceClient(IApiClient apiClient, Instance instance) { if (apiClient == null) throw new ArgumentNullException(nameof(apiClient)); Metadata = instance ?? throw new ArgumentNullException(nameof(instance)); Byond = new ByondClient(apiClient, instance); Repository = new RepositoryClient(apiClient, instance); DreamDaemon = new DreamDaemonClient(apiClient, instance); Configuration = new ConfigurationClient(apiClient, instance); Users = new InstanceUserClient(apiClient, instance); ChatBots = new ChatBotsClient(apiClient, instance); DreamMaker = new DreamMakerClient(apiClient, instance); Jobs = new JobsClient(apiClient, instance); } } }
using System; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Client.Components { /// <inheritdoc /> sealed class InstanceClient : IInstanceClient { /// <inheritdoc /> public Instance Metadata { get; } /// <inheritdoc /> public IByondClient Byond { get; } /// <inheritdoc /> public IRepositoryClient Repository { get; } /// <inheritdoc /> public IDreamDaemonClient DreamDaemon { get; } /// <inheritdoc /> public IConfigurationClient Configuration { get; } /// <inheritdoc /> public IInstanceUserClient Users { get; } /// <inheritdoc /> public IChatBotsClient ChatBots { get; } /// <inheritdoc /> public IDreamMakerClient DreamMaker { get; } /// <inheritdoc /> public IJobsClient Jobs { get; } /// <summary> /// The <see cref="IApiClient"/> for the <see cref="InstanceClient"/> /// </summary> readonly IApiClient apiClient; /// <summary> /// Construct a <see cref="InstanceClient"/> /// </summary> /// <param name="apiClient">The value of <see cref="apiClient"/></param> /// <param name="instance">The value of <see cref="Metadata"/></param> public InstanceClient(IApiClient apiClient, Instance instance) { this.apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient)); Metadata = instance ?? throw new ArgumentNullException(nameof(instance)); Byond = new ByondClient(apiClient, instance); Repository = new RepositoryClient(apiClient, instance); DreamDaemon = new DreamDaemonClient(apiClient, instance); Configuration = new ConfigurationClient(apiClient, instance); Users = new InstanceUserClient(apiClient, instance); ChatBots = new ChatBotsClient(apiClient, instance); DreamMaker = new DreamMakerClient(apiClient, instance); Jobs = new JobsClient(apiClient, instance); } } }
agpl-3.0
C#
4d758c3a01022db6973ad32ff0417997951005dd
fix test data
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
rider/testData/integrationTests/PlayModeTest/checkPlayModeLogs/source/NewBehaviourScript.cs
rider/testData/integrationTests/PlayModeTest/checkPlayModeLogs/source/NewBehaviourScript.cs
using UnityEngine; using System.Threading; public class NewBehaviourScript : MonoBehaviour { void Start() { Debug.Log("Start"); new Thread(() => { Debug.Log("StartFromBackgroundThread"); }).Start(); } void Update() { Debug.Log("Update"); new Thread(() => { Debug.Log("UpdateFromBackgroundThread"); }).Start(); } void OnApplicationQuit() { Debug.Log("Quit"); new Thread(() => { Debug.Log("QuitFromBackgroundThread"); }).Start(); } }
using UnityEngine; public class NewBehaviourScript : MonoBehaviour { void Start() { Debug.Log("Start"); } void Update() { Debug.Log("Update"); } void OnApplicationQuit() { Debug.Log("Quit"); } }
apache-2.0
C#
1b0a1dd4108285dbec840ad8cf9a9ef1b014d066
Add missing licence header
DrabWeb/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,ZLima12/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,Damnae/osu,UselessToucan/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,DrabWeb/osu,naoey/osu,peppy/osu,ZLima12/osu,peppy/osu-new,NeoAdonis/osu,johnneijzen/osu,Nabile-Rahmani/osu,UselessToucan/osu,peppy/osu,Drezi126/osu,2yangk23/osu,naoey/osu,DrabWeb/osu,ppy/osu,EVAST9919/osu,naoey/osu,NeoAdonis/osu,Frontear/osuKyzer
osu.Game.Rulesets.Osu/Replays/OsuReplayInputHandler.cs
osu.Game.Rulesets.Osu/Replays/OsuReplayInputHandler.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using osu.Framework.Input; using osu.Game.Rulesets.Replays; using OpenTK; namespace osu.Game.Rulesets.Osu.Replays { public class OsuReplayInputHandler : FramedReplayInputHandler { public OsuReplayInputHandler(Replay replay) : base(replay) { } public override List<InputState> GetPendingStates() { List<OsuAction> actions = new List<OsuAction>(); if (CurrentFrame?.MouseLeft ?? false) actions.Add(OsuAction.LeftButton); if (CurrentFrame?.MouseRight ?? false) actions.Add(OsuAction.RightButton); return new List<InputState> { new ReplayState<OsuAction> { Mouse = new ReplayMouseState(ToScreenSpace(Position ?? Vector2.Zero)), PressedActions = actions } }; } } }
using System.Collections.Generic; using osu.Framework.Input; using osu.Game.Rulesets.Replays; using OpenTK; namespace osu.Game.Rulesets.Osu.Replays { public class OsuReplayInputHandler : FramedReplayInputHandler { public OsuReplayInputHandler(Replay replay) : base(replay) { } public override List<InputState> GetPendingStates() { List<OsuAction> actions = new List<OsuAction>(); if (CurrentFrame?.MouseLeft ?? false) actions.Add(OsuAction.LeftButton); if (CurrentFrame?.MouseRight ?? false) actions.Add(OsuAction.RightButton); return new List<InputState> { new ReplayState<OsuAction> { Mouse = new ReplayMouseState(ToScreenSpace(Position ?? Vector2.Zero)), PressedActions = actions } }; } } }
mit
C#
ab48b1531f94d6db13814811ec35d69896970a6f
fix ragnarok duration
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/ClassSpecific/ValkyrieAbnormalityTracker.cs
TCC.Core/ClassSpecific/ValkyrieAbnormalityTracker.cs
using TCC.Parsing.Messages; using TCC.ViewModels; namespace TCC.ClassSpecific { public class ValkyrieAbnormalityTracker : ClassAbnormalityTracker { private const uint RagnarokId = 10155130; public override void CheckAbnormality(S_ABNORMALITY_BEGIN p) { if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return; CheckRagnarok(p); } public override void CheckAbnormality(S_ABNORMALITY_REFRESH p) { if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return; CheckRagnarok(p); } public override void CheckAbnormality(S_ABNORMALITY_END p) { if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return; CheckRagnarok(p); } private static void CheckRagnarok(S_ABNORMALITY_BEGIN p) { if (p.AbnormalityId != RagnarokId) return; ((ValkyrieBarManager)ClassWindowViewModel.Instance.CurrentManager).Ragnarok.Buff.Start(p.Duration); } private static void CheckRagnarok(S_ABNORMALITY_END p) { if (p.AbnormalityId != RagnarokId) return; ((ValkyrieBarManager)ClassWindowViewModel.Instance.CurrentManager).Ragnarok.Buff.Refresh(0); } private static void CheckRagnarok(S_ABNORMALITY_REFRESH p) { if (p.AbnormalityId != RagnarokId) return; ((ValkyrieBarManager)ClassWindowViewModel.Instance.CurrentManager).Ragnarok.Buff.Refresh(p.Duration); } } }
using TCC.Parsing.Messages; using TCC.ViewModels; namespace TCC.ClassSpecific { public class ValkyrieAbnormalityTracker : ClassAbnormalityTracker { private const uint RagnarokId = 10155130; public override void CheckAbnormality(S_ABNORMALITY_BEGIN p) { if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return; CheckRagnarok(p); } public override void CheckAbnormality(S_ABNORMALITY_END p) { if (p.TargetId != SessionManager.CurrentPlayer.EntityId) return; CheckRagnarok(p); } private static void CheckRagnarok(S_ABNORMALITY_BEGIN p) { if (p.AbnormalityId != RagnarokId) return; ((ValkyrieBarManager)ClassWindowViewModel.Instance.CurrentManager).Ragnarok.Buff.Start(p.Duration); } private static void CheckRagnarok(S_ABNORMALITY_END p) { if (p.AbnormalityId != RagnarokId) return; ((ValkyrieBarManager)ClassWindowViewModel.Instance.CurrentManager).Ragnarok.Buff.Refresh(0); } } }
mit
C#
c7c36fa6cd913b9ca84840555244c2d67f5992a0
Remove WA1202
DotNetAnalyzers/WpfAnalyzers,JohanLarsson/WpfAnalyzers
WpfAnalyzers.Analyzers/DependencyProperties/WA1202DefaultValueTypeMustMatchRegisteredType.cs
WpfAnalyzers.Analyzers/DependencyProperties/WA1202DefaultValueTypeMustMatchRegisteredType.cs
//namespace WpfAnalyzers.DependencyProperties //{ // using System; // using System.Collections.Immutable; // using Microsoft.CodeAnalysis; // using Microsoft.CodeAnalysis.CSharp; // using Microsoft.CodeAnalysis.CSharp.Syntax; // using Microsoft.CodeAnalysis.Diagnostics; // [DiagnosticAnalyzer(LanguageNames.CSharp)] // internal class WA1202DefaultValueTypeMustMatchRegisteredType : DiagnosticAnalyzer // { // public const string DiagnosticId = "WA1202"; // private const string Title = "DependencyProperty default value must be of the type it is registered as."; // private const string MessageFormat = "DependencyProperty '{0}' default value must be of type {1}"; // private const string Description = Title; // private const string HelpLink = "http://stackoverflow.com/"; // private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( // DiagnosticId, // Title, // MessageFormat, // AnalyzerCategory.DependencyProperties, // DiagnosticSeverity.Error, // AnalyzerConstants.EnabledByDefault, // Description, // HelpLink); // /// <inheritdoc/> // public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Descriptor); // /// <inheritdoc/> // public override void Initialize(AnalysisContext context) // { // context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); // context.EnableConcurrentExecution(); // context.RegisterSyntaxNodeAction(HandleFieldDeclaration, SyntaxKind.FieldDeclaration); // } // private static void HandleFieldDeclaration(SyntaxNodeAnalysisContext context) // { // var fieldSymbol = (IFieldSymbol)context.ContainingSymbol; // if (!fieldSymbol.IsDependencyPropertyField()) // { // return; // } // var fieldDeclaration = context.Node as FieldDeclarationSyntax; // if (fieldDeclaration == null || fieldDeclaration.IsMissing) // { // return; // } // var type = fieldDeclaration.DependencyPropertyRegisteredType(); // var defaultValue = fieldDeclaration.DependencyPropertyRegisteredDefaultValue(); // throw new NotImplementedException(); // } // } //}
namespace WpfAnalyzers.DependencyProperties { using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class WA1202DefaultValueTypeMustMatchRegisteredType : DiagnosticAnalyzer { public const string DiagnosticId = "WA1202"; private const string Title = "DependencyProperty default value must be of the type it is registered as."; private const string MessageFormat = "DependencyProperty '{0}' default value must be of type {1}"; private const string Description = Title; private const string HelpLink = "http://stackoverflow.com/"; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( DiagnosticId, Title, MessageFormat, AnalyzerCategory.DependencyProperties, DiagnosticSeverity.Error, AnalyzerConstants.EnabledByDefault, Description, HelpLink); /// <inheritdoc/> public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Descriptor); /// <inheritdoc/> public override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterSyntaxNodeAction(HandleFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void HandleFieldDeclaration(SyntaxNodeAnalysisContext context) { var fieldSymbol = (IFieldSymbol)context.ContainingSymbol; if (!fieldSymbol.IsDependencyPropertyField()) { return; } var fieldDeclaration = context.Node as FieldDeclarationSyntax; if (fieldDeclaration == null || fieldDeclaration.IsMissing) { return; } var type = fieldDeclaration.DependencyPropertyRegisteredType(); var defaultValue = fieldDeclaration.DependencyPropertyRegisteredDefaultValue(); throw new NotImplementedException(); } } }
mit
C#
6c9e6296be94c2d54173a4f9ea2fdc5404698ab3
Update Viktor.cs
FireBuddy/adevade
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
using System; using EloBuddy; using EloBuddy.SDK; namespace AdEvade.Data.Spells.SpecialSpells { class Viktor : IChampionPlugin { static Viktor() { } public const string ChampionName = "Viktor"; public string GetChampionName() { return ChampionName; } public void LoadSpecialSpell(SpellData spellData) { if (spellData.SpellName == "ViktorDeathRay") { Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3; } } private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender != null && sender.Team != ObjectManager.Player.Team && args.SData.Name != null && args.SData.Name == "ViktorDeathRay") { } } } }
using System; using EloBuddy; using EloBuddy.SDK; namespace AdEvade.Data.Spells.SpecialSpells { class Viktor : IChampionPlugin { static Viktor() { } public const string ChampionName = "Viktor"; public string GetChampionName() { return ChampionName; } public void LoadSpecialSpell(SpellData spellData) { if (spellData.SpellName == "ViktorDeathRay") { Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3; } } private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender != null && sender.Team != ObjectManager.Player.Team && args.SData.Name != null && args.SData.Name == "ViktorDeathRay") { var End = enemy.GetWaypoints().Last(); var missileDist = End.To2D().Distance(args.Start.To2D()); var delay = missileDist / 1.5f + 600; spellData.SpellDelay = delay; SpellDetector.CreateSpellData(sender, args.Start, End, spellData); } } } }
mit
C#
34a380c589ef1bee1ad239c67980135b725f3ee7
Fix error with liquid propegation through air
blha303/TrueCraft,SirCmpwn/TrueCraft,illblew/TrueCraft,christopherbauer/TrueCraft,christopherbauer/TrueCraft,Mitch528/TrueCraft,robinkanters/TrueCraft,thdtjsdn/TrueCraft,manio143/TrueCraft,Mitch528/TrueCraft,creatorfromhell/TrueCraft,christopherbauer/TrueCraft,robinkanters/TrueCraft,SirCmpwn/TrueCraft,illblew/TrueCraft,flibitijibibo/TrueCraft,flibitijibibo/TrueCraft,manio143/TrueCraft,thdtjsdn/TrueCraft,SirCmpwn/TrueCraft,creatorfromhell/TrueCraft,Mitch528/TrueCraft,manio143/TrueCraft,robinkanters/TrueCraft,blha303/TrueCraft,thdtjsdn/TrueCraft,flibitijibibo/TrueCraft,illblew/TrueCraft,blha303/TrueCraft
TrueCraft.Core/Logic/Blocks/AirBlock.cs
TrueCraft.Core/Logic/Blocks/AirBlock.cs
using System; using TrueCraft.API; using TrueCraft.API.Logic; namespace TrueCraft.Core.Logic.Blocks { public class AirBlock : BlockProvider { public static readonly byte BlockID = 0x00; public override byte ID { get { return 0x00; } } public override double BlastResistance { get { return 0; } } public override double Hardness { get { return 0; } } public override bool Opaque { get { return false; } } public override byte Luminance { get { return 0; } } public override string DisplayName { get { return "Air"; } } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(0, 0); } protected override ItemStack[] GetDrop(BlockDescriptor descriptor) { return new ItemStack[0]; } } }
using System; using TrueCraft.API; using TrueCraft.API.Logic; namespace TrueCraft.Core.Logic.Blocks { public class AirBlock : BlockProvider { public static readonly byte BlockID = 0x00; public override byte ID { get { return 0x00; } } public override double BlastResistance { get { return 0; } } public override double Hardness { get { return 100000; } } public override bool Opaque { get { return false; } } public override byte Luminance { get { return 0; } } public override string DisplayName { get { return "Air"; } } public override Tuple<int, int> GetTextureMap(byte metadata) { return new Tuple<int, int>(0, 0); } protected override ItemStack[] GetDrop(BlockDescriptor descriptor) { return new ItemStack[0]; } } }
mit
C#
f97c70510a921f8deca4c97f4318a269df82c20e
fix for EF6, no idea why I had to do this
michalguzek/Comessa6,michalguzek/Comessa6,michalguzek/Comessa6
Comessa6/Comessa6/Controllers/PaymentsController.cs
Comessa6/Comessa6/Controllers/PaymentsController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Comessa6.ViewModels; using System.Threading.Tasks; using Comessa6.Models; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace Comessa6.Controllers { public class PaymentsController : Controller { // GET: Orders [HttpGet] public async Task<ActionResult> GetPayments(int userID) { using (var db = new comessa5Entities()) { #region Get Payments DateTime paymentsOlderThan = DateTime.Now; paymentsOlderThan -= TimeSpan.FromHours(paymentsOlderThan.Hour); List<PaymentViewModel> payments = await (from payment in db.vpayment where ((userID == -1 && payment.date > paymentsOlderThan) || payment.recipientId == userID || payment.senderId == userID) orderby payment.id descending select new PaymentViewModel { ID = payment.id, Value = payment.amount, Comment = payment.comment, SenderID = payment.senderId, RecipientID = payment.recipientId, SenderName = payment.senderName, RecipientName = payment.recipientName, Type = (PaymentType)payment.type, Date = payment.date } ).ToListAsync(); return PartialView("PaymentsView", payments); #endregion } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Comessa6.ViewModels; using System.Threading.Tasks; using Comessa6.Models; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace Comessa6.Controllers { public class PaymentsController : Controller { // GET: Orders [HttpGet] public async Task<ActionResult> GetPayments(int userID) { using (var db = new comessa5Entities()) { #region Get Payments DateTime paymentsOlderThan = DateTime.Now; paymentsOlderThan -= TimeSpan.FromHours(paymentsOlderThan.Hour); //int id = (int)Session["UserID"]; List<PaymentViewModel> payments = await db.vpayment .Where(payment => userID == -1 ? (payment.date > paymentsOlderThan) : (payment.recipientId == userID || payment.senderId == userID)) .Select(paymentInfo => new PaymentViewModel { ID = paymentInfo.id, Value = paymentInfo.amount, Comment = paymentInfo.comment, SenderID = paymentInfo.senderId, RecipientID = paymentInfo.recipientId, SenderName = paymentInfo.senderName, RecipientName = paymentInfo.recipientName, Type = (PaymentType)paymentInfo.type, Date = paymentInfo.date } ).ToListAsync(); return PartialView("PaymentsView", payments); #endregion } } } }
mit
C#
8613773835e671b9b674b7651f860f0366986857
Fix exception for empty service alerts list (#46)
RikkiGibson/Corvallis-Bus-Server,RikkiGibson/Corvallis-Bus-Server
CorvallisBus.Core/WebClients/ServiceAlertsClient.cs
CorvallisBus.Core/WebClients/ServiceAlertsClient.cs
using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using CorvallisBus.Core.Models; using HtmlAgilityPack; namespace CorvallisBus.Core.WebClients { public static class ServiceAlertsClient { static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581"); static readonly HttpClient httpClient = new HttpClient(); public static async Task<List<ServiceAlert>> GetServiceAlerts() { var responseStream = await httpClient.GetStreamAsync(FEED_URL); var htmlDocument = new HtmlDocument(); htmlDocument.Load(responseStream); var alerts = htmlDocument.DocumentNode .SelectNodes("//tbody/tr") ?.Select(row => ParseRow(row)) .ToList() ?? new List<ServiceAlert>(); return alerts; } private static ServiceAlert ParseRow(HtmlNode row) { var anchor = row.Descendants("a").First(); var relativeLink = anchor.Attributes["href"].Value; var link = new Uri(FEED_URL, relativeLink).ToString(); var title = anchor.InnerText; var publishDate = row.Descendants("span") .First(node => node.HasClass("date-display-single")) .Attributes["content"] .Value; return new ServiceAlert(title, publishDate, link); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using CorvallisBus.Core.Models; using HtmlAgilityPack; namespace CorvallisBus.Core.WebClients { public static class ServiceAlertsClient { static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581"); static readonly HttpClient httpClient = new HttpClient(); public static async Task<List<ServiceAlert>> GetServiceAlerts() { var responseStream = await httpClient.GetStreamAsync(FEED_URL); var htmlDocument = new HtmlDocument(); htmlDocument.Load(responseStream); var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr") .Select(row => ParseRow(row)) .ToList(); return alerts; } private static ServiceAlert ParseRow(HtmlNode row) { var anchor = row.Descendants("a").First(); var relativeLink = anchor.Attributes["href"].Value; var link = new Uri(FEED_URL, relativeLink).ToString(); var title = anchor.InnerText; var publishDate = row.Descendants("span") .First(node => node.HasClass("date-display-single")) .Attributes["content"] .Value; return new ServiceAlert(title, publishDate, link); } } }
mit
C#
52724d503d5024d5d7b18462b82a8229e0cb78fa
test for faced ness
thecodeite/SolitaireSolution
Tests/UnitTests/CardTests.cs
Tests/UnitTests/CardTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentAssertions; using NUnit.Framework; using Solitaire.Models; namespace Tests.UnitTests { [TestFixture] class CardTests { [Test] public void back_of_card_should_be_blank() { var card = new Card(); var appearance = card.Render(); appearance.Should().Be("**"); } [Test] public void card_should_have_front_and_back_and_start_facing_down() { dynamic card = new Card(); bool isFaceDown = card.IsFaceDown; isFaceDown.Should().BeTrue(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentAssertions; using NUnit.Framework; using Solitaire.Models; namespace Tests.UnitTests { [TestFixture] class CardTests { [Test] public void back_of_card_should_be_blank() { var card = new Card(); var appearance = card.Render(); appearance.Should().Be("**"); } } }
mit
C#
e29319e0f2b25f88c83d2c5eb9d6c4cd63a24480
add RequiredMembers
autumn009/TanoCSharpSamples
Chap38/RequiredMembers/RequiredMembers/Program.cs
Chap38/RequiredMembers/RequiredMembers/Program.cs
Person[] persons = { new Person(){ Id="aaa", Name="Alice" }, new Person(){ Id="bbb" } }; sub("aaa"); sub("bbb"); void sub(string key) { var person = persons.First(x => x.Id == key); Console.WriteLine($"Id={person.Id}"); Console.WriteLine($"Name={person.Name ?? "unknwon"}"); } public class Person { public required string Id { get; init; } public string? Name { get; init; } }
// See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, World!");
mit
C#
2bc3c4faba0621814ef438118f7e1c3d233d5b0c
Make controller public to access outside module classes
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Launchpad/components/LaunchpadModuleBase.cs
R7.University.Launchpad/components/LaunchpadModuleBase.cs
// // LaunchpadModuleBase.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2014 // // 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.Entities.Modules; namespace R7.University.Launchpad { /// <summary> /// Launchpad module base. /// </summary> public class LaunchpadPortalModuleBase : PortalModuleBase { private LaunchpadController ctrl = null; public LaunchpadController LaunchpadController { get { return ctrl ?? (ctrl = new LaunchpadController ()); } } private LaunchpadSettings settings = null; protected LaunchpadSettings LaunchpadSettings { get { return settings ?? (settings = new LaunchpadSettings (this)); } } } /// <summary> /// Launchpad module settings base. /// </summary> public class LaunchpadModuleSettingsBase : ModuleSettingsBase { private LaunchpadController ctrl = null; public LaunchpadController LaunchpadController { get { return ctrl ?? (ctrl = new LaunchpadController ()); } } private LaunchpadSettings settings = null; protected LaunchpadSettings LaunchpadSettings { get { return settings ?? (settings = new LaunchpadSettings (this)); } } } }
// // LaunchpadModuleBase.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2014 // // 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.Entities.Modules; namespace R7.University.Launchpad { /// <summary> /// Launchpad module base. /// </summary> public class LaunchpadPortalModuleBase : PortalModuleBase { private LaunchpadController ctrl = null; protected LaunchpadController LaunchpadController { get { return ctrl ?? (ctrl = new LaunchpadController ()); } } private LaunchpadSettings settings = null; protected LaunchpadSettings LaunchpadSettings { get { return settings ?? (settings = new LaunchpadSettings (this)); } } } /// <summary> /// Launchpad module settings base. /// </summary> public class LaunchpadModuleSettingsBase : ModuleSettingsBase { private LaunchpadController ctrl = null; protected LaunchpadController LaunchpadController { get { return ctrl ?? (ctrl = new LaunchpadController ()); } } private LaunchpadSettings settings = null; protected LaunchpadSettings LaunchpadSettings { get { return settings ?? (settings = new LaunchpadSettings (this)); } } } }
agpl-3.0
C#
cbe87e08b67261b9c2311a699ab65ccdca3c9510
Remove deprecated service registration.
peeedge/mobile,eatskolnikov/mobile,eatskolnikov/mobile,masterrr/mobile,masterrr/mobile,peeedge/mobile,ZhangLeiCharles/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile
Tests/Test.cs
Tests/Test.cs
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Toggl.Phoebe.Data; using XPlatUtils; namespace Toggl.Phoebe.Tests { public abstract class Test { private string databasePath; [TestFixtureSetUp] public virtual void Init () { } [TestFixtureTearDown] public virtual void Cleanup () { } [SetUp] public virtual void SetUp () { SynchronizationContext.SetSynchronizationContext (new SynchronizationContext ()); ServiceContainer.Register<MessageBus> (); ServiceContainer.Register<ITimeProvider> (() => new DefaultTimeProvider ()); ServiceContainer.Register<IDataStore> (delegate { databasePath = Path.GetTempFileName (); return new SQLiteDataStore (databasePath); }); } [TearDown] public virtual void TearDown () { ServiceContainer.Clear (); if (databasePath != null) { File.Delete (databasePath); databasePath = null; } } protected void RunAsync (Func<Task> fn) { fn ().GetAwaiter ().GetResult (); } protected MessageBus MessageBus { get { return ServiceContainer.Resolve<MessageBus> (); } } protected IDataStore DataStore { get { return ServiceContainer.Resolve<IDataStore> (); } } } }
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Toggl.Phoebe.Data; using XPlatUtils; namespace Toggl.Phoebe.Tests { public abstract class Test { private string databasePath; [TestFixtureSetUp] public virtual void Init () { } [TestFixtureTearDown] public virtual void Cleanup () { } [SetUp] public virtual void SetUp () { SynchronizationContext.SetSynchronizationContext (new SynchronizationContext ()); ServiceContainer.Register<MessageBus> (); ServiceContainer.Register<ModelManager> (); ServiceContainer.Register<ITimeProvider> (() => new DefaultTimeProvider ()); ServiceContainer.Register<IDataStore> (delegate { databasePath = Path.GetTempFileName (); return new SQLiteDataStore (databasePath); }); } [TearDown] public virtual void TearDown () { ServiceContainer.Clear (); if (databasePath != null) { File.Delete (databasePath); databasePath = null; } } protected void RunAsync (Func<Task> fn) { fn ().GetAwaiter ().GetResult (); } protected MessageBus MessageBus { get { return ServiceContainer.Resolve<MessageBus> (); } } protected IDataStore DataStore { get { return ServiceContainer.Resolve<IDataStore> (); } } } }
bsd-3-clause
C#
09089a31260122e1385aa58acbdcbc6bb781731d
Fix potential nullref
peppy/osu,UselessToucan/osu,EVAST9919/osu,EVAST9919/osu,Damnae/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu,NeoAdonis/osu,naoey/osu,ppy/osu,naoey/osu,Frontear/osuKyzer,Drezi126/osu,2yangk23/osu,johnneijzen/osu,DrabWeb/osu,DrabWeb/osu,naoey/osu,smoogipoo/osu,2yangk23/osu,peppy/osu-new,ppy/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,ZLima12/osu,UselessToucan/osu,Nabile-Rahmani/osu
osu.Game/Input/Bindings/GlobalKeyBindingInputManager.cs
osu.Game/Input/Bindings/GlobalKeyBindingInputManager.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Input; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Input.Bindings; namespace osu.Game.Input.Bindings { public class GlobalKeyBindingInputManager : DatabasedKeyBindingInputManager<GlobalAction> { private readonly Drawable handler; public GlobalKeyBindingInputManager(OsuGameBase game) { if (game is IKeyBindingHandler<GlobalAction>) handler = game; } public override IEnumerable<KeyBinding> DefaultKeyBindings => new[] { new KeyBinding(Key.F8, GlobalAction.ToggleChat), new KeyBinding(Key.F9, GlobalAction.ToggleSocial), new KeyBinding(new[] { Key.LControl, Key.LAlt, Key.R }, GlobalAction.ResetInputSettings), new KeyBinding(new[] { Key.LControl, Key.T }, GlobalAction.ToggleToolbar), new KeyBinding(new[] { Key.LControl, Key.O }, GlobalAction.ToggleSettings), new KeyBinding(new[] { Key.LControl, Key.D }, GlobalAction.ToggleDirect), }; protected override IEnumerable<Drawable> GetKeyboardInputQueue() => handler == null ? base.GetKeyboardInputQueue() : new[] { handler }.Concat(base.GetKeyboardInputQueue()); } public enum GlobalAction { [Description("Toggle chat overlay")] ToggleChat, [Description("Toggle social overlay")] ToggleSocial, [Description("Reset input settings")] ResetInputSettings, [Description("Toggle toolbar")] ToggleToolbar, [Description("Toggle settings")] ToggleSettings, [Description("Toggle osu!direct")] ToggleDirect, } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Input; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Input.Bindings; namespace osu.Game.Input.Bindings { public class GlobalKeyBindingInputManager : DatabasedKeyBindingInputManager<GlobalAction> { private readonly Drawable handler; public GlobalKeyBindingInputManager(OsuGameBase game) { if (game is IKeyBindingHandler<GlobalAction>) handler = game; } public override IEnumerable<KeyBinding> DefaultKeyBindings => new[] { new KeyBinding(Key.F8, GlobalAction.ToggleChat), new KeyBinding(Key.F9, GlobalAction.ToggleSocial), new KeyBinding(new[] { Key.LControl, Key.LAlt, Key.R }, GlobalAction.ResetInputSettings), new KeyBinding(new[] { Key.LControl, Key.T }, GlobalAction.ToggleToolbar), new KeyBinding(new[] { Key.LControl, Key.O }, GlobalAction.ToggleSettings), new KeyBinding(new[] { Key.LControl, Key.D }, GlobalAction.ToggleDirect), }; protected override IEnumerable<Drawable> GetKeyboardInputQueue() => new[] { handler }.Concat(base.GetKeyboardInputQueue()); } public enum GlobalAction { [Description("Toggle chat overlay")] ToggleChat, [Description("Toggle social overlay")] ToggleSocial, [Description("Reset input settings")] ResetInputSettings, [Description("Toggle toolbar")] ToggleToolbar, [Description("Toggle settings")] ToggleSettings, [Description("Toggle osu!direct")] ToggleDirect, } }
mit
C#
9846b2bd525fde68ae6c8650a15b46838babf2c3
Fix issue #261
bobqian1130/PushSharp,kouweizhong/PushSharp,richardvaldivieso/PushSharp,codesharpdev/PushSharp,arleyandrada/PushSharp,volkd/PushSharp,rucila/PushSharp,richardvaldivieso/PushSharp,sumalla/PushSharp,profporridge/PushSharp,fhchina/PushSharp,sskodje/PushSharp,has-taiar/PushSharp.Web,agran/PushSharp,ingljo/PushSharp,ingljo/PushSharp,cafeburger/PushSharp,profporridge/PushSharp,SuPair/PushSharp,tianhang/PushSharp,rucila/PushSharp,FragCoder/PushSharp,arleyandrada/PushSharp,JeffCertain/PushSharp,cnbin/PushSharp,tianhang/PushSharp,rucila/PushSharp,cnbin/PushSharp,has-taiar/PushSharp.Web,FragCoder/PushSharp,yuejunwu/PushSharp,fhchina/PushSharp,ZanoMano/PushSharp,fanpan26/PushSharp,sskodje/PushSharp,codesharpdev/PushSharp,kouweizhong/PushSharp,SuPair/PushSharp,agran/PushSharp,mao1350848579/PushSharp,mao1350848579/PushSharp,JeffCertain/PushSharp,18098924759/PushSharp,bberak/PushSharp,ZanoMano/PushSharp,sumalla/PushSharp,codesharpdev/PushSharp,bobqian1130/PushSharp,JeffCertain/PushSharp,wanglj7525/PushSharp,chaoscope/PushSharp,rolltechrick/PushSharp,fanpan26/PushSharp,ZanoMano/PushSharp,fhchina/PushSharp,volkd/PushSharp,zoser0506/PushSharp,cafeburger/PushSharp,richardvaldivieso/PushSharp,chaoscope/PushSharp,kouweizhong/PushSharp,zoser0506/PushSharp,ingljo/PushSharp,zoser0506/PushSharp,sumalla/PushSharp,SuPair/PushSharp,18098924759/PushSharp,agran/PushSharp,tianhang/PushSharp,chaoscope/PushSharp,rolltechrick/PushSharp,cafeburger/PushSharp,wanglj7525/PushSharp,volkd/PushSharp,bberak/PushSharp,18098924759/PushSharp,yuejunwu/PushSharp,rolltechrick/PushSharp,FragCoder/PushSharp,sskodje/PushSharp,yuejunwu/PushSharp,cnbin/PushSharp,profporridge/PushSharp,fanpan26/PushSharp,bobqian1130/PushSharp,mao1350848579/PushSharp,wanglj7525/PushSharp
PushSharp.Blackberry/BlackberryPushChannelSettings.cs
PushSharp.Blackberry/BlackberryPushChannelSettings.cs
using PushSharp.Core; namespace PushSharp.Blackberry { public class BlackberryPushChannelSettings : IPushChannelSettings { public string ApplicationId { get; set; } public string Password { get; set; } public string Boundary { get { return "ASDFaslkdfjasfaSfdasfhpoiurwqrwm"; } } private const string SEND_URL = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest"; public BlackberryPushChannelSettings() { SendUrl = SEND_URL; } public BlackberryPushChannelSettings(string applicationId, string password) { ApplicationId = applicationId; Password = password; SendUrl = SEND_URL; } /// <summary> /// Push Proxy Gateway (PPG) Url is used for submitting push requests /// Default value is BIS PPG evaluation url /// https://pushapi.eval.blackberry.com/mss/PD_pushRequest /// </summary> public string SendUrl { get; private set; } /// <summary> /// Overrides SendUrl with any PPG url: BIS or BES /// </summary> /// <param name="url">Push Proxy Gateway (PPG) Url, /// For BIS,it's PPG production url is in format: http://cpxxx.pushapi.na.blackberry.com /// where xxx should be replaced with CPID (Content Provider ID)</param> public void OverrideSendUrl(string url) { if (!string.IsNullOrWhiteSpace(url)) { if (url.EndsWith("pushapi.na.blackberry.com", StringComparison.InvariantCultureIgnoreCase) || url.EndsWith("pushapi.eval.blackberry.com", StringComparison.InvariantCultureIgnoreCase)) url = url + @"/mss/PD_pushRequest"; } SendUrl = url; } } }
using PushSharp.Core; namespace PushSharp.Blackberry { public class BlackberryPushChannelSettings : IPushChannelSettings { public string ApplicationId { get; set; } public string Password { get; set; } public string Boundary { get { return "ASDFaslkdfjasfaSfdasfhpoiurwqrwm"; } } private const string SEND_URL = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest"; public BlackberryPushChannelSettings() { SendUrl = SEND_URL; } public BlackberryPushChannelSettings(string applicationId, string password) { ApplicationId = applicationId; Password = password; SendUrl = SEND_URL; } public string SendUrl { get; private set; } public void OverrideSendUrl(string url) { SendUrl = url; } } }
apache-2.0
C#
e387d0b2230bd4ad26b73cd4b8e0173babc50f1a
Update Forsendelse.cs
difi/sikker-digital-post-klient-dotnet
SikkerDigitalPost.Net.Domene/Entiteter/Forsendelse.cs
SikkerDigitalPost.Net.Domene/Entiteter/Forsendelse.cs
using System; namespace SikkerDigitalPost.Net.Domene.Entiteter { public class Forsendelse { /// <summary> /// Informasjon som brukes av postkasseleverandør for å behandle den digitale posten. /// </summary> public DigitalPost DigitalPost { get; set; } /// <summary> /// Pakke med hoveddokument og ev. vedlegg som skal sendes. /// </summary> public Dokumentpakke Dokumentpakke { get; set; } /// <summary> /// Ansvarlig avsender av forsendelsen. Dette vil i de aller fleste tilfeller være den offentlige virksomheten som er ansvarlig for brevet som skal sendes. /// </summary> public Behandlingsansvarlig Behandlingsansvarlig { get; set; } /// <summary> /// Unik ID opprettet og definert i en initiell melding og siden brukt i alle tilhørende kvitteringer knyttet til den opprinnelige meldingen. /// Skal være unik for en avsender. /// </summary> public readonly string KonversasjonsId = Guid.NewGuid().ToString(); /// <summary> /// Setter forsendelsens prioritet. Standard er Prioritet.Normal /// </summary> public Prioritet Prioritet = Prioritet.Normal; /// <summary> /// Språkkode i henhold til ISO-639-1 (2 bokstaver). /// Brukes til å informere postkassen om hvilket språk som benyttes, slik at varselet om mulig kan vises i riktig kontekst. /// /// Standard er NO. /// </summary> public string Språkkode = "NO"; /// <summary> /// Brukes til å skille mellom ulike kvitteringskøer for samme tekniske avsender. /// En forsendelse gjort med en MPC Id vil kun dukke opp i kvitteringskøen med samme MPC Id. /// /// Standardverdi er blank MPC Id. /// </summary> public string MpcId { get; set; } } }
using System; namespace SikkerDigitalPost.Net.Domene.Entiteter { public class Forsendelse { /// <summary> /// Informasjon som brukes av postkasseleverandør for å behandle den digitale posten. /// </summary> public DigitalPost DigitalPost { get; set; } /// <summary> /// Pakke med hoveddokument og ev. vedlegg som skal sendes. /// </summary> public Dokumentpakke Dokumentpakke { get; set; } /// <summary> /// Ansvarlig avsender av forsendelsen. Dette vil i de aller fleste tilfeller vøre den offentlige virksomheten som er ansvarlig for brevet som skal sendes. /// </summary> public Behandlingsansvarlig Behandlingsansvarlig { get; set; } /// <summary> /// Unik ID opprettet og definert i en initiell melding og siden brukt i alle tilhørende kvitteringer knyttet til den opprinnelige meldingen. /// Skal være unik for en avsender. /// </summary> public readonly string KonversasjonsId = Guid.NewGuid().ToString(); /// <summary> /// Setter forsendelsens prioritet. Standard er Prioritet.Normal /// </summary> public Prioritet Prioritet = Prioritet.Normal; /// <summary> /// Språkkode i henhold til ISO-639-1 (2 bokstaver). /// Brukes til å informere postkassen om hvilket språk som benyttes, slik at varselet om mulig kan vises i riktig kontekst. /// /// Standard er NO. /// </summary> public string Språkkode = "NO"; /// <summary> /// Brukes til å skille mellom ulike kvitteringskøer for samme tekniske avsender. /// En forsendelse gjort med en MPC Id vil kun dukke opp i kvitteringskøen med samme MPC Id. /// /// Standardverdi er blank MPC Id. /// </summary> public string MpcId { get; set; } } }
apache-2.0
C#
0ea3fc780752f7ffa2cc7fa765f1b90a0606905d
put dev tools to othe right group
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Shell/MainMenu/ToolsMainMenuItems.cs
WalletWasabi.Gui/Shell/MainMenu/ToolsMainMenuItems.cs
using AvalonStudio.MainMenu; using AvalonStudio.Menus; using System; using System.Collections.Generic; using System.Composition; using System.Text; namespace WalletWasabi.Gui.Shell.MainMenu { internal class ToolsMainMenuItems { private IMenuItemFactory MenuItemFactory { get; } [ImportingConstructor] public ToolsMainMenuItems(IMenuItemFactory menuItemFactory) { MenuItemFactory = menuItemFactory; } #region MainMenu [ExportMainMenuItem("Tools")] [DefaultOrder(1)] public IMenuItem Tools => MenuItemFactory.CreateHeaderMenuItem("Tools", null); #endregion MainMenu #region Group [ExportMainMenuDefaultGroup("Tools", "Utilities")] [DefaultOrder(0)] public object UtilitiesGroup => null; [ExportMainMenuDefaultGroup("Tools", "Settings")] [DefaultOrder(10)] public object SettingsGroup => null; #endregion Group #region MenuItem [ExportMainMenuItem("Tools", "Wallet Manager")] [DefaultOrder(1)] [DefaultGroup("Utilities")] public IMenuItem WalletManager => MenuItemFactory.CreateCommandMenuItem("Tools.WalletManager"); #if DEBUG [ExportMainMenuItem("Tools", "Dev Tools")] [DefaultOrder(10)] [DefaultGroup("Utilities")] public IMenuItem DevTools => MenuItemFactory.CreateCommandMenuItem("Tools.DevTools"); #endif [ExportMainMenuItem("Tools", "Transaction Broadcaster")] [DefaultOrder(2)] [DefaultGroup("Utilities")] public IMenuItem BroadcastTransaction => MenuItemFactory.CreateCommandMenuItem("Tools.BroadcastTransaction"); [ExportMainMenuItem("Tools", "Settings")] [DefaultOrder(20)] [DefaultGroup("Settings")] public IMenuItem Settings => MenuItemFactory.CreateCommandMenuItem("Tools.Settings"); #endregion MenuItem } }
using AvalonStudio.MainMenu; using AvalonStudio.Menus; using System; using System.Collections.Generic; using System.Composition; using System.Text; namespace WalletWasabi.Gui.Shell.MainMenu { internal class ToolsMainMenuItems { private IMenuItemFactory MenuItemFactory { get; } [ImportingConstructor] public ToolsMainMenuItems(IMenuItemFactory menuItemFactory) { MenuItemFactory = menuItemFactory; } #region MainMenu [ExportMainMenuItem("Tools")] [DefaultOrder(1)] public IMenuItem Tools => MenuItemFactory.CreateHeaderMenuItem("Tools", null); #endregion MainMenu #region Group [ExportMainMenuDefaultGroup("Tools", "Utilities")] [DefaultOrder(0)] public object UtilitiesGroup => null; [ExportMainMenuDefaultGroup("Tools", "Settings")] [DefaultOrder(10)] public object SettingsGroup => null; #endregion Group #region MenuItem [ExportMainMenuItem("Tools", "Wallet Manager")] [DefaultOrder(1)] [DefaultGroup("Utilities")] public IMenuItem WalletManager => MenuItemFactory.CreateCommandMenuItem("Tools.WalletManager"); #if DEBUG [ExportMainMenuItem("Tools", "Dev Tools")] [DefaultOrder(10)] [DefaultGroup("Managers")] public IMenuItem DevTools => MenuItemFactory.CreateCommandMenuItem("Tools.DevTools"); #endif [ExportMainMenuItem("Tools", "Transaction Broadcaster")] [DefaultOrder(2)] [DefaultGroup("Utilities")] public IMenuItem BroadcastTransaction => MenuItemFactory.CreateCommandMenuItem("Tools.BroadcastTransaction"); [ExportMainMenuItem("Tools", "Settings")] [DefaultOrder(20)] [DefaultGroup("Settings")] public IMenuItem Settings => MenuItemFactory.CreateCommandMenuItem("Tools.Settings"); #endregion MenuItem } }
mit
C#
b1228304da8bd11c42993f395c78b23501286f36
Add a test for multiple directory watchers
DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
tests/OmniSharp.Roslyn.CSharp.Tests/FilesChangedFacts.cs
tests/OmniSharp.Roslyn.CSharp.Tests/FilesChangedFacts.cs
using System.IO; using System.Linq; using System.Threading.Tasks; using OmniSharp.FileWatching; using OmniSharp.Models.FilesChanged; using OmniSharp.Roslyn.CSharp.Services.Files; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Roslyn.CSharp.Tests { public class OnFilesChangedFacts : AbstractSingleRequestHandlerTestFixture<OnFilesChangedService> { public OnFilesChangedFacts(ITestOutputHelper testOutput) : base(testOutput) { } protected override string EndpointName => OmniSharpEndpoints.FilesChanged; [Fact] public async Task TestFileAddedToMSBuildWorkspaceOnCreation() { using (var testProject = await TestAssets.Instance.GetTestProjectAsync("ProjectAndSolution")) using (var host = CreateOmniSharpHost(testProject.Directory)) { var watcher = host.GetExport<IFileSystemWatcher>(); var path = Path.GetDirectoryName(host.Workspace.CurrentSolution.Projects.First().FilePath); var filePath = Path.Combine(path, "FileName.cs"); File.WriteAllText(filePath, "text"); var handler = GetRequestHandler(host); await handler.Handle(new[] { new FilesChangedRequest() { FileName = filePath, ChangeType = FileChangeType.Create } }); Assert.Contains(host.Workspace.CurrentSolution.Projects.First().Documents, d => d.Name == filePath); } } [Fact] public void TestMultipleDirectoryWatchers() { using (var host = CreateEmptyOmniSharpHost()) { var watcher = host.GetExport<IFileSystemWatcher>(); bool firstWatcherCalled = false; bool secondWatcherCalled = false; watcher.WatchDirectory("", (path, changeType) => { firstWatcherCalled = true; }); watcher.WatchDirectory("", (path, changeType) => { secondWatcherCalled = true; }); var handler = GetRequestHandler(host); handler.Handle(new[] { new FilesChangedRequest() { FileName = "FileName.cs", ChangeType = FileChangeType.Create } }); Assert.True(firstWatcherCalled); Assert.True(secondWatcherCalled); } } } }
using OmniSharp.FileWatching; using OmniSharp.Models.FilesChanged; using OmniSharp.Roslyn.CSharp.Services.Files; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Roslyn.CSharp.Tests { public class OnFilesChangedFacts : AbstractSingleRequestHandlerTestFixture<OnFilesChangedService> { public OnFilesChangedFacts(ITestOutputHelper testOutput) : base(testOutput) { } protected override string EndpointName => OmniSharpEndpoints.FilesChanged; [Fact] public void TestFileWatcherCalled() { using (var host = CreateEmptyOmniSharpHost()) { var watcher = host.GetExport<IFileSystemWatcher>(); string filePath = null; FileChangeType? ct = null; watcher.WatchDirectory("", (path, changeType) => { filePath = path; ct = changeType; }); var handler = GetRequestHandler(host); handler.Handle(new[] { new FilesChangedRequest() { FileName = "FileName.cs", ChangeType = FileChangeType.Create } }); Assert.Equal("FileName.cs", filePath); Assert.Equal(FileChangeType.Create, ct); } } } }
mit
C#
c8c0aafcb1e3b43ab16fa2f62b7d024496923011
Simplify Login() action - no explicit return necessary
GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet
aspnet/4-auth/Controllers/SessionController.cs
aspnet/4-auth/Controllers/SessionController.cs
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public void Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public ActionResult Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
apache-2.0
C#
a5584802f31007da2992dae445ffe69c36966ffd
Update Globals.cs
Selz/SiftScienceNet
src/SiftScienceNet/Globals.cs
src/SiftScienceNet/Globals.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SiftScienceNet { public class Globals { public const string Authority = "https://api.siftscience.com"; public const string EventsEndpoint = Authority + "/v204/events"; public const string EventsWithScoreEndpoint = EventsEndpoint + "?return_action=true"; public const string LabelsEndpoint = Authority + "/v204/users/{0}/labels"; public const string ScoresEndpoint = Authority + "/v204/score/{0}/?api_key={1}"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SiftScienceNet { public class Globals { public const string Authority = "https://api.siftscience.com"; public const string EventsEndpoint = Authority + "/v203/events"; public const string EventsWithScoreEndpoint = EventsEndpoint + "?return_action=true"; public const string LabelsEndpoint = Authority + "/v203/users/{0}/labels"; public const string ScoresEndpoint = Authority + "/v203/score/{0}/?api_key={1}"; } }
mit
C#
bc111a37f9980ff8c37ae783b184263f572cbafa
Update Music.cs
wanddy/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,wanddy/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,down4u/WeiXinMPSDK,JeffreySu/WxOpen,down4u/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,JeffreySu/WxOpen,JeffreySu/WeiXinMPSDK,lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK
Senparc.Weixin.MP/Senparc.Weixin.MP/Entities/Response/Music.cs
Senparc.Weixin.MP/Senparc.Weixin.MP/Entities/Response/Music.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Senparc.Weixin.MP.Entities { public class Music { public string Title { get; set; } public string Description { get; set; } public string MusicUrl { get; set; } public string HQMusicUrl { get; set; } ///// <summary> ///// 缩略图的媒体id,通过上传多媒体文件,得到的id ///// 官方API上有,但是加入的话会出错 ///// </summary> public string ThumbMediaId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Senparc.Weixin.MP.Entities { public class Music { public string Title { get; set; } public string Description { get; set; } public string MusicUrl { get; set; } public string HQMusicUrl { get; set; } ///// <summary> ///// 缩略图的媒体id,通过上传多媒体文件,得到的id ///// 官方API上有,但是加入的话会出错 ///// </summary> //public string ThumbMediaId { get; set; } } }
apache-2.0
C#
77b8a843a4343b7f34ace1af2fec5bccf89a2796
add more UrlSegment tests
NebulousConcept/b2-csharp-client
b2-csharp-client-test/B2.Client/UrlSegmentTest.cs
b2-csharp-client-test/B2.Client/UrlSegmentTest.cs
using B2.Client.Rest; using B2.Client.Rest.Request.Param; using NUnit.Framework; namespace B2.Client.Test { [TestFixture] public class UrlSegmentTest { [Test] public void TestLiteralSegmentDoesNotTransform() { const string paramName = "paramName"; const string paramValue = "paramValue"; var param = new RestParam(paramName, paramValue); var segment = UrlSegment.Literal(paramName); Assert.That(segment.Transform(param.Yield()), Is.EqualTo(paramName)); } [Test] public void TestLiteralSegmentDoesNotThrow() { const string paramName = "paramName"; const string paramValue = "paramValue"; const string segmentName = "segmentName"; var param = new RestParam(paramName, paramValue); var segment = UrlSegment.Literal(segmentName); //check that passing in parameters where none match is okay Assert.That(segment.Transform(param.Yield()), Is.EqualTo(segmentName)); var conflictingParam = new RestParam(segmentName, paramValue); //check that multiple matching params are okay Assert.That(segment.Transform(conflictingParam.ConcatWith(conflictingParam)), Is.EqualTo(segmentName)); } [Test] public void TestParameterSegmentDoesTransform() { const string paramName = "paramName"; const string paramValue = "paramValue"; var param = new RestParam(paramName, paramValue); var segment = UrlSegment.Parameter(paramName); Assert.That(segment.Transform(param.Yield()), Is.EqualTo(paramValue)); } [Test] public void TestParameterSegmentWithNoMatchThrows() { const string paramName = "paramName"; const string paramValue = "paramValue"; const string segmentName = "segmentName"; var param = new RestParam(paramName, paramValue); var segment = UrlSegment.Parameter(segmentName); Assert.That(() => segment.Transform(param.Yield()), Throws.InvalidOperationException); } [Test] public void TestParameterSegmentWithMultipleMatchesThrows() { const string paramName = "paramName"; const string paramValue = "paramValue"; var param = new RestParam(paramName, paramValue); var segment = UrlSegment.Parameter(paramName); Assert.That(() => segment.Transform(param.ConcatWith(param)), Throws.InvalidOperationException); } } }
using B2.Client.Rest; using B2.Client.Rest.Request.Param; using NUnit.Framework; namespace B2.Client.Test { [TestFixture] public class UrlSegmentTest { [Test] public void TestLiteralSegmentDoesNotTransform() { const string paramName = "paramName"; const string paramValue = "paramValue"; var param = new RestParam(paramName, paramValue); var segment = UrlSegment.Literal(paramName); Assert.That(segment.Transform(param.Yield()), Is.EqualTo(paramName)); } [Test] public void TestParameterSegmentDoesTransform() { const string paramName = "paramName"; const string paramValue = "paramValue"; var param = new RestParam(paramName, paramValue); var segment = UrlSegment.Parameter(paramName); Assert.That(segment.Transform(param.Yield()), Is.EqualTo(paramValue)); } } }
mit
C#
44b43c1fc50525d5c0c22e1ed9346892f2905d5f
use ReadNil
pocketberserker/MessagePack.FSharpExtensions
src/MessagePack.FSharpExtensions/Formatters/UnitFormatter.cs
src/MessagePack.FSharpExtensions/Formatters/UnitFormatter.cs
using System; using MessagePack.Formatters; using Microsoft.FSharp.Core; namespace MessagePack.FSharp.Formatters { public class UnitFormatter : IMessagePackFormatter<Unit> { public UnitFormatter() { } public int Serialize(ref byte[] bytes, int offset, Unit value, IFormatterResolver formatterResolver) { return MessagePackBinary.WriteNil(ref bytes, offset); } public Unit Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize) { MessagePackBinary.ReadNil(bytes, offset, out readSize); return null; } } }
using System; using MessagePack.Formatters; using Microsoft.FSharp.Core; namespace MessagePack.FSharp.Formatters { public class UnitFormatter : IMessagePackFormatter<Unit> { public UnitFormatter() { } public int Serialize(ref byte[] bytes, int offset, Unit value, IFormatterResolver formatterResolver) { return MessagePackBinary.WriteNil(ref bytes, offset); } public Unit Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize) { if (MessagePackBinary.IsNil(bytes, offset)) { readSize = 1; return null; } else { throw new Exception("expected nil, but was other type."); } } } }
mit
C#
1e7de9baa224e6ccc8b632e16ab470981398991f
Update XPathGeometryTypeConverter.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Serializer.Xaml/Converters/XPathGeometryTypeConverter.cs
src/Serializer.Xaml/Converters/XPathGeometryTypeConverter.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; #if NETSTANDARD1_3 using System.ComponentModel; #else using Portable.Xaml.ComponentModel; #endif using Core2D.Path; using Core2D.Path.Parser; namespace Serializer.Xaml.Converters { /// <summary> /// Defines <see cref="XPathGeometry"/> type converter. /// </summary> internal class XPathGeometryTypeConverter : TypeConverter { /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } /// <inheritdoc/> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return false; // destinationType == typeof(string); } /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return XPathGeometryParser.Parse((string)value); } /// <inheritdoc/> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { return value is XPathGeometry geometry ? geometry.ToString() : throw new NotSupportedException(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; #if NETSTANDARD1_3 using System.ComponentModel; #else using Portable.Xaml.ComponentModel; #endif using Core2D.Path; using Core2D.Path.Parser; namespace Serializer.Xaml.Converters { /// <summary> /// Defines <see cref="XPathGeometry"/> type converter. /// </summary> internal class XPathGeometryTypeConverter : TypeConverter { /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } /// <inheritdoc/> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return XPathGeometryParser.Parse((string)value); } /// <inheritdoc/> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { return value is XPathGeometry geometry ? geometry.ToString() : throw new NotSupportedException(); } } }
mit
C#
0169f07c75ac66bcd45a5d2e7e0a0775ef401bdd
Update nuget package
KKings/Sitecore.ContentSearch.Fluent
src/Sitecore.ContentSearch.Fluent/Properties/AssemblyInfo.cs
src/Sitecore.ContentSearch.Fluent/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sitecore.ContentSearch.Fluent")] [assembly: AssemblyDescription("Fluent API for Sitecore Content Search API")] [assembly: AssemblyCompany("Kyle Kingsbury")] [assembly: AssemblyProduct("Sitecore.ContentSearch.Fluent")] [assembly: AssemblyCopyright("Copyright © Kyle Kingsbury 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("244e617d-9f82-43ca-8648-6dc8377b93e4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.21")] [assembly: AssemblyFileVersion("1.0.3.21")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sitecore.ContentSearch.Fluent")] [assembly: AssemblyDescription("Fluent API for Sitecore Content Search API")] [assembly: AssemblyCompany("Kyle Kingsbury")] [assembly: AssemblyProduct("Sitecore.ContentSearch.Fluent")] [assembly: AssemblyCopyright("Copyright © Kyle Kingsbury 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("244e617d-9f82-43ca-8648-6dc8377b93e4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.20")] [assembly: AssemblyFileVersion("1.0.3.20")]
mit
C#
a9c4bf331b69560dce13f9052841fdcccebf5458
Make text buffer read-only
terrajobst/nquery-vnext
NQueryViewer/EditorIntegration/NQuerySyntaxTreeManager.cs
NQueryViewer/EditorIntegration/NQuerySyntaxTreeManager.cs
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using NQuery.Language; namespace NQueryViewer.EditorIntegration { internal sealed class NQuerySyntaxTreeManager : INQuerySyntaxTreeManager { private readonly ITextBuffer _textBuffer; private SyntaxTree _syntaxTree; private CancellationTokenSource _cancellationTokenSource; public NQuerySyntaxTreeManager(ITextBuffer textBuffer) { _textBuffer = textBuffer; _textBuffer.PostChanged += TextBufferOnPostChanged; QueueParseRequest(); } public SyntaxTree SyntaxTree { get { return _syntaxTree; } private set { if (_syntaxTree != value) { _syntaxTree = value; OnSyntaxTreeChanged(EventArgs.Empty); } } } private void TextBufferOnPostChanged(object sender, EventArgs e) { QueueParseRequest(); } private void QueueParseRequest() { var snapshot = _textBuffer.CurrentSnapshot; if (_cancellationTokenSource != null) _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; var sc = SynchronizationContext.Current; Task.Factory .StartNew(() => SyntaxTree.ParseQuery(snapshot.GetText()), cancellationToken) .ContinueWith(t => sc.Post(s => { if (_textBuffer.CurrentSnapshot == snapshot) SyntaxTree = t.Result; }, null), TaskContinuationOptions.NotOnCanceled); } private void OnSyntaxTreeChanged(EventArgs e) { var handler = SyntaxTreeChanged; if (handler != null) handler(this, e); } public event EventHandler<EventArgs> SyntaxTreeChanged; } }
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using NQuery.Language; namespace NQueryViewer.EditorIntegration { internal sealed class NQuerySyntaxTreeManager : INQuerySyntaxTreeManager { private ITextBuffer _textBuffer; private SyntaxTree _syntaxTree; private CancellationTokenSource _cancellationTokenSource; public NQuerySyntaxTreeManager(ITextBuffer textBuffer) { _textBuffer = textBuffer; _textBuffer.PostChanged += TextBufferOnPostChanged; QueueParseRequest(); } public SyntaxTree SyntaxTree { get { return _syntaxTree; } private set { if (_syntaxTree != value) { _syntaxTree = value; OnSyntaxTreeChanged(EventArgs.Empty); } } } private void TextBufferOnPostChanged(object sender, EventArgs e) { QueueParseRequest(); } private void QueueParseRequest() { var snapshot = _textBuffer.CurrentSnapshot; if (_cancellationTokenSource != null) _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; var sc = SynchronizationContext.Current; Task.Factory .StartNew(() => SyntaxTree.ParseQuery(snapshot.GetText()), cancellationToken) .ContinueWith(t => sc.Post(s => { if (_textBuffer.CurrentSnapshot == snapshot) SyntaxTree = t.Result; }, null), TaskContinuationOptions.NotOnCanceled); } private void OnSyntaxTreeChanged(EventArgs e) { var handler = SyntaxTreeChanged; if (handler != null) handler(this, e); } public event EventHandler<EventArgs> SyntaxTreeChanged; } }
mit
C#
d811986292dd0f22cb4276ae4ac72b2bd1e576b4
fix issue with loading media content from a group
codehollow/FeedReader
FeedReader/Feeds/MediaRSS/MediaGroup.cs
FeedReader/Feeds/MediaRSS/MediaGroup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace CodeHollow.FeedReader.Feeds.MediaRSS { /// <summary> /// A collection of media that are effectively the same content, yet different representations. For isntance: the same song recorded in both WAV and MP3 format. /// </summary> public class MediaGroup { /// <summary> /// Initializes a new instance of the <see cref="MediaGroup"/> class. /// Reads a rss media group item enclosure based on the xml given in element /// </summary> /// <param name="element">enclosure element as xml</param> public MediaGroup (XElement element) { var media = element.GetElements("media", "content"); this.Media = media.Select(x => new Media(x)).ToList(); } /// <summary> /// Media object /// </summary> public ICollection<Media> Media { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace CodeHollow.FeedReader.Feeds.MediaRSS { /// <summary> /// A collection of media that are effectively the same content, yet different representations. For isntance: the same song recorded in both WAV and MP3 format. /// </summary> public class MediaGroup { /// <summary> /// Initializes a new instance of the <see cref="MediaGroup"/> class. /// Reads a rss media group item enclosure based on the xml given in element /// </summary> /// <param name="element">enclosure element as xml</param> public MediaGroup (XElement element) { var media = element.GetElements("media", "contents"); this.Media = media.Select(x => new Media(x)).ToList(); } /// <summary> /// Media object /// </summary> public ICollection<Media> Media { get; set; } } }
mit
C#
d322b7ebfd98468258baf25e4c6257da28502e52
remove unnecessary usings
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
src/AtomicChessPuzzles/Controllers/ReviewController.cs
src/AtomicChessPuzzles/Controllers/ReviewController.cs
using AtomicChessPuzzles.DbRepositories; using AtomicChessPuzzles.Models; using Microsoft.AspNet.Mvc; using System.Collections.Generic; namespace AtomicChessPuzzles.Controllers { public class ReviewController : Controller { IPuzzleRepository puzzleRepository; public ReviewController(IPuzzleRepository _puzzleRepository) { puzzleRepository = _puzzleRepository; } [Route("/Review")] public IActionResult Index() { List<Puzzle> inReview = puzzleRepository.InReview(); return View(inReview); } [HttpPost] [Route("/Review/Approve/{id}")] public IActionResult Approve(string id) { if (puzzleRepository.Approve(id)) { return Json(new { success = true }); } else { return Json(new { success = false, error = "Approval failed." }); } } [HttpPost] [Route("/Review/Reject/{id}")] public IActionResult Reject(string id) { if (puzzleRepository.Reject(id)) { return Json(new { success = true }); } else { return Json(new { success = false, error = "Rejection failed." }); } } } }
using AtomicChessPuzzles.DbRepositories; using AtomicChessPuzzles.MemoryRepositories; using AtomicChessPuzzles.Models; using ChessDotNet; using ChessDotNet.Variants.Atomic; using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace AtomicChessPuzzles.Controllers { public class ReviewController : Controller { IPuzzleRepository puzzleRepository; public ReviewController(IPuzzleRepository _puzzleRepository) { puzzleRepository = _puzzleRepository; } [Route("/Review")] public IActionResult Index() { List<Puzzle> inReview = puzzleRepository.InReview(); return View(inReview); } [HttpPost] [Route("/Review/Approve/{id}")] public IActionResult Approve(string id) { if (puzzleRepository.Approve(id)) { return Json(new { success = true }); } else { return Json(new { success = false, error = "Approval failed." }); } } [HttpPost] [Route("/Review/Reject/{id}")] public IActionResult Reject(string id) { if (puzzleRepository.Reject(id)) { return Json(new { success = true }); } else { return Json(new { success = false, error = "Rejection failed." }); } } } }
agpl-3.0
C#
e1a3ddc4273ed4cd42e6026dad2e9fdb5877c546
add jittergridsampler
brendan-rius/raytracer-epitech
raytracer/raytracer/samplers/GridSampler.cs
raytracer/raytracer/samplers/GridSampler.cs
using System; using System.Collections.Generic; namespace raytracer.samplers { /// <summary> /// A grid sampler generate one ray for each "pixel" on the screen. It is the simplest /// sampler, but it can lead to aliasing. /// A grid sampler have to know the size of the screen to be used /// <seealso cref="Sample" /> /// <seealso cref="Screen" /> /// </summary> public class GridSampler : Sampler { /// <summary> /// The screen used to generate the samples /// </summary> protected Screen Screen; /// <summary> /// Create the sampler from a screen. /// <seealso cref="Screen" /> /// </summary> /// <param name="screen"></param> public GridSampler(Screen screen) { Screen = screen; } public override IEnumerable<Sample> Samples() { for (var y = 0.5f; y < Screen.y; ++y) { for (var x = 0.5f; x < Screen.x; ++x) { yield return new Sample(x, y); } } } } /// <summary> /// A jitter grid sampler create a random sample for each "pixel", (not at the center /// as a simple <seealso cref="GridSampler" /> would do. Thus, we can generate /// many sample for the same pixel, improving the render. /// </summary> internal class JitterGridSampler : GridSampler { private readonly Random RNG; /// <summary> /// Creates a new sampler /// </summary> /// <param name="screen">the screen for the grid sampler</param> /// <param name="rng">a random number generator. If null, this class will create one</param> public JitterGridSampler(Screen screen, Random rng = null) : base(screen) { RNG = rng ?? new Random(); } public override IEnumerable<Sample> Samples() { for (var y = 0f; y < Screen.y; ++y) { for (var x = 0f; x < Screen.x; ++x) { yield return new Sample((float) RNG.NextDouble(), (float) RNG.NextDouble()); } } } } }
using System.Collections.Generic; namespace raytracer.samplers { /// <summary> /// A grid sampler generate one ray for each "pixel" on the screen. It is the simplest /// sampler, but it can lead to aliasing. /// A grid sampler have to know the size of the screen to be used /// <seealso cref="Sample" /> /// <seealso cref="Screen" /> /// </summary> public class GridSampler : Sampler { /// <summary> /// The screen used to generate the samples /// </summary> private Screen Screen; /// <summary> /// Create the sampler from a screen. /// <seealso cref="Screen" /> /// </summary> /// <param name="screen"></param> public GridSampler(Screen screen) { Screen = screen; } public override IEnumerable<Sample> Samples() { for (var y = 0.5f; y < Screen.y; ++y) { for (var x = 0.5f; x < Screen.x; ++x) { yield return new Sample(x, y); } } } } }
mit
C#
99f17d4b353e83a34e869b82825cb01941dbc445
Make data + metadata proper JSON for postgres
damianh/SqlStreamStore,danbarua/Cedar.EventStore,damianh/Cedar.EventStore,SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore
src/Cedar.EventStore.Tests/EventStoreAcceptanceTests.cs
src/Cedar.EventStore.Tests/EventStoreAcceptanceTests.cs
namespace Cedar.EventStore { using System; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Xunit.Abstractions; public abstract partial class EventStoreAcceptanceTests { private readonly ITestOutputHelper _testOutputHelper; protected abstract EventStoreAcceptanceTestFixture GetFixture(); protected EventStoreAcceptanceTests(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Fact] public async Task When_dispose_and_read_then_should_throw() { using(var fixture = GetFixture()) { var store = await fixture.GetEventStore(); store.Dispose(); Func<Task> act = () => store.ReadAll(Checkpoint.Start, 10); act.ShouldThrow<ObjectDisposedException>(); } } [Fact] public async Task Can_dispose_more_than_once() { using (var fixture = GetFixture()) { var store = await fixture.GetEventStore(); store.Dispose(); Action act = store.Dispose; act.ShouldNotThrow(); } } private static NewStreamEvent[] CreateNewStreamEvents(params int[] eventNumbers) { return eventNumbers .Select(eventNumber => { var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0')); return new NewStreamEvent(eventId, "type", "\"data\"", "\"metadata\""); }) .ToArray(); } private static StreamEvent ExpectedStreamEvent( string streamId, int eventNumber, int sequenceNumber, DateTime created) { var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0')); return new StreamEvent(streamId, eventId, sequenceNumber, null, created, "type", "\"data\"", "\"metadata\""); } } }
namespace Cedar.EventStore { using System; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Xunit.Abstractions; public abstract partial class EventStoreAcceptanceTests { private readonly ITestOutputHelper _testOutputHelper; protected abstract EventStoreAcceptanceTestFixture GetFixture(); protected EventStoreAcceptanceTests(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Fact] public async Task When_dispose_and_read_then_should_throw() { using(var fixture = GetFixture()) { var store = await fixture.GetEventStore(); store.Dispose(); Func<Task> act = () => store.ReadAll(Checkpoint.Start, 10); act.ShouldThrow<ObjectDisposedException>(); } } [Fact] public async Task Can_dispose_more_than_once() { using (var fixture = GetFixture()) { var store = await fixture.GetEventStore(); store.Dispose(); Action act = store.Dispose; act.ShouldNotThrow(); } } private static NewStreamEvent[] CreateNewStreamEvents(params int[] eventNumbers) { return eventNumbers .Select(eventNumber => { var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0')); return new NewStreamEvent(eventId, "type", "data", "metadata"); }) .ToArray(); } private static StreamEvent ExpectedStreamEvent( string streamId, int eventNumber, int sequenceNumber, DateTime created) { var eventId = Guid.Parse("00000000-0000-0000-0000-" + eventNumber.ToString().PadLeft(12, '0')); return new StreamEvent(streamId, eventId, sequenceNumber, null, created, "type", "data", "metadata"); } } }
mit
C#
33d516eecb0b11541c733de1797b9706c8c69763
Move guest participation beatmap up to below loved
ppy/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game/Overlays/Profile/Sections/BeatmapsSection.cs
osu.Game/Overlays/Profile/Sections/BeatmapsSection.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Localisation; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Profile.Sections.Beatmaps; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.Profile.Sections { public class BeatmapsSection : ProfileSection { public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle; public override string Identifier => @"beatmaps"; public BeatmapsSection() { Children = new[] { new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle), new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, UsersStrings.ShowExtraBeatmapsGuestTitle), new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle), new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle) }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Localisation; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Profile.Sections.Beatmaps; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.Profile.Sections { public class BeatmapsSection : ProfileSection { public override LocalisableString Title => UsersStrings.ShowExtraBeatmapsTitle; public override string Identifier => @"beatmaps"; public BeatmapsSection() { Children = new[] { new PaginatedBeatmapContainer(BeatmapSetType.Favourite, User, UsersStrings.ShowExtraBeatmapsFavouriteTitle), new PaginatedBeatmapContainer(BeatmapSetType.Ranked, User, UsersStrings.ShowExtraBeatmapsRankedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Loved, User, UsersStrings.ShowExtraBeatmapsLovedTitle), new PaginatedBeatmapContainer(BeatmapSetType.Pending, User, UsersStrings.ShowExtraBeatmapsPendingTitle), new PaginatedBeatmapContainer(BeatmapSetType.Guest, User, UsersStrings.ShowExtraBeatmapsGuestTitle), new PaginatedBeatmapContainer(BeatmapSetType.Graveyard, User, UsersStrings.ShowExtraBeatmapsGraveyardTitle) }; } } }
mit
C#
4084308e1bf05a8cc35d92924675ace2da7776bf
set JsonEncodeValue to default for MultipleFileUploadEditorAttribute
volkanceylan/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity
Serenity.Core/ComponentModel/Upload/MultipleFileUploadEditorAttribute.cs
Serenity.Core/ComponentModel/Upload/MultipleFileUploadEditorAttribute.cs
namespace Serenity.ComponentModel { public class MultipleFileUploadEditorAttribute : ImageUploadEditorAttribute { public MultipleFileUploadEditorAttribute() : base("MultipleImageUpload") { AllowNonImage = true; JsonEncodeValue = true;. } } }
namespace Serenity.ComponentModel { public class MultipleFileUploadEditorAttribute : ImageUploadEditorAttribute { public MultipleFileUploadEditorAttribute() : base("MultipleImageUpload") { AllowNonImage = true; } } }
mit
C#
66c95b5005ef02a7e2a9fc6d8cea8cd56296b99d
Allow to run build even if git repo informations are not available
Abc-Arbitrage/Zebus.Persistence,Abc-Arbitrage/Zebus
build/scripts/utilities.cake
build/scripts/utilities.cake
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); try { _versionContext.Git = GitVersion(); } catch { _versionContext.Git = new Cake.Common.Tools.GitVersion.GitVersion(); } return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
#tool "nuget:?package=GitVersion.CommandLine" #addin "Cake.Yaml" public class ContextInfo { public string NugetVersion { get; set; } public string AssemblyVersion { get; set; } public GitVersion Git { get; set; } public string BuildVersion { get { return NugetVersion + "-" + Git.Sha; } } } ContextInfo _versionContext = null; public ContextInfo VersionContext { get { if(_versionContext == null) throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property."); return _versionContext; } } public ContextInfo ReadContext(FilePath filepath) { _versionContext = DeserializeYamlFromFile<ContextInfo>(filepath); _versionContext.Git = GitVersion(); return _versionContext; } public void UpdateAppVeyorBuildVersionNumber() { var increment = 0; while(increment < 10) { try { var version = VersionContext.BuildVersion; if(increment > 0) version += "-" + increment; AppVeyor.UpdateBuildVersion(version); break; } catch { increment++; } } }
mit
C#
3405dc8d484442867940043f724807aa4ef4a652
Switch to version 1.3.7
biarne-a/Zebus,AtwooTM/Zebus,Abc-Arbitrage/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.3.7")] [assembly: AssemblyFileVersion("1.3.7")] [assembly: AssemblyInformationalVersion("1.3.7")]
using System.Reflection; [assembly: AssemblyVersion("1.3.6")] [assembly: AssemblyFileVersion("1.3.6")] [assembly: AssemblyInformationalVersion("1.3.6")]
mit
C#
6f577972e2f78c6e6434ba31d44bc87489200d77
include source-generated documents in inheritance-margin call
mavasani/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,bartdesmet/roslyn
src/Workspaces/Remote/ServiceHub/Services/InheritanceMargin/RemoteInheritanceMarginService.cs
src/Workspaces/Remote/ServiceHub/Services/InheritanceMargin/RemoteInheritanceMarginService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteInheritanceMarginService : BrokeredServiceBase, IRemoteInheritanceMarginService { internal sealed class Factory : FactoryBase<IRemoteInheritanceMarginService> { protected override IRemoteInheritanceMarginService CreateService(in ServiceConstructionArguments arguments) { return new RemoteInheritanceMarginService(arguments); } } public RemoteInheritanceMarginService(in ServiceConstructionArguments arguments) : base(in arguments) { } public ValueTask<ImmutableArray<InheritanceMarginItem>> GetInheritanceMarginItemsAsync( Checksum solutionChecksum, DocumentId documentId, TextSpan spanToSearch, bool includeGlobalImports, bool frozenPartialSemantics, CancellationToken cancellationToken) { return RunServiceAsync(solutionChecksum, async solution => { var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var service = document.GetRequiredLanguageService<IInheritanceMarginService>(); return await service.GetInheritanceMemberItemsAsync(document, spanToSearch, includeGlobalImports, frozenPartialSemantics, cancellationToken).ConfigureAwait(false); }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteInheritanceMarginService : BrokeredServiceBase, IRemoteInheritanceMarginService { internal sealed class Factory : FactoryBase<IRemoteInheritanceMarginService> { protected override IRemoteInheritanceMarginService CreateService(in ServiceConstructionArguments arguments) { return new RemoteInheritanceMarginService(arguments); } } public RemoteInheritanceMarginService(in ServiceConstructionArguments arguments) : base(in arguments) { } public ValueTask<ImmutableArray<InheritanceMarginItem>> GetInheritanceMarginItemsAsync( Checksum solutionChecksum, DocumentId documentId, TextSpan spanToSearch, bool includeGlobalImports, bool frozenPartialSemantics, CancellationToken cancellationToken) { return RunServiceAsync(solutionChecksum, solution => { var document = solution.GetRequiredDocument(documentId); var service = document.GetRequiredLanguageService<IInheritanceMarginService>(); return service.GetInheritanceMemberItemsAsync(document, spanToSearch, includeGlobalImports, frozenPartialSemantics, cancellationToken); }, cancellationToken); } } }
mit
C#
038f92a732f567ebca3bc70eaa12e7869b8b8893
Make Basket enumerable.
lukedrury/super-market-kata
engine/engine/tests/SupermarketAcceptanceTests.cs
engine/engine/tests/SupermarketAcceptanceTests.cs
using System.Collections.Generic; using NUnit.Framework; namespace engine.tests { [TestFixture] public class SupermarketAcceptanceTests { [Test] public void EmptyBasket() { var till = new Till(); var basket = new Basket(); var total = till.CalculatePrice(basket); var expected = 0; Assert.That(total, Is.EqualTo(expected)); } [Test] public void SingleItemInBasket() { var till = new Till(); var basket = new Basket(); basket.Add("pennySweet", 1); var total = till.CalculatePrice(basket); var expected = 1; Assert.That(total, Is.EqualTo(expected)); } } public class Basket : IEnumerable<BasketItem> { private readonly IList<BasketItem> items = new List<BasketItem>(); public void Add(string item, int unitPrice) { items.Add(new BasketItem(item, unitPrice)); } public IEnumerator<BasketItem> GetEnumerator() { return items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class BasketItem { public string Item { get; private set; } public int UnitPrice { get; private set; } public BasketItem(string item, int unitPrice) { Item = item; UnitPrice = unitPrice; } } public class Till { public int CalculatePrice(Basket basket) { return 0; } } }
using NUnit.Framework; namespace engine.tests { [TestFixture] public class SupermarketAcceptanceTests { [Test] public void EmptyBasket() { var till = new Till(); var basket = new Basket(); var total = till.CalculatePrice(basket); var expected = 0; Assert.That(total, Is.EqualTo(expected)); } [Test] public void SingleItemInBasket() { var till = new Till(); var basket = new Basket(); basket.Add("pennySweet", 1); var total = till.CalculatePrice(basket); var expected = 1; Assert.That(total, Is.EqualTo(expected)); } } public class Basket { private readonly IList<BasketItem> items = new List<BasketItem>(); public void Add(string item, int unitPrice) { items.Add(new BasketItem(item, unitPrice)); } } public class BasketItem { public string Item { get; private set; } public int UnitPrice { get; private set; } public BasketItem(string item, int unitPrice) { Item = item; UnitPrice = unitPrice; } } public class Till { public int CalculatePrice(Basket basket) { return 0; } } }
mit
C#
5b437cd3b02fb65791b49f18914ea2f4b52fbc03
Fix crash when multiple threads may exist.
Grabacr07/VirtualDesktop
source/VirtualDesktop/Internal/RawWindow.cs
source/VirtualDesktop/Internal/RawWindow.cs
using System; using System.Windows.Interop; using System.Windows.Threading; using WindowsDesktop.Interop; namespace WindowsDesktop.Internal { internal abstract class RawWindow { public string Name { get; set; } public HwndSource Source { get; private set; } public IntPtr Handle => this.Source?.Handle ?? IntPtr.Zero; public virtual void Show() { this.Show(new HwndSourceParameters(this.Name)); } protected void Show(HwndSourceParameters parameters) { this.Source = new HwndSource(parameters); this.Source.AddHook(this.WndProc); } public virtual void Close() { this.Source?.RemoveHook(this.WndProc); // Source could have been created on a different thread, which means we // have to Dispose of it on the UI thread or it will crash. this.Source?.Dispatcher?.BeginInvoke(DispatcherPriority.Send, (Action)(() => this.Source?.Dispose())); this.Source = null; NativeMethods.CloseWindow(this.Handle); } protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { return IntPtr.Zero; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Interop; using WindowsDesktop.Interop; namespace WindowsDesktop.Internal { internal abstract class RawWindow { public string Name { get; set; } public HwndSource Source { get; private set; } public IntPtr Handle => this.Source?.Handle ?? IntPtr.Zero; public virtual void Show() { this.Show(new HwndSourceParameters(this.Name)); } protected void Show(HwndSourceParameters parameters) { this.Source = new HwndSource(parameters); this.Source.AddHook(this.WndProc); } public virtual void Close() { this.Source?.RemoveHook(this.WndProc); this.Source?.Dispose(); this.Source = null; NativeMethods.CloseWindow(this.Handle); } protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { return IntPtr.Zero; } } }
mit
C#
95b73bf239dc80ec3464fda23bbbfcfcc5a74976
add object-type to object-type LruCache to SimpleMapper to reduce reflection calls
mvbalaw/Mapper
src/MvbaMapper/SimpleMapper.cs
src/MvbaMapper/SimpleMapper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using CodeQuery; using MvbaCore; namespace MvbaMapper { public class SimpleMapper { private static readonly LruCache<string, List<KeyValuePair<string, Action<object, object>>>> FrequentMaps = new LruCache<string, List<KeyValuePair<string, Action<object, object>>>>(50); public void Map(object source, object destination) { Map(source, destination, new Expression<Func<object, object>>[0]); } public void Map<TDestination>(object source, object destination, params Expression<Func<TDestination, object>>[] propertiesToIgnore) { if (source == null) { return; } if (destination == null) { throw new ArgumentNullException("destination"); } var sourceType = source.GetType(); var destinationType = destination.GetType(); string key = sourceType.FullName + destinationType.FullName; var map = FrequentMaps[key]; if (map == null) { map = Reflection.GetMatchingFieldsAndProperties(sourceType, destinationType) .Where(x => x.DestinationPropertyType.IsAssignableFrom(x.SourcePropertyType) || x.DestinationPropertyType.IsGenericAssignableFrom(x.SourcePropertyType)) .Select(x => new KeyValuePair<string, Action<object, object>>(x.Name, (s, d) => { var sourceValue = x.GetValueFromSource(s); x.SetValueToDestination(d, sourceValue); })) .ToList(); FrequentMaps.Add(key, map); } var properties = propertiesToIgnore.Any() ? new HashSet<string>(new MapperUtilities().GetPropertyNames(propertiesToIgnore)) : new HashSet<string>(); foreach (var action in map .Where(x => !properties.Contains(x.Key))) { action.Value(source, destination); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using CodeQuery; using MvbaCore; namespace MvbaMapper { public class SimpleMapper { public void Map(object source, object destination) { Map(source, destination, new Expression<Func<object, object>>[0]); } public void Map<TDestination>(object source, object destination, Expression<Func<TDestination, object>>[] propertiesToIgnore) { var properties = new HashSet<string>(new MapperUtilities().GetPropertyNames(propertiesToIgnore)); if (source == null) { return; } if (destination == null) { throw new ArgumentNullException("destination"); } foreach (var std in Reflection.GetMatchingFieldsAndProperties(source.GetType(), destination.GetType()) .Where(x => !properties.Contains(x.Name)) .Where(x => x.DestinationPropertyType.IsAssignableFrom(x.SourcePropertyType) || x.DestinationPropertyType.IsGenericAssignableFrom(x.SourcePropertyType))) { var sourceValue = std.GetValueFromSource(source); std.SetValueToDestination(destination, sourceValue); } } } }
mit
C#
6435db2596c464f9a258d21b45bff0427d1de3f2
Fix running on Linux. Closes #30.
Abc-Arbitrage/ZeroLog
src/ZeroLog/Utils/HighResolutionDateTime.cs
src/ZeroLog/Utils/HighResolutionDateTime.cs
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace ZeroLog.Utils { internal static class HighResolutionDateTime { private static readonly bool _isAvailable = CheckAvailability(); [DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi)] private static extern void GetSystemTimePreciseAsFileTime(out long filetime); public static DateTime UtcNow { get { if (!_isAvailable) return DateTime.UtcNow; GetSystemTimePreciseAsFileTime(out var filetime); return DateTime.FromFileTimeUtc(filetime); } } [DebuggerStepThrough] private static bool CheckAvailability() { try { GetSystemTimePreciseAsFileTime(out _); return true; } catch (DllNotFoundException) { // Not running Windows 8 or higher. return false; } catch (EntryPointNotFoundException) { // Not running Windows 8 or higher. return false; } } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace ZeroLog.Utils { internal static class HighResolutionDateTime { private static readonly bool _isAvailable = CheckAvailability(); [DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi)] private static extern void GetSystemTimePreciseAsFileTime(out long filetime); public static DateTime UtcNow { get { if (!_isAvailable) return DateTime.UtcNow; GetSystemTimePreciseAsFileTime(out var filetime); return DateTime.FromFileTimeUtc(filetime); } } [DebuggerStepThrough] private static bool CheckAvailability() { try { GetSystemTimePreciseAsFileTime(out _); return true; } catch (EntryPointNotFoundException) { // Not running Windows 8 or higher. return false; } } } }
mit
C#
096e4aa0e540ab5e9a661df5e7b2a7504dac92f5
update BasicSliderBar design
EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework
osu.Framework/Graphics/UserInterface/BasicSliderBar.cs
osu.Framework/Graphics/UserInterface/BasicSliderBar.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 osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; namespace osu.Framework.Graphics.UserInterface { public class BasicSliderBar<T> : SliderBar<T> where T : struct, IComparable, IConvertible { public Color4 BackgroundColour { get => Box.Colour; set => Box.Colour = value; } public Color4 SelectionColour { get => SelectionBox.Colour; set => SelectionBox.Colour = value; } protected readonly Box SelectionBox; protected readonly Box Box; public BasicSliderBar() { Children = new Drawable[] { Box = new Box { RelativeSizeAxes = Axes.Both, Colour = FrameworkColour.Green, }, SelectionBox = new Box { RelativeSizeAxes = Axes.Both, Colour = FrameworkColour.Yellow, } }; } protected override void UpdateValue(float value) { SelectionBox.ScaleTo(new Vector2(value, 1), 300, Easing.OutQuint); } } }
// 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 osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; namespace osu.Framework.Graphics.UserInterface { public class BasicSliderBar<T> : SliderBar<T> where T : struct, IComparable, IConvertible { public Color4 BackgroundColour { get => Box.Colour; set => Box.Colour = value; } public Color4 SelectionColour { get => SelectionBox.Colour; set => SelectionBox.Colour = value; } protected readonly Box SelectionBox; protected readonly Box Box; public BasicSliderBar() { CornerRadius = 4; Masking = true; Children = new Drawable[] { Box = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.MediumPurple.Darken(0.5f), }, SelectionBox = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.MediumPurple.Lighten(0.1f), } }; } protected override void UpdateValue(float value) { SelectionBox.ScaleTo(new Vector2(value, 1), 300, Easing.OutQuint); } } }
mit
C#
0a873084f88bfdfc13714878cb345dfa3781bb55
add LanmanServer to pgina service dependencies
daviddumas/pgina,daviddumas/pgina,daviddumas/pgina,MutonUfoAI/pgina,MutonUfoAI/pgina,MutonUfoAI/pgina
pGina/src/Service/Service/ProjectInstaller.Designer.cs
pGina/src/Service/Service/ProjectInstaller.Designer.cs
namespace pGina.Service.Service { partial class ProjectInstaller { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pGinaServiceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller(); this.pGinaServiceProjectInstaller = new System.ServiceProcess.ServiceInstaller(); // // pGinaServiceProcessInstaller // this.pGinaServiceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.pGinaServiceProcessInstaller.Password = null; this.pGinaServiceProcessInstaller.Username = null; // // pGinaServiceProjectInstaller // this.pGinaServiceProjectInstaller.Description = "pGina Management Service"; this.pGinaServiceProjectInstaller.DisplayName = "pGina Service"; this.pGinaServiceProjectInstaller.ServiceName = "pGina"; this.pGinaServiceProjectInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; this.pGinaServiceProjectInstaller.ServicesDependedOn = new string[] { "TermService", "LanmanServer" }; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.pGinaServiceProcessInstaller, this.pGinaServiceProjectInstaller}); } #endregion private System.ServiceProcess.ServiceProcessInstaller pGinaServiceProcessInstaller; private System.ServiceProcess.ServiceInstaller pGinaServiceProjectInstaller; } }
namespace pGina.Service.Service { partial class ProjectInstaller { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pGinaServiceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller(); this.pGinaServiceProjectInstaller = new System.ServiceProcess.ServiceInstaller(); // // pGinaServiceProcessInstaller // this.pGinaServiceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.pGinaServiceProcessInstaller.Password = null; this.pGinaServiceProcessInstaller.Username = null; // // pGinaServiceProjectInstaller // this.pGinaServiceProjectInstaller.Description = "pGina Management Service"; this.pGinaServiceProjectInstaller.DisplayName = "pGina Service"; this.pGinaServiceProjectInstaller.ServiceName = "pGina"; this.pGinaServiceProjectInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; this.pGinaServiceProjectInstaller.ServicesDependedOn = new string[] {"TermService"}; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.pGinaServiceProcessInstaller, this.pGinaServiceProjectInstaller}); } #endregion private System.ServiceProcess.ServiceProcessInstaller pGinaServiceProcessInstaller; private System.ServiceProcess.ServiceInstaller pGinaServiceProjectInstaller; } }
bsd-3-clause
C#
b2f7411f3aaaa0ab170c4c376a94263f6722e4d1
Add standard demo sites setup as a test
webprofusion/Certify
src/Certify.Tests/Certify.Service.Tests.Integration/ManagedSitesTests.cs
src/Certify.Tests/Certify.Service.Tests.Integration/ManagedSitesTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using Certify.Models; using System.Collections.Generic; namespace Certify.Service.Tests.Integration { [TestClass] public class ManagedCertificateTests : ServiceTestBase { [TestMethod] public async Task TestGetManagedCertificates() { var filter = new ManagedCertificateFilter(); var result = await _client.GetManagedCertificates(filter); Assert.IsNotNull(result, $"Fetched {result.Count} managed sites"); } [TestMethod] public async Task TestGetManagedCertificate() { //get full list var filter = new ManagedCertificateFilter { MaxResults = 10 }; var results = await _client.GetManagedCertificates(filter); Assert.IsTrue(results.Count > 0, "Got one or more managed sites"); //attempt to get single item var site = await _client.GetManagedCertificate(results[0].Id); Assert.IsNotNull(site, $"Fetched single managed site details"); } [TestMethod] [Ignore] public async Task TestCreateManagedCertificates() { //get full list var list = new List<ManagedCertificate> { GetExample("msdn.webprofusion.com", 12), GetExample("demo.webprofusion.co.uk", 45), GetExample("clients.dependencymanager.com",75), GetExample("soundshed.com",32), GetExample("*.projectbids.co.uk",48), GetExample("exchange.projectbids.co.uk",19), GetExample("remote.dependencymanager.com",7), GetExample("git.example.com",56) }; foreach (var site in list) { await _client.UpdateManagedCertificate(site); } } private ManagedCertificate GetExample(string title, int numDays) { return new ManagedCertificate() { Id = Guid.NewGuid().ToString(), Name = title, DateExpiry = DateTime.Now.AddDays(numDays), DateLastRenewalAttempt = DateTime.Now.AddDays(-1), LastRenewalStatus = RequestState.Success }; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using Certify.Models; namespace Certify.Service.Tests.Integration { [TestClass] public class ManagedCertificateTests : ServiceTestBase { [TestMethod] public async Task TestGetManagedCertificates() { var filter = new ManagedCertificateFilter(); var result = await _client.GetManagedCertificates(filter); Assert.IsNotNull(result, $"Fetched {result.Count} managed sites"); } [TestMethod] public async Task TestGetManagedCertificate() { //get full list var filter = new ManagedCertificateFilter { MaxResults = 10 }; var results = await _client.GetManagedCertificates(filter); Assert.IsTrue(results.Count > 0, "Got one or more managed sites"); //attempt to get single item var site = await _client.GetManagedCertificate(results[0].Id); Assert.IsNotNull(site, $"Fetched single managed site details"); } } }
mit
C#
86c0560d67d1d2d2e2d91375dedd044c56a752b0
Update CreateCohortRequest.cs
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/CreateCohortRequest.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/CreateCohortRequest.cs
using System; namespace SFA.DAS.CommitmentsV2.Api.Types { public sealed class CreateCohortRequest { public string UserId { get; set; } public NewCohort Cohort { get; set; } public NewDraftApprenticeship DraftApprenticeship { get; set; } public sealed class NewCohort { public long EmployerAccountId { get; set; } public string LegalEntityId { get; set; } public int ProviderId { get; set; } } public sealed class NewDraftApprenticeship { public string FirstName { get; set; } public string LastName { get; set; } public DateTime? DateOfBirth { get; set; } public string ULN { get; set; } public string CourseCode { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public string OriginatorReference { get; set; } } } }
using System; namespace SFA.DAS.CommitmentsV2.Api.Types { public sealed class CreateCohortRequest { public string UserId { get; set; } public NewCohort Cohort { get; set; } public NewDraftApprenticeship DraftApprenticeship { get; set; } public sealed class NewCohort { public long EmployerAccountId { get; set; } public string LegalEntityId { get; set; } public int ProviderId { get; set; } } public sealed class NewDraftApprenticeship { public string FirstName { get; set; } public string LastName { get; set; } public DateTime? DateOfBirth { get; set; } public string ULN { get; set; } public string CourseCode { get; set; } public int? Cost { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public string OriginatorsReference { get; set; } } } }
mit
C#
b8cefcb493dae0ed33175fa8325914db0c3d4549
add default value to timestamps
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Data/EntityTypeConfigurations/BaseEntityConfiguration.cs
src/FilterLists.Data/EntityTypeConfigurations/BaseEntityConfiguration.cs
using FilterLists.Data.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace FilterLists.Data.EntityTypeConfigurations { public class BaseEntityTypeConfiguration<TBase> : IEntityTypeConfiguration<TBase> where TBase : BaseEntity { public virtual void Configure(EntityTypeBuilder<TBase> entityTypeBuilder) { entityTypeBuilder.HasKey(b => b.Id); entityTypeBuilder.Property(b => b.Id) .ValueGeneratedOnAdd(); entityTypeBuilder.Property(b => b.CreatedDateUtc) .HasColumnType("TIMESTAMP") .HasDefaultValueSql("CURRENT_TIMESTAMP") .ValueGeneratedOnAdd(); entityTypeBuilder.Property(b => b.ModifiedDateUtc) .HasColumnType("TIMESTAMP") .HasDefaultValueSql("CURRENT_TIMESTAMP") .ValueGeneratedOnUpdate(); } } }
using FilterLists.Data.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace FilterLists.Data.EntityTypeConfigurations { public class BaseEntityTypeConfiguration<TBase> : IEntityTypeConfiguration<TBase> where TBase : BaseEntity { public virtual void Configure(EntityTypeBuilder<TBase> entityTypeBuilder) { entityTypeBuilder.HasKey(b => b.Id); entityTypeBuilder.Property(b => b.Id) .ValueGeneratedOnAdd(); entityTypeBuilder.Property(b => b.CreatedDateUtc) .HasColumnType("TIMESTAMP") .ValueGeneratedOnAdd(); entityTypeBuilder.Property(b => b.ModifiedDateUtc) .HasColumnType("TIMESTAMP") .ValueGeneratedOnUpdate(); } } }
mit
C#
cb5a1acfeec0e24220bd298204b1536f5308b9dc
test fixed
mijay/NClone
src/NClone.Tests/ReplicationStrategies/ReplicationStrategyFactoryTest.cs
src/NClone.Tests/ReplicationStrategies/ReplicationStrategyFactoryTest.cs
using FakeItEasy; using FakeItEasy.ExtensionSyntax.Full; using NClone.MetadataProviders; using NClone.ReplicationStrategies; using NUnit.Framework; namespace NClone.Tests.ReplicationStrategies { public class ReplicationStrategyFactoryTest: TestBase { private static ReplicationStrategyFactory StrategyWhere<T>(ReplicationBehavior isMarkedAs) { var metadataProvider = A.Fake<IMetadataProvider>(x => x.Strict()); metadataProvider .CallsTo(x => x.GetBehavior(typeof (T))) .Returns(isMarkedAs); metadataProvider .CallsTo(x => x.GetMembers(typeof (T))) .WithAnyArguments() .Returns(new MemberInformation[0]); return new ReplicationStrategyFactory(metadataProvider); } [Test] public void TypeIsMarkedAsIgnored_IgnoringStrategyReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Ignore); IReplicationStrategy result = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result, Is.InstanceOf<IgnoringReplicationStrategy>()); } [Test] public void SourceIsMarkedAsCopy_CopyStrategyReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Copy); IReplicationStrategy result = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result, Is.InstanceOf<CopyOnlyReplicationStrategy>()); } [Test] public void SourceIsMarkedAsReplicate_CommonStrategyReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Replicate); IReplicationStrategy result = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result, Is.InstanceOf<CommonReplicationStrategy>()); } [Test] public void GetStrategyTwiceForTheSameType_SameStrategiesReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Replicate); IReplicationStrategy result1 = strategyFactory.StrategyForType(typeof (Class)); IReplicationStrategy result2 = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result2, Is.SameAs(result1)); } private class Class { public object field; } } }
using FakeItEasy; using FakeItEasy.ExtensionSyntax.Full; using NClone.MetadataProviders; using NClone.ReplicationStrategies; using NUnit.Framework; namespace NClone.Tests.ReplicationStrategies { public class ReplicationStrategyFactoryTest: TestBase { private static ReplicationStrategyFactory StrategyWhere<T>(ReplicationBehavior isMarkedAs) { var metadataProvider = A.Fake<IMetadataProvider>(x => x.Strict()); metadataProvider .CallsTo(x => x.GetBehavior(typeof (T))) .Returns(isMarkedAs); return new ReplicationStrategyFactory(metadataProvider); } [Test] public void TypeIsMarkedAsIgnored_IgnoringStrategyReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Ignore); IReplicationStrategy result = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result, Is.InstanceOf<IgnoringReplicationStrategy>()); } [Test] public void SourceIsMarkedAsCopy_CopyStrategyReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Copy); IReplicationStrategy result = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result, Is.InstanceOf<CopyOnlyReplicationStrategy>()); } [Test] public void SourceIsMarkedAsReplicate_CommonStrategyReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Replicate); IReplicationStrategy result = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result, Is.InstanceOf<CommonReplicationStrategy>()); } [Test] public void GetStrategyTwiceForTheSameType_SameStrategiesReturned() { ReplicationStrategyFactory strategyFactory = StrategyWhere<Class>(isMarkedAs: ReplicationBehavior.Replicate); IReplicationStrategy result1 = strategyFactory.StrategyForType(typeof (Class)); IReplicationStrategy result2 = strategyFactory.StrategyForType(typeof (Class)); Assert.That(result2, Is.SameAs(result1)); } private class Class { public object field; } } }
mit
C#
3bf70dea60ed87d447cdbe64bc03cfc843bfc7b1
fix test to using heading block
peppy/osu-new,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,ppy/osu,ppy/osu
osu.Game.Tests/Visual/Online/TestSceneWikiSidebar.cs
osu.Game.Tests/Visual/Online/TestSceneWikiSidebar.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 Markdig.Parsers; using Markdig.Syntax; using Markdig.Syntax.Inlines; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; using osu.Game.Overlays; using osu.Game.Overlays.Wiki; namespace osu.Game.Tests.Visual.Online { public class TestSceneWikiSidebar : OsuTestScene { [Cached] private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Orange); [Cached] private readonly OverlayScrollContainer scrollContainer = new OverlayScrollContainer(); private WikiSidebar sidebar; [SetUp] public void SetUp() => Schedule(() => Child = sidebar = new WikiSidebar()); [Test] public void TestNoContent() { AddStep("No Content", () => { }); } [Test] public void TestOnlyMainTitle() { AddStep("Add TOC", () => { for (var i = 0; i < 10; i++) addTitle($"This is a very long title {i + 1}"); }); } [Test] public void TestWithSubtitle() { AddStep("Add TOC", () => { for (var i = 0; i < 10; i++) addTitle($"This is a very long title {i + 1}", i % 4 != 0); }); } private void addTitle(string text, bool subtitle = false) { var headingBlock = createHeadingBlock(text, subtitle ? 3 : 2); sidebar.AddToc(headingBlock, createHeading(headingBlock)); } private HeadingBlock createHeadingBlock(string text, int level = 2) => new HeadingBlock(new HeadingBlockParser()) { Inline = new ContainerInline().AppendChild(new LiteralInline(text)), Level = level, }; private MarkdownHeading createHeading(HeadingBlock headingBlock) => new OsuMarkdownHeading(headingBlock); } }
// 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 Markdig.Parsers; using Markdig.Syntax; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Overlays; using osu.Game.Overlays.Wiki; namespace osu.Game.Tests.Visual.Online { public class TestSceneWikiSidebar : OsuTestScene { [Cached] private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Orange); [Cached] private readonly OverlayScrollContainer scrollContainer = new OverlayScrollContainer(); private WikiSidebar sidebar; private readonly MarkdownHeading dummyHeading = new MarkdownHeading(new HeadingBlock(new HeadingBlockParser())); [SetUp] public void SetUp() => Schedule(() => Child = sidebar = new WikiSidebar()); [Test] public void TestNoContent() { AddStep("No Content", () => { }); } [Test] public void TestOnlyMainTitle() { AddStep("Add TOC", () => { for (var i = 0; i < 10; i++) { sidebar.AddToc($"This is a very long title {i + 1}", dummyHeading, 2); } }); } [Test] public void TestWithSubtitle() { AddStep("Add TOC", () => { for (var i = 0; i < 20; i++) { sidebar.AddToc($"This is a very long title {i + 1}", dummyHeading, i % 4 == 0 ? 2 : 3); } }); } } }
mit
C#
f6e4fddc003261e767f62ad068ee976f180d2776
remove var
jefking/King.Service.ServiceBus
King.Service.ServiceBus.Tests/Integration/Wrappers/BusTopicClientTests.cs
King.Service.ServiceBus.Tests/Integration/Wrappers/BusTopicClientTests.cs
namespace King.Service.ServiceBus.Test.Integration.Wrappers { using global::Azure.Data.Wrappers; using King.Service.ServiceBus.Models; using King.Service.ServiceBus.Wrappers; using Microsoft.Azure.ServiceBus; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; [TestFixture] public class BusTopicClientTests { private static readonly string connection = King.Service.ServiceBus.Test.Integration.Configuration.ConnectionString; private string sendName, recieveName, sendBatchName; [SetUp] public void Setup() { var random = new Random(); sendName = string.Format("a{0}b", random.Next()); sendBatchName = string.Format("a{0}b", random.Next()); var client = new BusManagementClient(connection); Task.WaitAll( new Task[] { client.TopicCreate(sendName) , client.TopicCreate(sendBatchName) } ); } [TearDown] public void TearDown() { var client = new BusManagementClient(connection).Client; Task.WaitAll( new Task[] { client.DeleteTopicAsync(sendName) , client.DeleteTopicAsync(sendBatchName) } ); } [Test] public async Task Send() { var queue = new BusTopicClient(sendName, connection); await queue.Send(new Message()); } [Test] public async Task SendBatch() { var msgs = new Message[] { new Message(), new Message(), new Message(), new Message() }; var queue = new BusTopicClient(sendBatchName, connection); await queue.Send(msgs); } } }
namespace King.Service.ServiceBus.Test.Integration.Wrappers { using global::Azure.Data.Wrappers; using King.Service.ServiceBus.Models; using King.Service.ServiceBus.Wrappers; using Microsoft.Azure.ServiceBus; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; [TestFixture] public class BusTopicClientTests { private static readonly string connection = King.Service.ServiceBus.Test.Integration.Configuration.ConnectionString; private string sendName, recieveName, sendBatchName; [SetUp] public void Setup() { var random = new Random(); sendName = string.Format("a{0}b", random.Next()); recieveName = string.Format("a{0}b", random.Next()); sendBatchName = string.Format("a{0}b", random.Next()); var client = new BusManagementClient(connection); Task.WaitAll( new Task[] { client.TopicCreate(sendName) , client.TopicCreate(recieveName) , client.TopicCreate(sendBatchName) } ); } [TearDown] public void TearDown() { var client = new BusManagementClient(connection).Client; Task.WaitAll( new Task[] { client.DeleteTopicAsync(sendName) , client.DeleteTopicAsync(recieveName) , client.DeleteTopicAsync(sendBatchName) } ); } [Test] public async Task Send() { var queue = new BusTopicClient(sendName, connection); await queue.Send(new Message()); } [Test] public async Task SendBatch() { var msgs = new Message[] { new Message(), new Message(), new Message(), new Message() }; var queue = new BusTopicClient(sendBatchName, connection); await queue.Send(msgs); } } }
mit
C#
36b7a7617aad41a1bbd6c5548d2513d8c7741f81
use local variable
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/AddWallet/ConfirmRecoveryWordsViewModel.cs
WalletWasabi.Fluent/ViewModels/AddWallet/ConfirmRecoveryWordsViewModel.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Windows.Input; using DynamicData; using DynamicData.Binding; using ReactiveUI; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Wallets; namespace WalletWasabi.Fluent.ViewModels.AddWallet { public class ConfirmRecoveryWordsViewModel : RoutableViewModel { private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords; public ConfirmRecoveryWordsViewModel(NavigationStateViewModel navigationState, List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager) : base(navigationState, NavigationTarget.DialogScreen) { SourceList<RecoveryWordViewModel> confirmationWordsSourceList = new(); var finishCommandCanExecute = confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .WhenValueChanged(x => x.IsConfirmed) .Select(x => !confirmationWordsSourceList.Items.Any(x => !x.IsConfirmed)); NextCommand = ReactiveCommand.Create( () => { walletManager.AddWallet(keyManager); ClearNavigation(NavigationTarget.DialogScreen); }, finishCommandCanExecute); CancelCommand = ReactiveCommand.Create(() => ClearNavigation(NavigationTarget.DialogScreen)); confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .OnItemAdded(x => x.Reset()) .Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index)) .Bind(out _confirmationWords) .Subscribe(); // Select 4 random words to confirm. confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(x => new Random().NextDouble()).Take(4)); } public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords; public ICommand NextCommand { get; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Windows.Input; using DynamicData; using DynamicData.Binding; using ReactiveUI; using WalletWasabi.Blockchain.Keys; 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.DialogScreen) { _confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>(); var finishCommandCanExecute = _confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .WhenValueChanged(x => x.IsConfirmed) .Select(x => !_confirmationWordsSourceList.Items.Any(x => !x.IsConfirmed)); NextCommand = ReactiveCommand.Create( () => { walletManager.AddWallet(keyManager); ClearNavigation(NavigationTarget.DialogScreen); }, finishCommandCanExecute); CancelCommand = ReactiveCommand.Create(() => ClearNavigation(NavigationTarget.DialogScreen)); _confirmationWordsSourceList .Connect() .ObserveOn(RxApp.MainThreadScheduler) .OnItemAdded(x => x.Reset()) .Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index)) .Bind(out _confirmationWords) .Subscribe(); // Select 4 random words to confirm. _confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(x => new Random().NextDouble()).Take(4)); } public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords; public ICommand NextCommand { get; } } }
mit
C#
c65ea3d9e05f3c22ee88f7ff0b75758282d8a23d
refactor linq steps to methods
Pondidum/Stronk,Pondidum/Stronk
src/Stronk/ConfigBuilder.cs
src/Stronk/ConfigBuilder.cs
using System.Linq; using Stronk.Policies; using Stronk.PropertySelection; using Stronk.SourceValueSelection; namespace Stronk { public class ConfigBuilder { private readonly StronkOptions _options; public ConfigBuilder(StronkOptions options) { _options = options; } public void Populate(object target, IConfigurationSource configSource) { var propertySelectors = _options.PropertySelectors.ToArray(); _options.WriteLog( "Populating '{typeName}', from {sourceTypeName} using\nPropertySelectors: {propertySelectors}\nSourceValueSelectors: {valueSelectors}\nValueConverters: {valueConverters}.", target.GetType().Name, configSource.GetType().Name, propertySelectors.SelectTypeNames(), _options.ValueSelectors.SelectTypeNames(), _options.ValueConverters.SelectTypeNames()); var propertySelectorArgs = new PropertySelectorArgs( _options.Logger, target.GetType()); var properties = propertySelectors .SelectMany(selector => selector.Select(propertySelectorArgs)) .ToArray(); _options.WriteLog( "Selected {count} properties to populate: {properties}", properties.Length, properties.Select(p => p.Name)); var applicator = new Applicator(_options); var values = properties .Select(property => NewPropertyConversionUnit(configSource, property)) .Where(SelectedValueIsValid) .Where(SelectedConvertersAreValid); foreach (var descriptor in values) { applicator.Apply(descriptor, target); } } private bool SelectedConvertersAreValid(PropertyConversionUnit descriptor) { if (descriptor.Converters.Any()) return true; _options.WriteLog("Unable to any converters for {typeName} for property {propertyName}", descriptor.Property.Type.Name, descriptor.Property.Name); _options.ErrorPolicy.OnConverterNotFound.Handle(new ConverterNotFoundArgs { AvailableConverters = _options.ValueConverters, Property = descriptor.Property }); return false; } private bool SelectedValueIsValid(PropertyConversionUnit descriptor) { if (descriptor.Value != null) return true; _options.WriteLog("Unable to find a value for {propertyName}", descriptor.Property.Name); _options.ErrorPolicy.OnSourceValueNotFound.Handle(new SourceValueNotFoundArgs { ValueSelectors = _options.ValueSelectors, Property = descriptor.Property }); return false; } private PropertyConversionUnit NewPropertyConversionUnit(IConfigurationSource configSource, PropertyDescriptor property) { var selectionArgs = new ValueSelectorArgs(_options.Logger, configSource, property); return new PropertyConversionUnit { Property = property, Converters = _options.ValueConverters.Where(c => c.CanMap(property.Type)).ToArray(), Value = _options.ValueSelectors.Select(x => x.Select(selectionArgs)).FirstOrDefault(v => v != null) }; } } }
using System.Linq; using Stronk.Policies; using Stronk.PropertySelection; using Stronk.SourceValueSelection; using Stronk.ValueConversion; namespace Stronk { public class ConfigBuilder { private readonly StronkOptions _options; public ConfigBuilder(StronkOptions options) { _options = options; } public void Populate(object target, IConfigurationSource configSource) { var propertySelectors = _options.PropertySelectors.ToArray(); _options.WriteLog( "Populating '{typeName}', from {sourceTypeName} using\nPropertySelectors: {propertySelectors}\nSourceValueSelectors: {valueSelectors}\nValueConverters: {valueConverters}.", target.GetType().Name, configSource.GetType().Name, propertySelectors.SelectTypeNames(), _options.ValueSelectors.SelectTypeNames(), _options.ValueConverters.SelectTypeNames()); var propertySelectorArgs = new PropertySelectorArgs( _options.Logger, target.GetType()); var properties = propertySelectors .SelectMany(selector => selector.Select(propertySelectorArgs)) .ToArray(); _options.WriteLog( "Selected {count} properties to populate: {properties}", properties.Length, properties.Select(p => p.Name)); var applicator = new Applicator(_options); var values = properties .Select(property => NewPropertyConversionUnit(configSource, property)) .Where(descriptor => { if (descriptor.Value != null) return true; _options.WriteLog("Unable to find a value for {propertyName}", descriptor.Property.Name); _options.ErrorPolicy.OnSourceValueNotFound.Handle(new SourceValueNotFoundArgs { ValueSelectors = _options.ValueSelectors, Property = descriptor.Property }); return false; }) .Where(descriptor => { if (descriptor.Converters.Any()) return true; _options.WriteLog("Unable to any converters for {typeName} for property {propertyName}", descriptor.Property.Type.Name, descriptor.Property.Name); _options.ErrorPolicy.OnConverterNotFound.Handle(new ConverterNotFoundArgs { AvailableConverters = _options.ValueConverters, Property = descriptor.Property }); return false; }); foreach (var descriptor in values) { applicator.Apply(descriptor, target); } } private PropertyConversionUnit NewPropertyConversionUnit(IConfigurationSource configSource, PropertyDescriptor property) { var selectionArgs = new ValueSelectorArgs(_options.Logger, configSource, property); return new PropertyConversionUnit { Property = property, Converters = _options.ValueConverters.Where(c => c.CanMap(property.Type)).ToArray(), Value = _options.ValueSelectors.Select(x => x.Select(selectionArgs)).FirstOrDefault(v => v != null) }; } } }
lgpl-2.1
C#
19d99991bdd9889ce516bd0049e796d00e412046
fix preview top padding on iOS.
patridge/MarkdownSharp.Portable
MarkdownSharp.Sample.Forms/MarkdownSharp.Sample.Forms.cs
MarkdownSharp.Sample.Forms/MarkdownSharp.Sample.Forms.cs
using System; using Xamarin.Forms; namespace MarkdownSharp.Sample.Forms { public class App : Application { readonly Markdown markdown = new Markdown(); string markdownHtml; public void UpdatePreview(string rawMarkdown) { markdownHtml = markdown.Transform(rawMarkdown); if (webView != null) { webView.Source = new HtmlWebViewSource() { Html = markdownHtml, }; } } Editor markdownEditor; WebView webView; ContentPage markdownInputPage; ContentPage markdownPreviewPage; public App() { markdownEditor = new Editor() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; markdownEditor.TextChanged += MarkdownEditor_TextChanged; markdownInputPage = new ContentPage() { Title = "Markdown Input", Content = new StackLayout() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, Padding = new OnPlatform<Thickness>() { iOS = new Thickness(0, 20, 0, 0), }, Children = { markdownEditor, }, }, }; webView = new WebView() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; markdownPreviewPage = new ContentPage() { Title = "HTML Preview", Content = new StackLayout() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, Padding = new OnPlatform<Thickness>() { iOS = new Thickness(0, 20, 0, 0), }, Children = { webView, }, }, }; var tabs = new TabbedPage() { Children = { markdownInputPage, markdownPreviewPage, }, }; MainPage = tabs; } void MarkdownEditor_TextChanged (object sender, TextChangedEventArgs e) { UpdatePreview(e.NewTextValue); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
using System; using Xamarin.Forms; namespace MarkdownSharp.Sample.Forms { public class App : Application { readonly Markdown markdown = new Markdown(); string markdownHtml; public void UpdatePreview(string rawMarkdown) { markdownHtml = markdown.Transform(rawMarkdown); if (webView != null) { webView.Source = new HtmlWebViewSource() { Html = markdownHtml, }; } } Editor markdownEditor; WebView webView; ContentPage markdownInputPage; ContentPage markdownPreviewPage; public App() { markdownEditor = new Editor() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; markdownEditor.TextChanged += MarkdownEditor_TextChanged; markdownInputPage = new ContentPage() { Title = "Markdown Input", Content = new StackLayout() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, Padding = new OnPlatform<Thickness>() { iOS = new Thickness(0, 20, 0, 0), }, Children = { markdownEditor, }, }, }; webView = new WebView() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; markdownPreviewPage = new ContentPage() { Title = "HTML Preview", Content = new StackLayout() { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { webView, }, }, }; var tabs = new TabbedPage() { Children = { markdownInputPage, markdownPreviewPage, }, }; MainPage = tabs; } void MarkdownEditor_TextChanged (object sender, TextChangedEventArgs e) { UpdatePreview(e.NewTextValue); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
mit
C#
70662670f47d4c13adac7b152631fac6be577343
Make scheduler private fields readonly (#2054)
benaadams/corefxlab,KrzysztofCwalina/corefxlab,whoisj/corefxlab,stephentoub/corefxlab,dotnet/corefxlab,ericstj/corefxlab,ahsonkhan/corefxlab,KrzysztofCwalina/corefxlab,adamsitnik/corefxlab,tarekgh/corefxlab,dotnet/corefxlab,whoisj/corefxlab,ericstj/corefxlab,ericstj/corefxlab,ericstj/corefxlab,benaadams/corefxlab,stephentoub/corefxlab,tarekgh/corefxlab,adamsitnik/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,joshfree/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,ahsonkhan/corefxlab,joshfree/corefxlab
src/System.IO.Pipelines/System/Threading/Scheduler.cs
src/System.IO.Pipelines/System/Threading/Scheduler.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Threading { public abstract class Scheduler { private static readonly ThreadPoolScheduler _threadPoolScheduler = new ThreadPoolScheduler(); private static readonly InlineScheduler _inlineScheduler = new InlineScheduler(); public static Scheduler ThreadPool => _threadPoolScheduler; public static Scheduler Inline => _inlineScheduler; public abstract void Schedule(Action action); public abstract void Schedule(Action<object> action, object state); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Threading { public abstract class Scheduler { private static ThreadPoolScheduler _threadPoolScheduler = new ThreadPoolScheduler(); private static InlineScheduler _inlineScheduler = new InlineScheduler(); public static Scheduler ThreadPool => _threadPoolScheduler; public static Scheduler Inline => _inlineScheduler; public abstract void Schedule(Action action); public abstract void Schedule(Action<object> action, object state); } }
mit
C#
22edb3e1bba3529809a3502819e3da01d2377ef5
Disable ServicePoint on Silverlight
jskeet/google-api-dotnet-client,googleapis/google-api-dotnet-client,amnsinghl/google-api-dotnet-client,eshivakant/google-api-dotnet-client,arjunRanosys/google-api-dotnet-client,eydjey/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,hivie7510/google-api-dotnet-client,cdanielm58/google-api-dotnet-client,jskeet/google-api-dotnet-client,eshangin/google-api-dotnet-client,milkmeat/google-api-dotnet-client,mylemans/google-api-dotnet-client,sqt-android/google-api-dotnet-client,amitla/google-api-dotnet-client,aoisensi/google-api-dotnet-client,asifshaon/google-api-dotnet-client,ssett/google-api-dotnet-client,jtattermusch/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,inetdream/google-api-dotnet-client,hoangduit/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,maha-khedr/google-api-dotnet-client,ErAmySharma/google-api-dotnet-client,ephraimncory/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,hurcane/google-api-dotnet-client,MyOwnClone/google-api-dotnet-client,shumaojie/google-api-dotnet-client,rburgstaler/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,googleapis/google-api-dotnet-client,initaldk/google-api-dotnet-client,amitla/google-api-dotnet-client,bacm/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,SimonAntony/google-api-dotnet-client,karishmal/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,liuqiaosz/google-api-dotnet-client,peleyal/google-api-dotnet-client,ajaypradeep/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,neil-119/google-api-dotnet-client,nicolasdavel/google-api-dotnet-client,shumaojie/google-api-dotnet-client,olofd/google-api-dotnet-client,smarly-net/google-api-dotnet-client,MesutGULECYUZ/google-api-dotnet-client,ajmal744/google-api-dotnet-client,peleyal/google-api-dotnet-client,hurcane/google-api-dotnet-client,PiRSquared17/google-api-dotnet-client,lli-klick/google-api-dotnet-client,initaldk/google-api-dotnet-client,neil-119/google-api-dotnet-client,hurcane/google-api-dotnet-client,jskeet/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,jtattermusch/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,jesusog/google-api-dotnet-client,kelvinRosa/google-api-dotnet-client,RavindraPatidar/google-api-dotnet-client,duckhamqng/google-api-dotnet-client,chenneo/google-api-dotnet-client,amit-learning/google-api-dotnet-client,sawanmishra/google-api-dotnet-client,kapil-chauhan-ngi/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,line21c/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,googleapis/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,Senthilvera/google-api-dotnet-client,DJJam/google-api-dotnet-client,luantn2/google-api-dotnet-client,peleyal/google-api-dotnet-client,hurcane/google-api-dotnet-client,abujehad139/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,joesoc/google-api-dotnet-client,mjacobsen4DFM/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,aoisensi/google-api-dotnet-client,initaldk/google-api-dotnet-client,kekewong/google-api-dotnet-client,pgallastegui/google-api-dotnet-client
Src/GoogleApis/Apis/Authentication/HttpRequestFactory.cs
Src/GoogleApis/Apis/Authentication/HttpRequestFactory.cs
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Net; namespace Google.Apis.Authentication { /// <summary> /// Use the Create method to create HttpWebRequests given a Uri. /// </summary> public class HttpRequestFactory : ICreateHttpRequest { #region ICreateHttpRequest Members public HttpWebRequest Create(Uri target, string method) { var req = WebRequest.Create(target) as HttpWebRequest; req.Method = method; #if !SILVERLIGHT // Turn off Expect100Continue behavior. For web method calls it is not used // and many servers reject the request if this is present on PUT or POST // requests with a body present. If used, Expect100Continue prevents the client // from sending the request body unless the server approves the request by sending // Expect100Continue. req.ServicePoint.Expect100Continue = false; #endif return req; } #endregion } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Net; namespace Google.Apis.Authentication { /// <summary> /// Use the Create method to create HttpWebRequests given a Uri. /// </summary> public class HttpRequestFactory : ICreateHttpRequest { #region ICreateHttpRequest Members public HttpWebRequest Create(Uri target, string method) { var req = WebRequest.Create(target) as HttpWebRequest; req.Method = method; // Turn off Expect100Continue behavior. For web method calls it is not used // and many servers reject the request if this is present on PUT or POST // requests with a body present. If used, Expect100Continue prevents the client // from sending the request body unless the server approves the request by sending // Expect100Continue. req.ServicePoint.Expect100Continue = false; return req; } #endregion } }
apache-2.0
C#
0083003324cbf1e980240b8dde6cc73553987840
Update AssemblyInfo.
ogaudefroy/WebFormsRouteUnitTester
WebFormsRouteUnitTester.Tests/Properties/AssemblyInfo.cs
WebFormsRouteUnitTester.Tests/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WebFormsRouteUnitTester.Tests")] [assembly: AssemblyDescription("WebFormsRouteUnitTester unit tests assembly")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Olivier GAUDEFROY")] [assembly: AssemblyProduct("WebFormsRouteUnitTester.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("643d5802-e934-40e5-95a8-f43ca17d5454")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WebFormsRouteUnitTester.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebFormsRouteUnitTester.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("643d5802-e934-40e5-95a8-f43ca17d5454")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
902faa90f9c61be32eb4a93555a6e2bbba283115
Update Index.cshtml
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Home/Index.cshtml
Anlab.Mvc/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> Update posted: August 3, 2021<br /><br /> <strong>New Methods Under Development</strong><br /><br /> Crude Fiber<br /> Crude Fate by Acid Hydrolysis<br /> Expected to be offered mid September, 2021 </div> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p> <p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and waste water, and feed in support of agricultural and environmental research.</p> <p>For new clients, please note the drop-down menu under “Lab Information” which contains an “Order Completion Help” section to help guide you in creating a work order. Also helpful under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides brief descriptions of our current methods.</p> <p>Please feel free to contact the lab with any questions.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> <p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br> Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p> </address> <p><a href="/media/pdf/UC-Davis-Analytical-Laboratory-Handout.pdf" target="_blank" title="Anlab Flyer"><div><img src="~/Images/AnlabFlyerThumb.png"/><br/>Lab Flyer</div> </a></p> </div>
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p> <p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and waste water, and feed in support of agricultural and environmental research.</p> <p>For new clients, please note the drop-down menu under “Lab Information” which contains an “Order Completion Help” section to help guide you in creating a work order. Also helpful under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides brief descriptions of our current methods.</p> <p>Please feel free to contact the lab with any questions.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> <p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br> Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p> </address> <p><a href="/media/pdf/UC-Davis-Analytical-Laboratory-Handout.pdf" target="_blank" title="Anlab Flyer"><div><img src="~/Images/AnlabFlyerThumb.png"/><br/>Lab Flyer</div> </a></p> </div>
mit
C#
756ee3b19a21ecae9cbd0b18b4267cda21216071
Simplify EndParser
smbecker/Eto.Parse,ArsenShnurkov/Eto.Parse,ArsenShnurkov/Eto.Parse,picoe/Eto.Parse,smbecker/Eto.Parse,picoe/Eto.Parse
Eto.Parse/Parsers/EndParser.cs
Eto.Parse/Parsers/EndParser.cs
using System; using Eto.Parse; using System.Collections.Generic; namespace Eto.Parse.Parsers { public class EndParser : Parser { protected EndParser(EndParser other) : base(other) { } public EndParser() { } protected override ParseMatch InnerParse(ParseArgs args) { if (args.Scanner.IsEnd) return args.EmptyMatch; else return args.NoMatch; } public override IEnumerable<NamedParser> Find(string parserId) { yield break; } public override Parser Clone() { return new EndParser(this); } } }
using System; using Eto.Parse; using System.Collections.Generic; namespace Eto.Parse.Parsers { public class EndParser : Parser { protected EndParser(EndParser other) : base(other) { } public EndParser() { } protected override ParseMatch InnerParse(ParseArgs args) { if (args.Scanner.IsEnd) return args.EmptyMatch; long offset = args.Offset; if (!args.Scanner.Read()) return args.EmptyMatch; args.Offset = offset; return args.NoMatch; } public override IEnumerable<NamedParser> Find(string parserId) { yield break; } public override Parser Clone() { return new EndParser(this); } } }
mit
C#
73b46e85418e1789adf4656598e529c6cd5d0cd9
sort and comment
CosmosOS/XSharp,CosmosOS/XSharp,CosmosOS/XSharp
source/XSharp.x86/OpCode.cs
source/XSharp.x86/OpCode.cs
using System; using System.Collections.Generic; using System.Text; namespace XSharp.x86 { // http://ref.x86asm.net/coder32-abc.html // http://ref.x86asm.net/coder32.html // http://www.sandpile.org/ // https://en.wikipedia.org/wiki/X86_instruction_listings // // Mulitbyte NOPs // https://software.intel.com/en-us/forums/watercooler-catchall/topic/307174 // https://reverseengineering.stackexchange.com/questions/11971/nop-with-argument-in-x86-64 // http://www.felixcloutier.com/x86/NOP.html // https://stackoverflow.com/questions/4798356/amd64-nopw-assembly-instruction // http://john.freml.in/amd64-nopl - Jump targets aligned on 16 byte boundaries // https://sites.google.com/site/paulclaytonplace/andy-glew-s-comparch-wiki/hint-instructions - Generic, Intel doesnt appear to have hints // Please add ops in alphabetical order public enum OpCode { Mov, NOP, PopAD, PushAD, Ret } }
using System; using System.Collections.Generic; using System.Text; namespace XSharp.x86 { // http://ref.x86asm.net/coder32-abc.html // http://ref.x86asm.net/coder32.html // http://www.sandpile.org/ // https://en.wikipedia.org/wiki/X86_instruction_listings // // Mulitbyte NOPs // https://software.intel.com/en-us/forums/watercooler-catchall/topic/307174 // https://reverseengineering.stackexchange.com/questions/11971/nop-with-argument-in-x86-64 // http://www.felixcloutier.com/x86/NOP.html // https://stackoverflow.com/questions/4798356/amd64-nopw-assembly-instruction // http://john.freml.in/amd64-nopl - Jump targets aligned on 16 byte boundaries // https://sites.google.com/site/paulclaytonplace/andy-glew-s-comparch-wiki/hint-instructions - Generic, Intel doesnt appear to have hints public enum OpCode { Mov, NOP, PushAD, PopAD, Ret } }
bsd-3-clause
C#
ccac1e878ba487247540012aed72166cdecfce42
Update ServiceCollectionExtensions.cs
Drawaes/CondenserDotNet,deanshackley/CondenserDotNet
src/CondenserDotNet.Client/ServiceCollectionExtensions.cs
src/CondenserDotNet.Client/ServiceCollectionExtensions.cs
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using CondenserDotNet.Client.Leadership; using CondenserDotNet.Client.Services; using Microsoft.Extensions.DependencyInjection; namespace CondenserDotNet.Client { public static class ServiceCollectionExtensions { public static IServiceCollection AddConsulServices(this IServiceCollection self) { self.AddSingleton<Func<HttpClient>>(() => new HttpClient() { BaseAddress = new Uri($"http://localhost:8500") }); self.AddSingleton<ILeaderRegistry, LeaderRegistry>(); self.AddSingleton<IServiceRegistry,ServiceRegistry>(); self.AddSingleton<IServiceManager, ServiceManager>(); return self; } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using CondenserDotNet.Client.Leadership; using CondenserDotNet.Client.Services; using Microsoft.Extensions.DependencyInjection; namespace CondenserDotNet.Client { public static class ServiceCollectionExtensions { public static IServiceCollection AddConsulServices(this IServiceCollection self) { self.AddSingleton<Func<HttpClient>>(() => new HttpClient() { BaseAddress = new Uri($"http://localhost:8500") }); self.AddSingleton<ILeaderRegistry>(); self.AddSingleton<IServiceRegistry,ServiceRegistry>(); self.AddSingleton<IServiceManager, ServiceManager>(); return self; } } }
mit
C#
5f6a38cc0a194a33c7a5c7e3f39573bf8c63f6ac
Destroy bullets when they are out of bounds
ramingar/fasteroid
Assets/scripts/Bullet.cs
Assets/scripts/Bullet.cs
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { private float velocity = 35f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this.transform.Translate(0, Time.deltaTime * this.velocity, 0, Space.Self); // Destroy the bullet when it is out of bounds of screen if (isOutOfScreen()) { Destroy(this.gameObject); } } private bool isOutOfScreen () { Vector3 posbullet = Camera.main.WorldToScreenPoint(this.gameObject.transform.position); float screenWidth = Camera.main.pixelWidth; float screenHeight = Camera.main.pixelHeight; if (posbullet.x < 0 || posbullet.x > screenWidth || posbullet.y < 0 || posbullet.y > screenHeight ) { return true; } return false; } }
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { private float velocity = 35f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this.transform.Translate(0, Time.deltaTime * this.velocity, 0, Space.Self); } }
mit
C#
386a939f1fedd8d144ada055178fbbd552a29309
Fix compile error : ReadLines() is not available in Unity
tigrouind/AITD-roomviewer
Assets/Scripts/VarParser.cs
Assets/Scripts/VarParser.cs
using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class VarParser { readonly Dictionary<string, Dictionary<int, string>> sections = new Dictionary<string, Dictionary<int, string>>(); public string GetText(string sectionName, int value) { Dictionary<int, string> section; if (sections.TryGetValue(sectionName, out section)) { string text; if(section.TryGetValue(value, out text)) { return text; } } return string.Empty; } public void Parse(string filePath) { var allLines = System.IO.File.ReadAllLines(filePath); Regex section = new Regex("^[A-Z](.*)$"); Regex item = new Regex("^(?<linenumber>[0-9]+)(-(?<next>[0-9]+))?(?<text>.*)"); Dictionary<int, string> currentSection = null; foreach (string line in allLines) { //check if new section Match sectionMatch = section.Match(line); if (sectionMatch.Success) { currentSection = new Dictionary<int, string>(); sections.Add(sectionMatch.Value.Trim(), currentSection); } else if (currentSection != null) { //parse line if inside section Match itemMatch = item.Match(line); if (itemMatch.Success) { int lineNumber = int.Parse(itemMatch.Groups["linenumber"].Value); string nextNumberString = itemMatch.Groups["next"].Value.Trim(); int nextNumber; if (!string.IsNullOrEmpty(nextNumberString)) { nextNumber = int.Parse(nextNumberString); } else { nextNumber = lineNumber; } string text = itemMatch.Groups["text"].Value.Trim(); if (!string.IsNullOrEmpty(text)) { for(int i = lineNumber; i <= nextNumber ; i++) { currentSection[i] = text; } } } } } } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class VarParser { readonly Dictionary<string, Dictionary<int, string>> sections = new Dictionary<string, Dictionary<int, string>>(); public string GetText(string sectionName, int value) { Dictionary<int, string> section; if (sections.TryGetValue(sectionName, out section)) { string text; if(section.TryGetValue(value, out text)) { return text; } } return string.Empty; } public void Parse(string filePath) { var allLines = System.IO.File.ReadLines(filePath); Regex section = new Regex("^[A-Z](.*)$"); Regex item = new Regex("^(?<linenumber>[0-9]+)(-(?<next>[0-9]+))?(?<text>.*)"); Dictionary<int, string> currentSection = null; foreach (string line in allLines) { //check if new section Match sectionMatch = section.Match(line); if (sectionMatch.Success) { currentSection = new Dictionary<int, string>(); sections.Add(sectionMatch.Value.Trim(), currentSection); } else if (currentSection != null) { //parse line if inside section Match itemMatch = item.Match(line); if (itemMatch.Success) { int lineNumber = int.Parse(itemMatch.Groups["linenumber"].Value); string nextNumberString = itemMatch.Groups["next"].Value.Trim(); int nextNumber; if (!string.IsNullOrEmpty(nextNumberString)) { nextNumber = int.Parse(nextNumberString); } else { nextNumber = lineNumber; } string text = itemMatch.Groups["text"].Value.Trim(); if (!string.IsNullOrEmpty(text)) { for(int i = lineNumber; i <= nextNumber ; i++) { currentSection[i] = text; } } } } } } }
mit
C#
9f8c7994db5698dc37f887d5195ebf069717ba22
change layer
JackCeparou/JackCeparouCompass
Decorators/SoundAlertDecorator.cs
Decorators/SoundAlertDecorator.cs
namespace Turbo.Plugins.Jack.Decorators { using System; using System.Collections.Generic; using Turbo.Plugins.Default; using Turbo.Plugins.Jack.TextToSpeech; public class SoundAlertDecorator<T> : IWorldDecorator where T : IActor { public bool Enabled { get; set; } public IController Hud { get; private set; } public WorldLayer Layer { get; private set; } public SoundAlert<T> SoundAlert { get; private set; } public SoundAlertDecorator() { Enabled = true; } public SoundAlertDecorator(IController hud) { Hud = hud; Enabled = true; Layer = WorldLayer.Map; } public SoundAlertDecorator(IController hud, SoundAlert<T> soundAlert = null) : this(hud) { SoundAlert = soundAlert ?? new SoundAlert<T>() { TextFunc = (actor) => actor.SnoActor.NameLocalized }; } public void Paint(IActor actor, IWorldCoordinate coord, string text) { if (!Enabled) return; if (actor == null) return; SoundAlertManagerPlugin.Register<T>(actor, SoundAlert); } public IEnumerable<ITransparent> GetTransparents() { yield break; } } }
namespace Turbo.Plugins.Jack.Decorators { using System; using System.Collections.Generic; using Turbo.Plugins.Default; using Turbo.Plugins.Jack.TextToSpeech; public class SoundAlertDecorator<T> : IWorldDecorator where T : IActor { public bool Enabled { get; set; } public IController Hud { get; private set; } public WorldLayer Layer { get; private set; } public SoundAlert<T> SoundAlert { get; private set; } public SoundAlertDecorator() { Enabled = true; } public SoundAlertDecorator(IController hud) { Hud = hud; Enabled = true; Layer = WorldLayer.Ground; } public SoundAlertDecorator(IController hud, SoundAlert<T> soundAlert = null) : this(hud) { SoundAlert = soundAlert ?? new SoundAlert<T>() { TextFunc = (actor) => actor.SnoActor.NameLocalized }; } public void Paint(IActor actor, IWorldCoordinate coord, string text) { if (!Enabled) return; if (actor == null) return; SoundAlertManagerPlugin.Register<T>(actor, SoundAlert); } public IEnumerable<ITransparent> GetTransparents() { yield break; } } }
mit
C#
c4940ff0d0a64bc99dabcebaf08a2631ca4aa2a9
Remove pragma header when caching
dolly22/VersionedAssets
src/AspNetCore.VersionedAssets/VersionedAssetsClientCaching.cs
src/AspNetCore.VersionedAssets/VersionedAssetsClientCaching.cs
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Net.Http.Headers; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AspNetCore.VersionedAssets { public class VersionedAssetsClientCaching { static readonly DateTime expiresNoCache = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); readonly VersionedAssetsCaching cachingOptions; public VersionedAssetsClientCaching(VersionedAssetsCaching cachingOptions) { if (cachingOptions == null) throw new ArgumentNullException(nameof(cachingOptions)); this.cachingOptions = cachingOptions; } public void ApplyResponseHeaders(HttpContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var assetInfo = context.Features.Get<IAssetInfoFeature>(); if (assetInfo == null) return; var headers = context.Response.GetTypedHeaders(); if (assetInfo.UrlHashMatched) { // apply caching headers headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue { Public = cachingOptions.Public, MaxAge = cachingOptions.MaxAge }; headers.Append(HeaderNames.Vary, "Accept-Encoding"); headers.Headers.Remove(HeaderNames.Pragma); } else { // set no cache headers headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue { MustRevalidate = true, NoCache = true, NoStore = true }; headers.Expires = expiresNoCache; headers.Append(HeaderNames.Pragma, "no-cache"); } } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AspNetCore.VersionedAssets { public class VersionedAssetsClientCaching { static readonly DateTime expiresNoCache = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); readonly VersionedAssetsCaching cachingOptions; public VersionedAssetsClientCaching(VersionedAssetsCaching cachingOptions) { if (cachingOptions == null) throw new ArgumentNullException(nameof(cachingOptions)); this.cachingOptions = cachingOptions; } public void ApplyResponseHeaders(HttpContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var assetInfo = context.Features.Get<IAssetInfoFeature>(); if (assetInfo == null) return; var headers = context.Response.GetTypedHeaders(); if (assetInfo.UrlHashMatched) { // apply caching headers headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue { Public = cachingOptions.Public, MaxAge = cachingOptions.MaxAge }; headers.Append("Vary", "Accept-Encoding"); } else { // set no cache headers headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue { MustRevalidate = true, NoCache = true, NoStore = true }; headers.Expires = expiresNoCache; headers.Append("Pragma", "no-cache"); } } } }
apache-2.0
C#
94ac823edfd106e2af5c96c55b81fdd2e2e53aa4
Add copyright notice to new file
nkolev92/sdk,nkolev92/sdk
test/Microsoft.NET.TestFramework/CommandExtensions.cs
test/Microsoft.NET.TestFramework/CommandExtensions.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.DotNet.Cli.Utils; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Microsoft.NET.TestFramework.Assertions; namespace Microsoft.NET.TestFramework { public static class CommandExtensions { public static ICommand EnsureExecutable(this ICommand command) { // Workaround for https://github.com/NuGet/Home/issues/4424 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Command.Create("chmod", new[] { "755", command.CommandName }) .Execute() .Should() .Pass(); } return command; } } }
using FluentAssertions; using Microsoft.DotNet.Cli.Utils; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Microsoft.NET.TestFramework.Assertions; namespace Microsoft.NET.TestFramework { public static class CommandExtensions { public static ICommand EnsureExecutable(this ICommand command) { // Workaround for https://github.com/NuGet/Home/issues/4424 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Command.Create("chmod", new[] { "755", command.CommandName }) .Execute() .Should() .Pass(); } return command; } } }
mit
C#
e357dd973afce7530515e1400321f64bb2f98468
remove white spaces
DrabWeb/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,RedNesto/osu-framework,ppy/osu-framework,default0/osu-framework,smoogipooo/osu-framework,naoey/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,RedNesto/osu-framework,naoey/osu-framework,smoogipooo/osu-framework,default0/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework
osu.Framework/Graphics/Containers/SearchContainer.cs
osu.Framework/Graphics/Containers/SearchContainer.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; namespace osu.Framework.Graphics.Containers { public class SearchContainer : SearchContainer<Drawable> { } public class SearchContainer<T> : Container<T>, IFilterableChildren where T : Drawable { private string searchTerm; /// <summary> /// String to filter <see cref="IFilterable"/> /// </summary> public string SearchTerm { get { return searchTerm; } set { searchTerm = value; match(this); } } public IEnumerable<IFilterable> FilterableChildren => Children.OfType<IFilterable>(); public string[] Keywords => null; public bool FilteredByParent { get; set; } private bool match(IFilterable searchable, List<string> parentKeywords = null) { var searchContainer = searchable as IFilterableChildren; var keywords = new List<string>(searchable.Keywords ?? new string[0]); keywords.AddRange(parentKeywords ?? new string[0].ToList()); if (searchContainer != null) { bool matching = false; foreach(IFilterable searchableChildren in searchContainer.FilterableChildren) matching = match(searchableChildren, keywords) || matching; return searchContainer.FilteredByParent = matching; } else { return searchable.FilteredByParent = keywords.Any(keyword => keyword.IndexOf(SearchTerm, StringComparison.InvariantCultureIgnoreCase) >= 0); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; namespace osu.Framework.Graphics.Containers { public class SearchContainer : SearchContainer<Drawable> { } public class SearchContainer<T> : Container<T>, IFilterableChildren where T : Drawable { private string searchTerm; /// <summary> /// String to filter <see cref="IFilterable"/> /// </summary> public string SearchTerm { get { return searchTerm; } set { searchTerm = value; match(this); } } public IEnumerable<IFilterable> FilterableChildren => Children.OfType<IFilterable>(); public string[] Keywords => null; public bool FilteredByParent { get; set; } private bool match(IFilterable searchable, List<string> parentKeywords = null) { var searchContainer = searchable as IFilterableChildren; var keywords = new List<string>(searchable.Keywords ?? new string[0]); keywords.AddRange(parentKeywords ?? new string[0].ToList()); if (searchContainer != null) { bool matching = false; foreach(IFilterable searchableChildren in searchContainer.FilterableChildren) matching = match(searchableChildren, keywords) || matching; return searchContainer.FilteredByParent = matching; } else { return searchable.FilteredByParent = keywords.Any(keyword => keyword.IndexOf(SearchTerm, StringComparison.InvariantCultureIgnoreCase) >= 0); } } } }
mit
C#
2173f46a4678eb2c708be15ea2362030e845528e
Add missing licence header
UselessToucan/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,ZLima12/osu,smoogipooo/osu,UselessToucan/osu,johnneijzen/osu,2yangk23/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,ppy/osu
osu.Game.Tournament.Tests/TestCaseGroupingManager.cs
osu.Game.Tournament.Tests/TestCaseGroupingManager.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays.Settings; using osu.Game.Tournament.Screens.Ladder.Components; namespace osu.Game.Tournament.Tests { public class TestCaseGroupingManager : LadderTestCase { public TestCaseGroupingManager() { FillFlowContainer items; Add(items = new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.Both }); foreach (var g in Ladder.Groupings) items.Add(new GroupingRow(g)); } public class GroupingRow : CompositeDrawable { public readonly TournamentGrouping Grouping; public GroupingRow(TournamentGrouping grouping) { Grouping = grouping; InternalChildren = new Drawable[] { new FillFlowContainer { Direction = FillDirection.Horizontal, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsTextBox { Width = 0.4f, Bindable = Grouping.Name }, new SettingsTextBox { Width = 0.4f, Bindable = Grouping.Description }, } } }; RelativeSizeAxes = Axes.X; Height = 40; } } } }
using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays.Settings; using osu.Game.Tournament.Screens.Ladder.Components; namespace osu.Game.Tournament.Tests { public class TestCaseGroupingManager : LadderTestCase { public TestCaseGroupingManager() { FillFlowContainer items; Add(items = new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.Both }); foreach (var g in Ladder.Groupings) items.Add(new GroupingRow(g)); } public class GroupingRow : CompositeDrawable { public readonly TournamentGrouping Grouping; public GroupingRow(TournamentGrouping grouping) { Grouping = grouping; InternalChildren = new Drawable[] { new FillFlowContainer { Direction = FillDirection.Horizontal, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsTextBox { Width = 0.4f, Bindable = Grouping.Name }, new SettingsTextBox { Width = 0.4f, Bindable = Grouping.Description }, } } }; RelativeSizeAxes = Axes.X; Height = 40; } } } }
mit
C#
20df4b4c9aed12a1bb22aac2f7896f6569f01960
Fix syntax error in TimingController
Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
Assets/Microgames/_Bosses/YoumuSlash/Scripts/YoumuSlashTimingController.cs
Assets/Microgames/_Bosses/YoumuSlash/Scripts/YoumuSlashTimingController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class YoumuSlashTimingController : MonoBehaviour { public delegate void BeatDelegate(int beat); public static BeatDelegate onBeat; [SerializeField] private YoumuSlashTimingData timingData; [SerializeField] private float StartDelay = .5f; private AudioSource musicSource; private int lastInvokedBeat; private void Awake() { onBeat = null; musicSource = GetComponent<AudioSource>(); musicSource.clip = timingData.MusicClip; timingData.initiate(musicSource); } void Start() { AudioHelper.playScheduled(musicSource, StartDelay); lastInvokedBeat = -1; onBeat += checkForSongEnd; InvokeRepeating("callOnBeat", StartDelay, timingData.getBeatDuration()); } void callOnBeat() { lastInvokedBeat++; onBeat(lastInvokedBeat); } void checkForSongEnd(int beat) { print("Debug beat check"); if (lastInvokedBeat > 1 && !musicSource.isPlaying) CancelInvoke(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class YoumuSlashTimingController : MonoBehaviour { public delegate void BeatDelegate(int beat); public static BeatDelegate onBeat; [SerializeField] private YoumuSlashTimingData timingData; [SerializeField] private float StartDelay = .5f; private AudioSource musicSource; private int lastInvokedBeat; private void Awake() { onBeat = null; musicSource = GetComponent<AudioSource>(); musicSource.clip = timingData.MusicClip; timingData.initiate(musicSource); } void Start() { AudioHelper.playScheduled(musicSource, StartDelay); lastInvokedBeat = -1; onBeat += checkForSongEnd; InvokeRepeating("callOnBeat", StartDelay, timingData.getBeatDuration()); } void callOnBeat() { lastInvokedBeat++; onBeat(lastInvokedBeat); } void checkForSongEnd(int beat) print("Debug beat check"); if (lastInvokedBeat > 1 && !musicSource.isPlaying) CancelInvoke(); } }
mit
C#
74f1ed2effaa0d4c3731fdfaaf99b75968f8e5e5
Drop type constraints on EnumExtensions methods
smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework/Extensions/EnumExtensions/EnumExtensions.cs
osu.Framework/Extensions/EnumExtensions/EnumExtensions.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Utils; namespace osu.Framework.Extensions.EnumExtensions { public static class EnumExtensions { /// <summary> /// Get values of an enum in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>() { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException($"{typeof(T)} must be an enum"); IEnumerable<T> items = (T[])Enum.GetValues(type); return GetValuesInOrder(items); } /// <summary> /// Get values of a collection of enum values in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>(this IEnumerable<T> items) { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException($"{typeof(T)} must be an enum"); if (!(Attribute.GetCustomAttribute(type, typeof(HasOrderedElementsAttribute)) is HasOrderedElementsAttribute orderedAttr)) return items; return items.OrderBy(i => { var fieldInfo = type.GetField(i.ToString()); if (fieldInfo?.GetCustomAttributes(typeof(OrderAttribute), false).FirstOrDefault() is OrderAttribute attr) return attr.Order; if (orderedAttr.AllowPartialOrdering) return Convert.ToInt32(i); throw new ArgumentException($"Not all values of {typeof(T)} have {nameof(OrderAttribute)} specified."); }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Utils; namespace osu.Framework.Extensions.EnumExtensions { public static class EnumExtensions { /// <summary> /// Get values of an enum in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>() where T : struct, Enum { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException($"{typeof(T)} must be an enum"); IEnumerable<T> items = (T[])Enum.GetValues(type); return GetValuesInOrder(items); } /// <summary> /// Get values of a collection of enum values in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>(this IEnumerable<T> items) where T : struct, Enum { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException($"{typeof(T)} must be an enum"); if (!(Attribute.GetCustomAttribute(type, typeof(HasOrderedElementsAttribute)) is HasOrderedElementsAttribute orderedAttr)) return items; return items.OrderBy(i => { var fieldInfo = type.GetField(i.ToString()); if (fieldInfo?.GetCustomAttributes(typeof(OrderAttribute), false).FirstOrDefault() is OrderAttribute attr) return attr.Order; if (orderedAttr.AllowPartialOrdering) return Convert.ToInt32(i); throw new ArgumentException($"Not all values of {typeof(T)} have {nameof(OrderAttribute)} specified."); }); } } }
mit
C#
6ee88179945a62be11e081f35d92dbdc3e91f97e
Improve code documentation in the OpenChain.Abstractions project
openchain/openchain
src/Openchain.Abstractions/ITransactionStore.cs
src/Openchain.Abstractions/ITransactionStore.cs
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Openchain { /// <summary> /// Represents a data store for key-value pairs. /// </summary> public interface ITransactionStore { /// <summary> /// Adds a transaction to the store. /// </summary> /// <param name="transactions">A collection of serialized <see cref="Transaction"/> to add to the store.</param> /// <exception cref="ConcurrentMutationException">A record has been mutated and the transaction is no longer valid.</exception> /// <returns>The task object representing the asynchronous operation.</returns> Task AddTransactions(IEnumerable<ByteString> transactions); /// <summary> /// Gets the current records for a set of keys. /// </summary> /// <param name="keys">The keys to query.</param> /// <returns>The task object representing the asynchronous operation.</returns> Task<IList<Record>> GetRecords(IEnumerable<ByteString> keys); /// <summary> /// Gets the hash of the last transaction in the ledger. /// </summary> /// <returns>The task object representing the asynchronous operation.</returns> Task<ByteString> GetLastTransaction(); /// <summary> /// Gets the transactions following the one whose hash has been provided. /// </summary> /// <param name="from">The hash of the transaction to start streaming from.</param> /// <returns>An observable representing the transaction stream.</returns> IObservable<ByteString> GetTransactionStream(ByteString from); } }
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Openchain { /// <summary> /// Represents a data store for key-value pairs. /// </summary> public interface ITransactionStore { /// <summary> /// Adds a transaction to the store. /// </summary> /// <param name="transactions">A collection of serialized <see cref="Transaction"/> to add to the store.</param> /// <exception cref="ConcurrentMutationException">A record has been mutated and the transaction is no longer valid.</exception> /// <returns>A task that represents the completion of the operation.</returns> Task AddTransactions(IEnumerable<ByteString> transactions); /// <summary> /// Gets the current records for a set of keys. /// </summary> /// <param name="keys">The keys to query.</param> /// <returns>A task that represents the completion of the operation and contains a list of the corresponding <see cref="Record"/>.</returns> Task<IList<Record>> GetRecords(IEnumerable<ByteString> keys); /// <summary> /// Gets the hash of the last transaction in the ledger. /// </summary> /// <returns>A task that represents the completion of the operation and contains the hash of the last transaction.</returns> Task<ByteString> GetLastTransaction(); /// <summary> /// Gets the transactions following the one whose hash has been provided. /// </summary> /// <param name="from">The hash of the transaction to start streaming from.</param> /// <returns>An observable representing the transaction stream.</returns> IObservable<ByteString> GetTransactionStream(ByteString from); } }
apache-2.0
C#
b05b1de99ac8b70d84aa309d32cd256bc8417acc
fix silly
paveltimofeev/UnityDictionary
UnityDictionary.cs
UnityDictionary.cs
#if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; using System.Collections.Generic; using System; [Serializable] public class UnityDictionary<TKey,TValue> { [SerializeField] private List<TKey> _keys = new List<TKey>(); [SerializeField] private List<TValue> _values = new List<TValue>(); private Dictionary<TKey,TValue> _cache; public void Add(TKey key, TValue value) { if (_cache == null) BuildCache(); _cache.Add(key,value); _keys.Add(key); _values.Add(value); } public TValue this[TKey key] { get { if (_cache == null) BuildCache(); return _cache[key]; } } void BuildCache() { _cache = new Dictionary<TKey,TValue>(); for (int i=0; i!=_keys.Count; i++) { _cache.Add(_keys[i],_values[i]); } } } //Unfortunately, Unity currently doesn't serialize UnityDictionary<int,string>, but it will serialize a dummy subclass of that. [Serializable] public class UnityDictionaryIntString : UnityDictionary<int,string> {} /* //TODO: implement the propertydrawer, and figure out how to make it so you dont need to have one per dummy subclass. #if UNITY_EDITOR [CustomPropertyDrawer(typeof(UnityDictionaryIntString))] public class UnityDictionaryDrawer : PropertyDrawer { override public void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty (position, label, property); //todo: put nice drawing code here EditorGUI.EndProperty (); } } #endif */
#if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; using System.Collections.Generic; using System; [Serializable] public class UnityDictionary<TKey,TValue> { [SerializeField] private List<TKey> _keys = new List<TKey>(); [SerializeField] private List<TValue> _values = new List<TValue>(); private Dictionary<TKey,TValue> _cache; public void Add(TKey key, TValue value) { if (_cache != null) BuildCache(); _cache.Add(key,value); _keys.Add(key); _values.Add(value); } public TValue this[TKey key] { get { if (_cache != null) BuildCache(); return _cache[key]; } } void BuildCache() { _cache = new Dictionary<TKey,TValue>(); for (int i=0; i!=_keys.Count; i++) { _cache.Add(_keys[i],_values[i]); } } } //Unfortunately, Unity currently doesn't serialize UnityDictionary<int,string>, but it will serialize a dummy subclass of that. [Serializable] public class UnityDictionaryIntString : UnityDictionary<int,string> {} /* //TODO: implement the propertydrawer, and figure out how to make it so you dont need to have one per dummy subclass. #if UNITY_EDITOR [CustomPropertyDrawer(typeof(UnityDictionaryIntString))] public class UnityDictionaryDrawer : PropertyDrawer { override public void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty (position, label, property); //todo: put nice drawing code here EditorGUI.EndProperty (); } } #endif */
mit
C#
1e29744190ff2775b06d7ba083e0d9ffd8ed5def
fix issue with camera orientation
unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter
AlembicImporter/Assets/AlembicImporter/Scripts/AlembicCamera.cs
AlembicImporter/Assets/AlembicImporter/Scripts/AlembicCamera.cs
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif [ExecuteInEditMode] public class AlembicCamera : AlembicElement { public AbcAPI.aiAspectRatioModeOverride m_aspectRatioMode = AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting; Camera m_camera; AbcAPI.aiCameraData m_abcData; public override void AbcSetup(AlembicStream abcStream, AbcAPI.aiObject abcObj, AbcAPI.aiSchema abcSchema) { base.AbcSetup(abcStream, abcObj, abcSchema); m_camera = GetOrAddComponent<Camera>(); } public override void AbcGetConfig(ref AbcAPI.aiConfig config) { if (m_aspectRatioMode != AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting) { config.aspectRatio = AbcAPI.GetAspectRatio((AbcAPI.aiAspectRatioMode) m_aspectRatioMode); } } public override void AbcSampleUpdated(AbcAPI.aiSample sample, bool topologyChanged) { AbcAPI.aiCameraGetData(sample, ref m_abcData); AbcDirty(); } public override void AbcUpdate() { if (AbcIsDirty()) { m_trans.forward = -m_trans.parent.forward; m_camera.fieldOfView = m_abcData.fieldOfView; m_camera.nearClipPlane = m_abcData.nearClippingPlane; m_camera.farClipPlane = m_abcData.farClippingPlane; // no use for focusDistance and focalLength yet (could be usefull for DoF component) AbcClean(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif [ExecuteInEditMode] public class AlembicCamera : AlembicElement { public AbcAPI.aiAspectRatioModeOverride m_aspectRatioMode = AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting; Camera m_camera; AbcAPI.aiCameraData m_abcData; public override void AbcSetup(AlembicStream abcStream, AbcAPI.aiObject abcObj, AbcAPI.aiSchema abcSchema) { base.AbcSetup(abcStream, abcObj, abcSchema); m_camera = GetOrAddComponent<Camera>(); } public override void AbcGetConfig(ref AbcAPI.aiConfig config) { if (m_aspectRatioMode != AbcAPI.aiAspectRatioModeOverride.InheritStreamSetting) { config.aspectRatio = AbcAPI.GetAspectRatio((AbcAPI.aiAspectRatioMode) m_aspectRatioMode); } } public override void AbcSampleUpdated(AbcAPI.aiSample sample, bool topologyChanged) { AbcAPI.aiCameraGetData(sample, ref m_abcData); AbcDirty(); } public override void AbcUpdate() { if (AbcIsDirty()) { m_trans.parent.forward = -m_trans.parent.forward; m_camera.fieldOfView = m_abcData.fieldOfView; m_camera.nearClipPlane = m_abcData.nearClippingPlane; m_camera.farClipPlane = m_abcData.farClippingPlane; // no use for focusDistance and focalLength yet (could be usefull for DoF component) AbcClean(); } } }
mit
C#
5e76d4bfc1038fcd128a131522b0e2f6014084df
remove template max length in pos app
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer/Models/AppViewModels/UpdatePointOfSaleViewModel.cs
BTCPayServer/Models/AppViewModels/UpdatePointOfSaleViewModel.cs
using System.ComponentModel.DataAnnotations; namespace BTCPayServer.Models.AppViewModels { public class UpdatePointOfSaleViewModel { [Required] [MaxLength(30)] public string Title { get; set; } [Required] [MaxLength(5)] public string Currency { get; set; } public string Template { get; set; } [Display(Name = "Enable shopping cart")] public bool EnableShoppingCart { get; set; } [Display(Name = "User can input custom amount")] public bool ShowCustomAmount { get; set; } [Display(Name = "User can input discount in %")] public bool ShowDiscount { get; set; } [Display(Name = "Enable tips")] public bool EnableTips { get; set; } public string Example1 { get; internal set; } public string Example2 { get; internal set; } public string ExampleCallback { get; internal set; } public string InvoiceUrl { get; internal set; } [Required] [MaxLength(30)] [Display(Name = "Text to display on each buttons for items with a specific price")] public string ButtonText { get; set; } [Required] [MaxLength(30)] [Display(Name = "Text to display on buttons next to the input allowing the user to enter a custom amount")] public string CustomButtonText { get; set; } [Required] [MaxLength(30)] [Display(Name = "Text to display in the tip input")] public string CustomTipText { get; set; } [MaxLength(30)] [Display(Name = "Tip percentage amounts (comma separated)")] public string CustomTipPercentages { get; set; } [MaxLength(500)] [Display(Name = "Custom bootstrap CSS file")] public string CustomCSSLink { get; set; } public string Id { get; set; } } }
using System.ComponentModel.DataAnnotations; namespace BTCPayServer.Models.AppViewModels { public class UpdatePointOfSaleViewModel { [Required] [MaxLength(30)] public string Title { get; set; } [Required] [MaxLength(5)] public string Currency { get; set; } [MaxLength(5000)] public string Template { get; set; } [Display(Name = "Enable shopping cart")] public bool EnableShoppingCart { get; set; } [Display(Name = "User can input custom amount")] public bool ShowCustomAmount { get; set; } [Display(Name = "User can input discount in %")] public bool ShowDiscount { get; set; } [Display(Name = "Enable tips")] public bool EnableTips { get; set; } public string Example1 { get; internal set; } public string Example2 { get; internal set; } public string ExampleCallback { get; internal set; } public string InvoiceUrl { get; internal set; } [Required] [MaxLength(30)] [Display(Name = "Text to display on each buttons for items with a specific price")] public string ButtonText { get; set; } [Required] [MaxLength(30)] [Display(Name = "Text to display on buttons next to the input allowing the user to enter a custom amount")] public string CustomButtonText { get; set; } [Required] [MaxLength(30)] [Display(Name = "Text to display in the tip input")] public string CustomTipText { get; set; } [MaxLength(30)] [Display(Name = "Tip percentage amounts (comma separated)")] public string CustomTipPercentages { get; set; } [MaxLength(500)] [Display(Name = "Custom bootstrap CSS file")] public string CustomCSSLink { get; set; } public string Id { get; set; } } }
mit
C#
1baddb08b895044db4a5f291f41a56f04e94055c
Make PeerWithPersistenceInfo's members readonly
Abc-Arbitrage/Zebus,biarne-a/Zebus
src/Abc.Zebus/Transport/PeerWithPersistenceInfo.cs
src/Abc.Zebus/Transport/PeerWithPersistenceInfo.cs
namespace Abc.Zebus.Transport { public struct PeerWithPersistenceInfo { public readonly Peer Peer; public readonly bool WasPersisted; public PeerWithPersistenceInfo(Peer peer, bool wasPersisted) { Peer = peer; WasPersisted = wasPersisted; } } }
namespace Abc.Zebus.Transport { public struct PeerWithPersistenceInfo { public Peer Peer; public bool WasPersisted; public PeerWithPersistenceInfo(Peer peer, bool wasPersisted) { Peer = peer; WasPersisted = wasPersisted; } } }
mit
C#
969fd1f6aab6b006b4ac3e782bc6cc790e40f980
Annotate implementations of IDiscardSymbol
reaction1989/roslyn,abock/roslyn,brettfo/roslyn,agocke/roslyn,eriawan/roslyn,dotnet/roslyn,tannergooding/roslyn,tmat/roslyn,reaction1989/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,KevinRansom/roslyn,diryboy/roslyn,KirillOsenkov/roslyn,physhi/roslyn,weltkante/roslyn,tmat/roslyn,eriawan/roslyn,KevinRansom/roslyn,dotnet/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,sharwell/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,davkean/roslyn,dotnet/roslyn,stephentoub/roslyn,sharwell/roslyn,heejaechang/roslyn,tannergooding/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,stephentoub/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,davkean/roslyn,gafter/roslyn,stephentoub/roslyn,genlu/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,genlu/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,jmarolf/roslyn,diryboy/roslyn,agocke/roslyn,KevinRansom/roslyn,tannergooding/roslyn,heejaechang/roslyn,aelij/roslyn,agocke/roslyn,shyamnamboodiripad/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,brettfo/roslyn,weltkante/roslyn,physhi/roslyn,abock/roslyn,gafter/roslyn,weltkante/roslyn,mavasani/roslyn,aelij/roslyn,tmat/roslyn,eriawan/roslyn,physhi/roslyn,abock/roslyn,wvdd007/roslyn,aelij/roslyn,AmadeusW/roslyn,diryboy/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn
src/Compilers/CSharp/Portable/Symbols/DiscardSymbol.cs
src/Compilers/CSharp/Portable/Symbols/DiscardSymbol.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #nullable enable using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class DiscardSymbol : Symbol, IDiscardSymbol { public DiscardSymbol(TypeWithAnnotations typeWithAnnotations) { Debug.Assert(typeWithAnnotations.Type is object); TypeWithAnnotations = typeWithAnnotations; } ITypeSymbol IDiscardSymbol.Type => TypeWithAnnotations.Type; CodeAnalysis.NullableAnnotation IDiscardSymbol.NullableAnnotation => TypeWithAnnotations.ToPublicAnnotation(); public TypeWithAnnotations TypeWithAnnotations { get; } public override Symbol? ContainingSymbol => null; public override Accessibility DeclaredAccessibility => Accessibility.NotApplicable; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsAbstract => false; public override bool IsExtern => false; public override bool IsImplicitlyDeclared => true; public override bool IsOverride => false; public override bool IsSealed => false; public override bool IsStatic => false; public override bool IsVirtual => false; public override SymbolKind Kind => SymbolKind.Discard; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; internal override ObsoleteAttributeData? ObsoleteAttributeData => null; internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a) => visitor.VisitDiscard(this, a); public override void Accept(SymbolVisitor visitor) => visitor.VisitDiscard(this); [return: MaybeNull] public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { #pragma warning disable CS8717 // A member returning a [MaybeNull] value introduces a null value when 'TResult' is a non-nullable reference type. return visitor.VisitDiscard(this); #pragma warning restore CS8717 // A member returning a [MaybeNull] value introduces a null value when 'TResult' is a non-nullable reference type. } public override void Accept(CSharpSymbolVisitor visitor) => visitor.VisitDiscard(this); public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) => visitor.VisitDiscard(this); public override bool Equals(Symbol? obj, TypeCompareKind compareKind) => obj is DiscardSymbol other && this.TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); public override int GetHashCode() => this.TypeWithAnnotations.GetHashCode(); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class DiscardSymbol : Symbol, IDiscardSymbol { public DiscardSymbol(TypeWithAnnotations typeWithAnnotations) { Debug.Assert(typeWithAnnotations.Type is object); TypeWithAnnotations = typeWithAnnotations; } ITypeSymbol IDiscardSymbol.Type => TypeWithAnnotations.Type; CodeAnalysis.NullableAnnotation IDiscardSymbol.NullableAnnotation => TypeWithAnnotations.ToPublicAnnotation(); public TypeWithAnnotations TypeWithAnnotations { get; } public override Symbol ContainingSymbol => null; public override Accessibility DeclaredAccessibility => Accessibility.NotApplicable; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsAbstract => false; public override bool IsExtern => false; public override bool IsImplicitlyDeclared => true; public override bool IsOverride => false; public override bool IsSealed => false; public override bool IsStatic => false; public override bool IsVirtual => false; public override SymbolKind Kind => SymbolKind.Discard; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; internal override ObsoleteAttributeData ObsoleteAttributeData => null; internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a) => visitor.VisitDiscard(this, a); public override void Accept(SymbolVisitor visitor) => visitor.VisitDiscard(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitDiscard(this); public override void Accept(CSharpSymbolVisitor visitor) => visitor.VisitDiscard(this); public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) => visitor.VisitDiscard(this); public override bool Equals(Symbol obj, TypeCompareKind compareKind) => obj is DiscardSymbol other && this.TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); public override int GetHashCode() => this.TypeWithAnnotations.GetHashCode(); } }
mit
C#
69f13017e7b8fa35dff21ef4de71c1a1f2245dcc
Remove log output
LMNRY/SetProperty,bsn069/SetProperty
Editor/SetPropertyDrawer.cs
Editor/SetPropertyDrawer.cs
// Copyright (c) 2014 Luminary LLC // Licensed under The MIT License (See LICENSE for full text) using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Reflection; [CustomPropertyDrawer(typeof(SetPropertyAttribute))] public class SetPropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // Rely on the default inspector GUI EditorGUI.BeginChangeCheck (); EditorGUI.PropertyField(position, property, label); // Update only when necessary SetPropertyAttribute setProperty = attribute as SetPropertyAttribute; if (EditorGUI.EndChangeCheck()) { // When a SerializedProperty is modified the actual field does not have the current value set (i.e. // FieldInfo.GetValue() will return the prior value that was set) until after this OnGUI call has completed. // Therefore, we need to mark this property as dirty, so that it can be updated with a subsequent OnGUI event // (e.g. Repaint) setProperty.IsDirty = true; } else if (setProperty.IsDirty) { // The propertyPath may reference something that is a child field of a field on this Object, so it is necessary // to find which object is the actual parent before attempting to set the property with the current value. object parent = GetParentObjectOfProperty(property.propertyPath, property.serializedObject.targetObject); Type type = parent.GetType(); PropertyInfo pi = type.GetProperty(setProperty.Name); if (pi == null) { Debug.LogError("Invalid property name: " + setProperty.Name + "\nCheck your [SetProperty] attribute"); } else { // Use FieldInfo instead of the SerializedProperty accessors as we'd have to deal with every // SerializedPropertyType and use the correct accessor pi.SetValue(parent, fieldInfo.GetValue(parent), null); } setProperty.IsDirty = false; } } private object GetParentObjectOfProperty(string path, object obj) { string[] fields = path.Split('.'); // We've finally arrived at the final object that contains the property if (fields.Length == 1) { return obj; } // We may have to walk public or private fields along the chain to finding our container object, so we have to allow for both FieldInfo fi = obj.GetType().GetField(fields[0], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); obj = fi.GetValue(obj); // Keep searching for our object that contains the property return GetParentObjectOfProperty(string.Join(".", fields, 1, fields.Length - 1), obj); } }
// Copyright (c) 2014 Luminary LLC // Licensed under The MIT License (See LICENSE for full text) using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Reflection; [CustomPropertyDrawer(typeof(SetPropertyAttribute))] public class SetPropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // Rely on the default inspector GUI EditorGUI.BeginChangeCheck (); EditorGUI.PropertyField(position, property, label); // Update only when necessary SetPropertyAttribute setProperty = attribute as SetPropertyAttribute; if (EditorGUI.EndChangeCheck()) { // When a SerializedProperty is modified the actual field does not have the current value set (i.e. // FieldInfo.GetValue() will return the prior value that was set) until after this OnGUI call has completed. // Therefore, we need to mark this property as dirty, so that it can be updated with a subsequent OnGUI event // (e.g. Repaint) Debug.Log ("Modified"); setProperty.IsDirty = true; } else if (setProperty.IsDirty) { // The propertyPath may reference something that is a child field of a field on this Object, so it is necessary // to find which object is the actual parent before attempting to set the property with the current value. object parent = GetParentObjectOfProperty(property.propertyPath, property.serializedObject.targetObject); Type type = parent.GetType(); PropertyInfo pi = type.GetProperty(setProperty.Name); if (pi == null) { Debug.LogError("Invalid property name: " + setProperty.Name + "\nCheck your [SetProperty] attribute"); } else { // Use FieldInfo instead of the SerializedProperty accessors as we'd have to deal with every // SerializedPropertyType and use the correct accessor pi.SetValue(parent, fieldInfo.GetValue(parent), null); } setProperty.IsDirty = false; } } private object GetParentObjectOfProperty(string path, object obj) { string[] fields = path.Split('.'); // We've finally arrived at the final object that contains the property if (fields.Length == 1) { return obj; } // We may have to walk public or private fields along the chain to finding our container object, so we have to allow for both FieldInfo fi = obj.GetType().GetField(fields[0], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); obj = fi.GetValue(obj); // Keep searching for our object that contains the property return GetParentObjectOfProperty(string.Join(".", fields, 1, fields.Length - 1), obj); } }
mit
C#
ebb38f7eebd8fb51dec7d93162cf5d9fba64d914
Update DirectionTransitDetails.cs
ericnewton76/gmaps-api-net
src/Google.Maps/Direction/DirectionTransitDetails.cs
src/Google.Maps/Direction/DirectionTransitDetails.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Google.Maps.Direction { [JsonObject(MemberSerialization.OptIn)] public class DirectionTransitDetails { [JsonProperty("arrival_stop")] public Stop ArrivalStop { get; set; } [JsonProperty("arrival_time")] public Time ArrivalTime { get; set; } [JsonProperty("departure_stop")] public Stop DepartureStop { get; set; } [JsonProperty("departure_time")] public Time DepartureTime { get; set; } [JsonProperty("headsign")] public string HeadSign { get; set; } [JsonProperty("line")] public LineInfo Line { get; set; } [JsonProperty("num_stops")] public string NumberOfStops { get; set; } public DirectionTransitDetails() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Google.Maps.Direction { [JsonObject(MemberSerialization.OptIn)] public class DirectionTransitDetails { [JsonProperty("arrival_stop")] public Stop ArrivalStop { get; set; } [JsonProperty("arrival_time")] public Time ArrivalTime { get; set; } [JsonProperty("departure_stop")] public Stop DepartureStop { get; set; } [JsonProperty("departure_time")] public Time DepartureTime { get; set; } [JsonProperty("headsign")] public string HeadSign { get; set; } [JsonProperty("line")] public LineInfo Line { get; set; } [JsonProperty("num_stops")] public string NumberOfStops { get; set; } public DirectionTransitDetails() { } } }
apache-2.0
C#
cb029209a386d596b93d531d9ba1baf69aef980d
Remove top level environment variables from default config
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Hosting/WebHostConfiguration.cs
src/Microsoft.AspNet.Hosting/WebHostConfiguration.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.Extensions.Configuration; namespace Microsoft.AspNet.Hosting { public class WebHostConfiguration { public static IConfiguration GetDefault() { return GetDefault(args: null); } public static IConfiguration GetDefault(string[] args) { var defaultSettings = new Dictionary<string, string> { { WebHostDefaults.CaptureStartupErrorsKey, "true" } }; // Setup the default locations for finding hosting configuration options // hosting.json, ASPNET_ prefixed env variables and command line arguments var configBuilder = new ConfigurationBuilder() .AddInMemoryCollection(defaultSettings) .AddJsonFile(WebHostDefaults.HostingJsonFile, optional: true) .AddEnvironmentVariables(prefix: WebHostDefaults.EnvironmentVariablesPrefix); if (args != null) { configBuilder.AddCommandLine(args); } return configBuilder.Build(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.Extensions.Configuration; namespace Microsoft.AspNet.Hosting { public class WebHostConfiguration { public static IConfiguration GetDefault() { return GetDefault(args: null); } public static IConfiguration GetDefault(string[] args) { var defaultSettings = new Dictionary<string, string> { { WebHostDefaults.CaptureStartupErrorsKey, "true" } }; // We are adding all environment variables first and then adding the ASPNET_ ones // with the prefix removed to unify with the command line and config file formats var configBuilder = new ConfigurationBuilder() .AddInMemoryCollection(defaultSettings) .AddJsonFile(WebHostDefaults.HostingJsonFile, optional: true) .AddEnvironmentVariables() .AddEnvironmentVariables(prefix: WebHostDefaults.EnvironmentVariablesPrefix); if (args != null) { configBuilder.AddCommandLine(args); } return configBuilder.Build(); } } }
apache-2.0
C#
a97afa9f4930d676e114e474e3f710c1b6a4afad
Add comment about IsExternalInit
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices/Utility/IsExternalInit.cs
src/PowerShellEditorServices/Utility/IsExternalInit.cs
using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// This type must be defined to use init property accessors, /// but is not in .NET Standard 2.0. /// So instead we define the type in our own code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal class IsExternalInit{} }
using System.ComponentModel; namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal class IsExternalInit{} }
mit
C#
10fb57ec372d87228556061a91120aac115e81c4
Add a just in case null check before deserialization
messagebird/csharp-rest-api
MessageBird/Resources/Resource.cs
MessageBird/Resources/Resource.cs
using System; using MessageBird.Exceptions; using MessageBird.Objects; using Newtonsoft.Json; namespace MessageBird.Resources { public abstract class Resource { public string Id { get { if (HasId) { return Object.Id; } throw new ErrorException(String.Format("Resource {0} has no id", Name)); } } public IIdentifiable<string> Object { get; protected set; } public bool HasId { get { return (Object != null) && !String.IsNullOrEmpty(Object.Id); } } public string Name { get; private set; } public virtual void Deserialize(string resource) { if (Object == null) { throw new ErrorException("Invalid resource, has no attached object", new NullReferenceException()); } JsonConvert.PopulateObject(resource, Object); } public virtual string Serialize() { var settings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; return JsonConvert.SerializeObject(Object, settings); } protected Resource(string name, IIdentifiable<string> attachedObject) { Name = name; Object = attachedObject; } } }
using System; using MessageBird.Exceptions; using MessageBird.Objects; using Newtonsoft.Json; namespace MessageBird.Resources { public abstract class Resource { public string Id { get { if (HasId) { return Object.Id; } throw new ErrorException(String.Format("Resource {0} has no id", Name)); } } public IIdentifiable<string> Object { get; protected set; } public bool HasId { get { return (Object != null) && !String.IsNullOrEmpty(Object.Id); } } public string Name { get; private set; } public virtual void Deserialize(string resource) { JsonConvert.PopulateObject(resource, Object); } public virtual string Serialize() { var settings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; return JsonConvert.SerializeObject(Object, settings); } protected Resource(string name, IIdentifiable<string> attachedObject) { Name = name; Object = attachedObject; } } }
isc
C#
691339a24e80ae47a0285cc6d71ec2900146de4e
Update AssemblyInfo.cs
YallaDotNet/Yalla.Core
src/Yalla.Core/Portable/Properties/AssemblyInfo.cs
src/Yalla.Core/Portable/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; 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: AssemblyTitle("Yalla.Core")] [assembly: AssemblyDescription("Yet Another Logging Library Abstraction for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Yalla")] [assembly: AssemblyCopyright("Copyright © Dmitry Shechtman 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("1.0.*")] [assembly: CLSCompliant(true)]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Yalla.Core")] [assembly: AssemblyDescription("Yet Another Logging Layer of Abstraction for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Yalla.Core")] [assembly: AssemblyCopyright("Copyright © Dmitry Shechtman 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
063434a564d39887ab0aca3b48ccc55ad95ce37d
Add Path property to IMediaFile.
ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey
client/BlueMonkey/BlueMonkey.MediaServices/IMediaFile.cs
client/BlueMonkey/BlueMonkey.MediaServices/IMediaFile.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlueMonkey.MediaServices { public interface IMediaFile : IDisposable { /// <summary> /// Path to file. /// </summary> string Path { get; } /// <summary> /// Get stream if available /// </summary> /// <returns></returns> Stream GetStream(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlueMonkey.MediaServices { public interface IMediaFile : IDisposable { /// <summary> /// Get stream if available /// </summary> /// <returns></returns> Stream GetStream(); } }
mit
C#
29f667ea37b4757ef6830e98a335b1360fcb0901
update version for the next release. unused constant field RELEASE_DATE is removed.
poderosaproject/poderosa,poderosaproject/poderosa,ttdoda/poderosa,ttdoda/poderosa,poderosaproject/poderosa,Chandu/poderosa,Chandu/poderosa,ArsenShnurkov/poderosa,ttdoda/poderosa,ArsenShnurkov/poderosa,ArsenShnurkov/poderosa,poderosaproject/poderosa,Chandu/poderosa,ttdoda/poderosa,poderosaproject/poderosa
Plugin/VersionInfo.cs
Plugin/VersionInfo.cs
/* * Copyright 2004,2006 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: VersionInfo.cs,v 1.13 2012/06/09 15:06:58 kzmi Exp $ */ using System; using System.Collections.Generic; using System.Text; namespace Poderosa { /// <summary> /// <ja> /// o[WԂ܂B /// </ja> /// <en> /// Return the version information. /// </en> /// </summary> /// <exclude/> public class VersionInfo { /// <summary> /// <ja> /// o[WԍłB /// </ja> /// <en> /// Version number. /// </en> /// </summary> public const string PODEROSA_VERSION = "4.3.12b"; /// <summary> /// <ja> /// vWFNgłB /// </ja> /// <en> /// Project name. /// </en> /// </summary> public const string PROJECT_NAME = "Poderosa Project"; } }
/* * Copyright 2004,2006 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: VersionInfo.cs,v 1.13 2012/06/09 15:06:58 kzmi Exp $ */ using System; using System.Collections.Generic; using System.Text; namespace Poderosa { /// <summary> /// <ja> /// o[WԂ܂B /// </ja> /// <en> /// Return the version information. /// </en> /// </summary> /// <exclude/> public class VersionInfo { /// <summary> /// <ja> /// o[WԍłB /// </ja> /// <en> /// Version number. /// </en> /// </summary> public const string PODEROSA_VERSION = "4.3.11b"; /// <summary> /// <ja> /// [XłB /// </ja> /// <en> /// Release Date. /// </en> /// </summary> public const string RELEASE_DATE = "Nov 22, 2006"; /// <summary> /// <ja> /// vWFNgłB /// </ja> /// <en> /// Project name. /// </en> /// </summary> public const string PROJECT_NAME = "Poderosa Project"; } }
apache-2.0
C#
9bac02be9e58cdfdd2242804fe75d00ad26c016c
Fix test name
martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode
tests/AdventOfCode.Tests/Puzzles/Y2021/Day01Tests.cs
tests/AdventOfCode.Tests/Puzzles/Y2021/Day01Tests.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.AdventOfCode.Puzzles.Y2021; /// <summary> /// A class containing tests for the <see cref="Day01"/> class. This class cannot be inherited. /// </summary> public sealed class Day01Tests : PuzzleTest { /// <summary> /// Initializes a new instance of the <see cref="Day01Tests"/> class. /// </summary> /// <param name="outputHelper">The <see cref="ITestOutputHelper"/> to use.</param> public Day01Tests(ITestOutputHelper outputHelper) : base(outputHelper) { } [Theory] [InlineData(false, 7)] [InlineData(true, 5)] public void Y2021_Day01_GetDepthMeasurementIncreases_Returns_Correct_Value( bool useSlidingWindow, int expected) { // Arrange int[] depthMeasurements = { 199, 200, 208, 210, 200, 207, 240, 269, 260, 263 }; // Act int actual = Day01.GetDepthMeasurementIncreases(depthMeasurements, useSlidingWindow); // Assert actual.ShouldBe(expected); } [Fact] public async Task Y2021_Day01_Solve_Returns_Correct_Solution() { // Act var puzzle = await SolvePuzzleAsync<Day01>(); // Assert puzzle.DepthIncreases.ShouldBe(1532); puzzle.DepthIncreasesWithSlidingWindow.ShouldBe(1571); } }
// 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.AdventOfCode.Puzzles.Y2021; /// <summary> /// A class containing tests for the <see cref="Day01"/> class. This class cannot be inherited. /// </summary> public sealed class Day01Tests : PuzzleTest { /// <summary> /// Initializes a new instance of the <see cref="Day01Tests"/> class. /// </summary> /// <param name="outputHelper">The <see cref="ITestOutputHelper"/> to use.</param> public Day01Tests(ITestOutputHelper outputHelper) : base(outputHelper) { } [Theory] [InlineData(false, 7)] [InlineData(true, 5)] public void Y2021_Day01_Get2020Product_Returns_Correct_Value( bool useSlidingWindow, int expected) { // Arrange int[] depthMeasurements = { 199, 200, 208, 210, 200, 207, 240, 269, 260, 263 }; // Act int actual = Day01.GetDepthMeasurementIncreases(depthMeasurements, useSlidingWindow); // Assert actual.ShouldBe(expected); } [Fact] public async Task Y2021_Day01_Solve_Returns_Correct_Solution() { // Act var puzzle = await SolvePuzzleAsync<Day01>(); // Assert puzzle.DepthIncreases.ShouldBe(1532); puzzle.DepthIncreasesWithSlidingWindow.ShouldBe(1571); } }
apache-2.0
C#
7ff712de505d3b5202d097e59228f3c5e2dd6979
Bump version
Yuisbean/WebMConverter,o11c/WebMConverter,nixxquality/WebMConverter
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.5.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.5.0")]
mit
C#
da2a86cd2c772491d8e8ac926435f63b368fc70c
upgrade version to 1.8.0
matortheeternal/mod-analyzer
ModAnalyzer/Properties/AssemblyInfo.cs
ModAnalyzer/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Mod Analyzer")] [assembly: AssemblyDescription("Analyzes Bethesda Game mod archive files.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mod Picker, LLC")] [assembly: AssemblyProduct("Mod Analyzer")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.8.0.0")] [assembly: AssemblyFileVersion("1.8.0.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Mod Analyzer")] [assembly: AssemblyDescription("Analyzes Bethesda Game mod archive files.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mod Picker, LLC")] [assembly: AssemblyProduct("Mod Analyzer")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.7.4.0")] [assembly: AssemblyFileVersion("1.7.4.0")]
mit
C#
188f27aff7df4aba29ca85d19654521c60f8e659
Update ImportingFromArrayList.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,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,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Data/Handling/Importing/ImportingFromArrayList.cs
Examples/CSharp/Data/Handling/Importing/ImportingFromArrayList.cs
using System.IO; using Aspose.Cells; using System.Collections; namespace Aspose.Cells.Examples.Data.Handling.Importing { public class ImportingFromArrayList { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Obtaining the reference of the worksheet Worksheet worksheet = workbook.Worksheets[0]; //Instantiating an ArrayList object ArrayList list = new ArrayList(); //Add few names to the list as string values list.Add("laurence chen"); list.Add("roman korchagin"); list.Add("kyle huang"); list.Add("tommy wang"); //Importing the contents of ArrayList to 1st row and first column vertically worksheet.Cells.ImportArrayList(list, 0, 0, true); //Saving the Excel file workbook.Save(dataDir + "DataImport.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System.Collections; namespace Aspose.Cells.Examples.Data.Handling.Importing { public class ImportingFromArrayList { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Obtaining the reference of the worksheet Worksheet worksheet = workbook.Worksheets[0]; //Instantiating an ArrayList object ArrayList list = new ArrayList(); //Add few names to the list as string values list.Add("laurence chen"); list.Add("roman korchagin"); list.Add("kyle huang"); list.Add("tommy wang"); //Importing the contents of ArrayList to 1st row and first column vertically worksheet.Cells.ImportArrayList(list, 0, 0, true); //Saving the Excel file workbook.Save(dataDir + "DataImport.out.xls"); } } }
mit
C#
7a542d6e23a321883ac6f421da2dd09a8242f868
Set collision behavior to skip with force
unic/Sitecore-Courier
Sitecore.Courier/FileCommandsFilter.cs
Sitecore.Courier/FileCommandsFilter.cs
using Sitecore.Update; namespace Sitecore.Courier { using System.Collections.Generic; using System.Linq; using Sitecore.Update.Commands; using Sitecore.Update.Interfaces; /// <summary> /// The language filter. /// </summary> public class FileCommandsFilter : ICommandFilter { private List<string> excludedFolders = new List<string>(); private bool forceoverwrites = false; public FileCommandsFilter() { excludedFolders.Add("serialization"); excludedFolders.Add("data"); } public List<string> ExcludedFolders { get { return excludedFolders; } set { excludedFolders = value; } } public bool ForceOverwrites { get { return forceoverwrites; } set { forceoverwrites = value; } } /// <summary> /// Filters the command. /// </summary> /// <param name="command">The command.</param> /// <returns>The filtered command.</returns> public ICommand FilterCommand(ICommand command) { if (command == null) return null; if (ForceOverwrites) { command.CollisionBehavior = CollisionBehavior.Force; } else { command.CollisionBehavior = CollisionBehavior.Skip; } if (!(command is AddFolderCommand) && !(command is AddFileCommand)) { return command; } if (this.excludedFolders.Any(folder => command.EntityPath.Replace("\\", string.Empty).StartsWith(folder))) { return null; } return command; } /// <summary> /// Clones this instance. /// </summary> /// <returns> /// The I command filter. /// </returns> public ICommandFilter Clone() { return new FileCommandsFilter() { ForceOverwrites = this.ForceOverwrites, ExcludedFolders = excludedFolders }; } } }
using Sitecore.Update; namespace Sitecore.Courier { using System.Collections.Generic; using System.Linq; using Sitecore.Update.Commands; using Sitecore.Update.Interfaces; /// <summary> /// The language filter. /// </summary> public class FileCommandsFilter : ICommandFilter { private List<string> excludedFolders = new List<string>(); private bool forceoverwrites = false; public FileCommandsFilter() { excludedFolders.Add("serialization"); excludedFolders.Add("data"); } public List<string> ExcludedFolders { get { return excludedFolders; } set { excludedFolders = value; } } public bool ForceOverwrites { get { return forceoverwrites; } set { forceoverwrites = value; } } /// <summary> /// Filters the command. /// </summary> /// <param name="command">The command.</param> /// <returns>The filtered command.</returns> public ICommand FilterCommand(ICommand command) { if (command == null) return null; if (ForceOverwrites) { command.CollisionBehavior = CollisionBehavior.Force; } if (!(command is AddFolderCommand) && !(command is AddFileCommand)) { return command; } if (this.excludedFolders.Any(folder => command.EntityPath.Replace("\\", string.Empty).StartsWith(folder))) { return null; } return command; } /// <summary> /// Clones this instance. /// </summary> /// <returns> /// The I command filter. /// </returns> public ICommandFilter Clone() { return new FileCommandsFilter() { ForceOverwrites = this.ForceOverwrites, ExcludedFolders = excludedFolders }; } } }
mit
C#
49c994ede715a6bf49866dc5580b867666a074e6
Update Obsolete attribute message
bartdesmet/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,abock/roslyn,bartdesmet/roslyn,tannergooding/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,reaction1989/roslyn,agocke/roslyn,physhi/roslyn,AlekseyTs/roslyn,davkean/roslyn,jmarolf/roslyn,davkean/roslyn,AmadeusW/roslyn,genlu/roslyn,stephentoub/roslyn,jmarolf/roslyn,tmat/roslyn,heejaechang/roslyn,gafter/roslyn,gafter/roslyn,mgoertz-msft/roslyn,gafter/roslyn,mavasani/roslyn,physhi/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,eriawan/roslyn,aelij/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,aelij/roslyn,mavasani/roslyn,wvdd007/roslyn,genlu/roslyn,diryboy/roslyn,diryboy/roslyn,davkean/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,jmarolf/roslyn,weltkante/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,mavasani/roslyn,weltkante/roslyn,abock/roslyn,tannergooding/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,eriawan/roslyn,dotnet/roslyn,AlekseyTs/roslyn,genlu/roslyn,dotnet/roslyn,diryboy/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,dotnet/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,tmat/roslyn,abock/roslyn,KirillOsenkov/roslyn,agocke/roslyn,heejaechang/roslyn,physhi/roslyn,wvdd007/roslyn,stephentoub/roslyn,tmat/roslyn,wvdd007/roslyn,reaction1989/roslyn
src/Workspaces/Core/Portable/SolutionCrawler/ServiceFeatureOnOffOptions.cs
src/Workspaces/Core/Portable/SolutionCrawler/ServiceFeatureOnOffOptions.cs
using System; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Shared.Options { internal static class ServiceFeatureOnOffOptions { /// <summary> /// This option is used by TypeScript. /// </summary> [Obsolete("Currently used by TypeScript - should move to the new option SolutionCrawlerOptions.BackgroundAnalysisScopeOption")] public static readonly PerLanguageOption<bool?> ClosedFileDiagnostic = new PerLanguageOption<bool?>( "ServiceFeaturesOnOff", "Closed File Diagnostic", defaultValue: null, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Closed File Diagnostic")); } }
using System; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Shared.Options { internal static class ServiceFeatureOnOffOptions { /// <summary> /// This option is used by TypeScript. /// </summary> [Obsolete("Use the new option SolutionCrawlerOptions.BackgroundAnalysisScopeOption")] public static readonly PerLanguageOption<bool?> ClosedFileDiagnostic = new PerLanguageOption<bool?>( "ServiceFeaturesOnOff", "Closed File Diagnostic", defaultValue: null, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Closed File Diagnostic")); } }
mit
C#
e73261347547e9fdbba2d6d8a1178a295c1fc323
Update ComparisonConditionType.cs
Microsoft/XamlBehaviors,PedroLamas/XamlBehaviors,PedroLamas/XamlBehaviors,PedroLamas/XamlBehaviors,Microsoft/XamlBehaviors,Microsoft/XamlBehaviors
src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Core/ComparisonConditionType.cs
src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Core/ComparisonConditionType.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Xaml.Interactions.Core { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// Represents one ternary condition. /// </summary> public enum ComparisonConditionType { /// <summary> /// Specifies an equal condition. /// </summary> Equal, /// <summary> /// Specifies a not equal condition. /// </summary> NotEqual, /// <summary> /// Specifies a less than condition. /// </summary> LessThan, /// <summary> /// Specifies a less than or equal condition. /// </summary> LessThanOrEqual, /// <summary> /// Specifies a greater than condition. /// </summary> GreaterThan, /// <summary> /// Specifies a greater than or equal condition. /// </summary> GreaterThanOrEqual } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Xaml.Interactions.Core { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// Represents one ternary condition. /// </summary> public enum ComparisonConditionType { Equal, NotEqual, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual } }
mit
C#
f67687212b6827f04e4f34c53d3294ea1700be19
change the listItem to realmObject
CORDEA/ConviviumCalculator,CORDEA/ConviviumCalculator,CORDEA/ConviviumCalculator,CORDEA/ConviviumCalculator,CORDEA/ConviviumCalculator,CORDEA/ConviviumCalculator
windows/ConviviumCalculator/ListItem.cs
windows/ConviviumCalculator/ListItem.cs
using Realms; namespace ConviviumCalculator { public class ListItem : RealmObject { public string Name { get; set; } public int Price { get; set; } public bool IsSwitch { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConviviumCalculator { public class ListItem { public string Name { get; set; } public int Price { get; set; } public bool IsSwitch { get; set; } public ListItem(string name, int price, bool isSwitch) { Name = name; Price = price; IsSwitch = isSwitch; } } }
apache-2.0
C#
2565872083c21df6910305627bbb4eb786754817
add model validations for CatalogItem
dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing
src/eShopCatalogMVC/Models/CatalogItem.cs
src/eShopCatalogMVC/Models/CatalogItem.cs
using System.ComponentModel.DataAnnotations; namespace eShopCatalogMVC.Models { public class CatalogItem { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } // decimal(18,2) [RegularExpression(@"^\d+\.\d{0,2}$", ErrorMessage = "The field Price must be a positive number with maximum two decimals.")] [Range(0, 9999999999999999.99)] public decimal Price { get; set; } public string PictureFileName { get; set; } public int CatalogTypeId { get; set; } public CatalogType CatalogType { get; set; } public int CatalogBrandId { get; set; } public CatalogBrand CatalogBrand { get; set; } // Quantity in stock [Range(0, int.MaxValue)] public int AvailableStock { get; set; } // Available stock at which we should reorder [Range(0, int.MaxValue)] public int RestockThreshold { get; set; } // Maximum number of units that can be in-stock at any time (due to physicial/logistical constraints in warehouses) [Range(0, int.MaxValue)] public int MaxStockThreshold { get; set; } /// <summary> /// True if item is on reorder /// </summary> public bool OnReorder { get; set; } } }
namespace eShopCatalogMVC.Models { public class CatalogItem { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal Price { get; set; } public string PictureFileName { get; set; } public int CatalogTypeId { get; set; } public CatalogType CatalogType { get; set; } public int CatalogBrandId { get; set; } public CatalogBrand CatalogBrand { get; set; } // Quantity in stock public int AvailableStock { get; set; } // Available stock at which we should reorder public int RestockThreshold { get; set; } // Maximum number of units that can be in-stock at any time (due to physicial/logistical constraints in warehouses) public int MaxStockThreshold { get; set; } /// <summary> /// True if item is on reorder /// </summary> public bool OnReorder { get; set; } } }
mit
C#
95b5d81698d82b4350a78f1eee84efcb2eb09b0c
Fix URI Is Not Responding test
OpenMagic/OpenMagic
tests/OpenMagic.Specifications/Steps/Extensions/UriExtensions/IsReposondingSteps.cs
tests/OpenMagic.Specifications/Steps/Extensions/UriExtensions/IsReposondingSteps.cs
using System; using FluentAssertions; using OpenMagic.Extensions; using OpenMagic.Specifications.Helpers; using TechTalk.SpecFlow; namespace OpenMagic.Specifications.Steps.Extensions.UriExtensions { [Binding] public class IsReposondingSteps { private readonly GivenData _given; private readonly ActualData _actual; public IsReposondingSteps(GivenData given, ActualData actual) { _given = given; _actual = actual; } [Given(@"URI is responding")] public void GivenUriIsResponding() { _given.Uri = new Uri("http://www.google.com"); } [Given(@"URI is not responding")] public void GivenUriIsNotResponding() { _given.Uri = new Uri("http://domainthat.doesnotexist"); } [When(@"I call IsResponding\(<uri>\)")] public void WhenICallIsResponding() { _actual.GetResult(() => _given.Uri.IsResponding()); } } }
using System; using FluentAssertions; using OpenMagic.Extensions; using OpenMagic.Specifications.Helpers; using TechTalk.SpecFlow; namespace OpenMagic.Specifications.Steps.Extensions.UriExtensions { [Binding] public class IsReposondingSteps { private readonly GivenData _given; private readonly ActualData _actual; public IsReposondingSteps(GivenData given, ActualData actual) { _given = given; _actual = actual; } [Given(@"URI is responding")] public void GivenUriIsResponding() { _given.Uri = new Uri("http://www.google.com"); } [Given(@"URI is not responding")] public void GivenUriIsNotResponding() { _given.Uri = new Uri("http://" + Guid.NewGuid()); } [When(@"I call IsResponding\(<uri>\)")] public void WhenICallIsResponding() { _actual.GetResult(() => _given.Uri.IsResponding()); } } }
mit
C#