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
83e72796ece32a983af7edec856bf30a8bd3b574
Add value task to FillBuffer()
KodamaSakuno/Sakuno.Base
src/Sakuno.Base/IO/StreamExtensions.cs
src/Sakuno.Base/IO/StreamExtensions.cs
using System; using System.ComponentModel; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Sakuno.IO { [EditorBrowsable(EditorBrowsableState.Never)] public static class StreamExtensions { public static int FillBuffer(this Stream stream, byte[] buffer, int offset, int count) { var remaining = count; do { var length = stream.Read(buffer, offset, remaining); if (length == 0) break; remaining -= length; offset += length; } while (remaining > 0); return count - remaining; } #if NETSTANDARD2_1 public static async ValueTask<int> FillBuffer(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default) { var remaining = buffer.Length; var offset = 0; do { var length = await stream.ReadAsync(buffer, cancellationToken); if (length == 0) break; remaining -= length; offset += length; } while (remaining > 0); return buffer.Length - remaining; } #endif } }
using System.ComponentModel; using System.IO; namespace Sakuno.IO { [EditorBrowsable(EditorBrowsableState.Never)] public static class StreamExtensions { public static int FillBuffer(this Stream stream, byte[] buffer, int offset, int count) { var remaining = count; do { var length = stream.Read(buffer, offset, remaining); if (length == 0) break; remaining -= length; offset += length; } while (remaining > 0); return count - remaining; } } }
mit
C#
b14d5d9052cda78c9cf5e36cd1dc921abe6b93cb
Implement Equals
charlenni/Mapsui,charlenni/Mapsui
Mapsui/MRect2.cs
Mapsui/MRect2.cs
using System.Collections.Generic; namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); /// <summary> /// Returns the vertices in clockwise order from bottom left around to bottom right /// </summary> public IEnumerable<MPoint> Vertices { get { yield return BottomLeft; yield return TopLeft; yield return TopRight; yield return BottomRight; } } public MRect Copy() { return new MRect(Min.X, Min.Y, Max.X, Max.Y); } public bool Contains(MPoint? point) { if (point is null) return false; if (point.X < Min.X) return false; if (point.Y < Min.Y) return false; if (point.X > Max.X) return false; if (point.Y > Max.Y) return false; return true; } public bool Contains(MRect r) { return Min.X <= r.Min.X && Min.Y <= r.Min.Y && Max.X >= r.Max.X && Max.Y >= r.Max.Y; } public bool Equals(MRect? other) { if (other is null) return false; return Min.Equals(other.Min) && Max.Equals(other.Max); } //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); }
using System.Collections.Generic; namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); /// <summary> /// Returns the vertices in clockwise order from bottom left around to bottom right /// </summary> public IEnumerable<MPoint> Vertices { get { yield return BottomLeft; yield return TopLeft; yield return TopRight; yield return BottomRight; } } public MRect Copy() { return new MRect(Min.X, Min.Y, Max.X, Max.Y); } public bool Contains(MPoint? point) { if (point == null) return false; if (point.X < Min.X) return false; if (point.Y < Min.Y) return false; if (point.X > Max.X) return false; if (point.Y > Max.Y) return false; return true; } public bool Contains(MRect r) { return Min.X <= r.Min.X && Min.Y <= r.Min.Y && Max.X >= r.Max.X && Max.Y >= r.Max.Y; } //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); }
mit
C#
357e336d8deb341498888658bf2cac2c88be1f7c
bump version to 2.12.0
piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker
Piwik.Tracker/Properties/AssemblyInfo.cs
Piwik.Tracker/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("PiwikTracker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Piwik")] [assembly: AssemblyProduct("PiwikTracker")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8121d06f-a801-42d2-a144-0036a0270bf3")] // 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.12.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("PiwikTracker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Piwik")] [assembly: AssemblyProduct("PiwikTracker")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8121d06f-a801-42d2-a144-0036a0270bf3")] // 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.11.1")]
bsd-3-clause
C#
187dbb346f8d2da24251acfeb15ee2f0fb0e243f
Remove UnityEvent from SharedConnectionRedirectionPayloadHandler
HelloKitty/Booma.Proxy
src/Booma.Proxy.Client.Unity.SharedHandlers/Handlers/SharedConnectionRedirectionPayloadHandler.cs
src/Booma.Proxy.Client.Unity.SharedHandlers/Handlers/SharedConnectionRedirectionPayloadHandler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; using SceneJect.Common; using UnityEngine; using UnityEngine.Events; namespace Booma.Proxy { public class SharedConnectionRedirectionPayloadHandler : GameMessageHandler<SharedConnectionRedirectPayload> { private IFullCryptoInitializationService<byte[]> CryptoInitializer { get; } /// <summary> /// Data model for connection details. /// </summary> private IGameConnectionEndpointDetails ConnectionEndpoint { get; } /// <inheritdoc /> public SharedConnectionRedirectionPayloadHandler([NotNull] IGameConnectionEndpointDetails connectionEndpoint, [NotNull] IFullCryptoInitializationService<byte[]> cryptoInitializer, ILog logger) : base(logger) { ConnectionEndpoint = connectionEndpoint ?? throw new ArgumentNullException(nameof(connectionEndpoint)); CryptoInitializer = cryptoInitializer ?? throw new ArgumentNullException(nameof(cryptoInitializer)); } /// <inheritdoc /> public override async Task HandleMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, SharedConnectionRedirectPayload payload) { if(Logger.IsInfoEnabled) Logger.Info($"Redirecting Login to {BuildLoginDebugString(payload)}"); //Have to clear crypto since we're connecting to a new endpoint CryptoInitializer.DecryptionInitializable.Uninitialize(); CryptoInitializer.EncryptionInitializable.Uninitialize(); //We don't immediately redirect in the handler anymore. We initialize the new connection endpoint //to a data model and then broadcast that we recieved a redirection request. This way scene loading //can happen inbetween. ConnectionEndpoint.IpAddress = payload.EndpointAddress.ToString(); ConnectionEndpoint.Port = payload.EndpointerPort; await OnConnectionRedirected(); } private string BuildLoginDebugString(SharedConnectionRedirectPayload payload) { return $"Ip: {payload.EndpointAddress} Port: {payload.EndpointerPort}"; } //Default version we don't do anything. protected virtual Task OnConnectionRedirected() { return Task.CompletedTask; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; using SceneJect.Common; using UnityEngine; using UnityEngine.Events; namespace Booma.Proxy { public sealed class SharedConnectionRedirectionPayloadHandler : GameMessageHandler<SharedConnectionRedirectPayload> { private IFullCryptoInitializationService<byte[]> CryptoInitializer { get; } /// <summary> /// Broadcasts when a connection redirection is recieved. /// </summary> [SerializeField] private UnityEvent OnConnectionRedirected; /// <summary> /// Data model for connection details. /// </summary> private IGameConnectionEndpointDetails ConnectionEndpoint { get; } /// <inheritdoc /> public SharedConnectionRedirectionPayloadHandler([NotNull] IGameConnectionEndpointDetails connectionEndpoint, [NotNull] IFullCryptoInitializationService<byte[]> cryptoInitializer, ILog logger) : base(logger) { ConnectionEndpoint = connectionEndpoint ?? throw new ArgumentNullException(nameof(connectionEndpoint)); CryptoInitializer = cryptoInitializer ?? throw new ArgumentNullException(nameof(cryptoInitializer)); } /// <inheritdoc /> public override async Task HandleMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, SharedConnectionRedirectPayload payload) { if(Logger.IsInfoEnabled) Logger.Info($"Redirecting Login to {BuildLoginDebugString(payload)}"); //Have to clear crypto since we're connecting to a new endpoint CryptoInitializer.DecryptionInitializable.Uninitialize(); CryptoInitializer.EncryptionInitializable.Uninitialize(); //We don't immediately redirect in the handler anymore. We initialize the new connection endpoint //to a data model and then broadcast that we recieved a redirection request. This way scene loading //can happen inbetween. ConnectionEndpoint.IpAddress = payload.EndpointAddress.ToString(); ConnectionEndpoint.Port = payload.EndpointerPort; OnConnectionRedirected?.Invoke(); } private string BuildLoginDebugString(SharedConnectionRedirectPayload payload) { return $"Ip: {payload.EndpointAddress} Port: {payload.EndpointerPort}"; } } }
agpl-3.0
C#
f6723bb6ca2e80430343fe4e49abd416ef6b0eae
Add exception catch for sub60 message handling
HelloKitty/Booma.Proxy
src/Booma.Proxy.Client.Unity.GladMMO/Interop/Handlers/InteropCommand60Handler.cs
src/Booma.Proxy.Client.Unity.GladMMO/Interop/Handlers/InteropCommand60Handler.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Common.Logging; namespace Booma.Proxy { /// <summary> /// Implementation of the message handler /// that handles specifically <see cref="BlockNetworkCommand60EventClientPayload"/> and dispatches the casted <typeparamref name="TSubCommandType"/> command /// to the implementer of this type. /// </summary> /// <typeparam name="TSubCommandType"></typeparam> public abstract class InteropCommand60Handler<TSubCommandType> : BaseInteropSubMessageMessageHandler<TSubCommandType, BlockNetworkCommand60EventServerPayload> where TSubCommandType : BaseSubCommand60 { /// <inheritdoc /> protected InteropCommand60Handler(ILog logger) : base(logger) { } /// <inheritdoc /> protected override bool CheckIsHandlable(BlockNetworkCommand60EventServerPayload payload) { //Just check if it's the type. return payload.Command is TSubCommandType; } /// <inheritdoc /> protected override TSubCommandType RetrieveSubMessage(BlockNetworkCommand60EventServerPayload payload) { //If they ask for it just provide it. Could be null, but not up to us. return payload.Command as TSubCommandType; } public override Task HandleMessage(InteropPSOBBPeerMessageContext context, BlockNetworkCommand60EventServerPayload payload) { //Because this is technically unsanitized input from remote clients, psobb servers just forward it //we don't want exceptions in this area to bubble up //if they do the network client will disconnect itself //therefore we supress and log these exceptions try { return base.HandleMessage(context, payload); } catch (Exception e) { if(Logger.IsErrorEnabled) Logger.Error($"Encountered Sub60 message Exception: \n {e.ToString()}"); return Task.CompletedTask; } } } }
using System; using System.Collections.Generic; using System.Text; using Common.Logging; namespace Booma.Proxy { /// <summary> /// Implementation of the message handler /// that handles specifically <see cref="BlockNetworkCommand60EventClientPayload"/> and dispatches the casted <typeparamref name="TSubCommandType"/> command /// to the implementer of this type. /// </summary> /// <typeparam name="TSubCommandType"></typeparam> public abstract class InteropCommand60Handler<TSubCommandType> : BaseInteropSubMessageMessageHandler<TSubCommandType, BlockNetworkCommand60EventServerPayload> where TSubCommandType : BaseSubCommand60 { /// <inheritdoc /> protected InteropCommand60Handler(ILog logger) : base(logger) { } /// <inheritdoc /> protected override bool CheckIsHandlable(BlockNetworkCommand60EventServerPayload payload) { //Just check if it's the type. return payload.Command is TSubCommandType; } /// <inheritdoc /> protected override TSubCommandType RetrieveSubMessage(BlockNetworkCommand60EventServerPayload payload) { //If they ask for it just provide it. Could be null, but not up to us. return payload.Command as TSubCommandType; } } }
agpl-3.0
C#
f5631f3a5345daecbe8f3d545fde7a477f11247e
Add extensions for other folders
ginach/onedrive-sdk-csharp,OneDrive/onedrive-sdk-csharp
src/OneDriveSdk/Requests/Extensions/SpecialCollectionRequestBuilderExtensions.cs
src/OneDriveSdk/Requests/Extensions/SpecialCollectionRequestBuilderExtensions.cs
// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Microsoft.OneDrive.Sdk { public partial class SpecialCollectionRequestBuilder { /// <summary> /// Gets app root special folder item request builder. /// <returns>The item request builder.</returns> /// </summary> public IItemRequestBuilder AppRoot { get { return new ItemRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.AppRoot), this.Client); } } /// <summary> /// Gets Documents special folder item request builder. /// <returns>The item request builder.</returns> /// </summary> public IItemRequestBuilder Documents { get { return new ItemRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.Documents), this.Client); } } /// <summary> /// Gets Photos special folder item request builder. /// <returns>The item request builder.</returns> /// </summary> public IItemRequestBuilder Photos { get { return new ItemRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.Photos), this.Client); } } /// <summary> /// Gets Camera Roll special folder item request builder. /// <returns>The item request builder.</returns> /// </summary> public IItemRequestBuilder CameraRoll { get { return new ItemRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.CameraRoll), this.Client); } } /// <summary> /// Gets Music special folder item request builder. /// <returns>The item request builder.</returns> /// </summary> public IItemRequestBuilder Music { get { return new ItemRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.Music), this.Client); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Microsoft.OneDrive.Sdk { public partial class SpecialCollectionRequestBuilder { /// <summary> /// Gets app root special folder item request builder. /// <returns>The item request builder.</returns> /// </summary> public IItemRequestBuilder AppRoot { get { return new ItemRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.AppRoot), this.Client); } } } }
mit
C#
e60d6b152e0a147942f646bbf963f5b5fd74dac6
Add Do Somthing
seyedk/Staffing
Staffing/Staffing/Program.cs
Staffing/Staffing/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Staffing { class Program { static void Main(string[] args) { } static void DoSomthing() { Console.WriteLine("I'm doing something now!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Staffing { class Program { static void Main(string[] args) { } } }
mit
C#
780b6e933b0030c0d05d8f9c144568631b93ae33
Remove unnecessary delegate redirects
ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework
osu.Framework/Input/Handlers/Joystick/JoystickHandler.cs
osu.Framework/Input/Handlers/Joystick/JoystickHandler.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.Input.StateChanges; using osu.Framework.Platform; using osu.Framework.Statistics; namespace osu.Framework.Input.Handlers.Joystick { public class JoystickHandler : InputHandler { public override bool IsActive => true; public override int Priority => 0; public override bool Initialize(GameHost host) { if (!(host.Window is DesktopWindow window)) return false; Enabled.BindValueChanged(e => { if (e.NewValue) { window.JoystickButtonDown += enqueueJoystickEvent; window.JoystickButtonUp += enqueueJoystickEvent; window.JoystickAxisChanged += enqueueJoystickEvent; } else { window.JoystickButtonDown -= enqueueJoystickEvent; window.JoystickButtonUp -= enqueueJoystickEvent; window.JoystickAxisChanged -= enqueueJoystickEvent; } }, true); return true; } private void enqueueJoystickEvent(IInput evt) { PendingInputs.Enqueue(evt); FrameStatistics.Increment(StatisticsCounterType.JoystickEvents); } } }
// 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.Input.StateChanges; using osu.Framework.Platform; using osu.Framework.Statistics; namespace osu.Framework.Input.Handlers.Joystick { public class JoystickHandler : InputHandler { public override bool IsActive => true; public override int Priority => 0; public override bool Initialize(GameHost host) { if (!(host.Window is DesktopWindow window)) return false; Enabled.BindValueChanged(e => { if (e.NewValue) { window.JoystickButtonDown += handleJoystickButtonEvent; window.JoystickButtonUp += handleJoystickButtonEvent; window.JoystickAxisChanged += handleJoystickAxisChangedEvent; } else { window.JoystickButtonDown -= handleJoystickButtonEvent; window.JoystickButtonUp -= handleJoystickButtonEvent; window.JoystickAxisChanged -= handleJoystickAxisChangedEvent; } }, true); return true; } private void handleJoystickAxisChangedEvent(JoystickAxisInput evt) => enqueueJoystickEvent(evt); private void handleJoystickButtonEvent(JoystickButtonInput evt) => enqueueJoystickEvent(evt); private void enqueueJoystickEvent(IInput evt) { PendingInputs.Enqueue(evt); FrameStatistics.Increment(StatisticsCounterType.JoystickEvents); } } }
mit
C#
ba9d23bf77773dce672f6e7dd58a0bff905aec65
Update Common.cs
alexguirre/RAGENativeUI,alexguirre/RAGENativeUI
Source/Common.cs
Source/Common.cs
using System; using Rage; using Rage.Native; namespace RAGENativeUI { public static class Common { /// <summary> /// Fonts used by GTA V /// </summary> public enum EFont { ChaletLondon = 0, HouseScript = 1, Monospace = 2, ChaletComprimeCologne = 4, Pricedown = 7 } public enum MenuControls { Up, Down, Left, Right, Select, Back } public static void PlaySound(string soundFile, string soundSet) { NativeFunction.CallByName<uint>("PLAY_SOUND_FRONTEND", -1, soundFile, soundSet, false); } /// <summary> /// Check if a Rage.GameControl is pressed while it's disabled /// </summary> /// <param name="index"></param> /// <param name="control"></param> /// <returns>true if a Rage.GameControl is pressed while it's disabled</returns> public static bool IsDisabledControlPressed(int index, GameControl control) { return NativeFunction.CallByName<bool>("IS_DISABLED_CONTROL_PRESSED", index, (int)control); } /// <summary> /// Check if a Rage.GameControl is just pressed while it's disabled /// </summary> /// <param name="index"></param> /// <param name="control"></param> /// <returns>true if a Rage.GameControl is just pressed while it's disabled</returns> public static bool IsDisabledControlJustPressed(int index, GameControl control) { return NativeFunction.CallByName<bool>("IS_DISABLED_CONTROL_JUST_PRESSED", index, (int)control); } /// <summary> /// Check if a Rage.GameControl is just released while it's disabled /// </summary> /// <param name="index"></param> /// <param name="control"></param> /// <returns>true if a Rage.GameControl is just released while it's disabled</returns> public static bool IsDisabledControlJustReleased(int index, GameControl control) { return NativeFunction.CallByName<bool>("IS_DISABLED_CONTROL_JUST_RELEASED", index, (int)control); } } }
using System; using Rage; using Rage.Native; namespace RAGENativeUI { public static class Common { public enum EFont { ChaletLondon = 0, HouseScript = 1, Monospace = 2, ChaletComprimeCologne = 4, Pricedown = 7 } public enum MenuControls { Up, Down, Left, Right, Select, Back } public static void PlaySound(string soundFile, string soundSet) { NativeFunction.CallByName<uint>("PLAY_SOUND_FRONTEND", -1, soundFile, soundSet, false); } public static bool IsDisabledControlPressed(int index, GameControl control) { return NativeFunction.CallByName<bool>("IS_DISABLED_CONTROL_PRESSED", index, (int)control); } public static bool IsDisabledControlJustPressed(int index, GameControl control) { return NativeFunction.CallByName<bool>("IS_DISABLED_CONTROL_JUST_PRESSED", index, (int)control); } public static bool IsDisabledControlJustReleased(int index, GameControl control) { return NativeFunction.CallByName<bool>("IS_DISABLED_CONTROL_JUST_RELEASED", index, (int)control); } } }
mit
C#
e1ce546ca5c46d5d140d7e45910685da6092ffb0
Use type/attribute for user secrets
martincostello/website,martincostello/website,martincostello/website,martincostello/website
src/Website/Startup.cs
src/Website/Startup.cs
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; /// <summary> /// A class representing the startup logic for the application. /// </summary> public class Startup : StartupBase { /// <summary> /// Initializes a new instance of the <see cref="Startup"/> class. /// </summary> /// <param name="env">The <see cref="IHostingEnvironment"/> to use.</param> public Startup(IHostingEnvironment env) : base(env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); bool isDevelopment = env.IsDevelopment(); if (isDevelopment) { builder.AddUserSecrets<Startup>(); } builder.AddApplicationInsightsSettings(developerMode: isDevelopment); Configuration = builder.Build(); } } }
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; /// <summary> /// A class representing the startup logic for the application. /// </summary> public class Startup : StartupBase { /// <summary> /// Initializes a new instance of the <see cref="Startup"/> class. /// </summary> /// <param name="env">The <see cref="IHostingEnvironment"/> to use.</param> public Startup(IHostingEnvironment env) : base(env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); bool isDevelopment = env.IsDevelopment(); if (isDevelopment) { builder.AddUserSecrets("martincostello.com"); } builder.AddApplicationInsightsSettings(developerMode: isDevelopment); Configuration = builder.Build(); } } }
apache-2.0
C#
4444078847f6f7bb1a40a6b7dac0d1fd801b61ab
Make TimeCache use MRU policy
Neio/DSAccessMonitor
TimeCache.cs
TimeCache.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace PropertyChange { public interface ICache<T> { T Get(string key, Func<T> getValue); } public class TimeCache<T> : ICache<T> where T : class { public MemoryCache m_cache = new MemoryCache(Guid.NewGuid().ToString()); long m_cacheLife; public TimeCache(TimeSpan cacheLifeTime) { m_cacheLife = (long)cacheLifeTime.TotalSeconds; } public T Get(string key, Func<T> getValue) { var cache = m_cache[key]; T value = m_cache[key] as T ?? getValue(); m_cache.Set(key, value, DateTimeOffset.Now.AddSeconds(m_cacheLife)); return value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace PropertyChange { public interface ICache<T> { T Get(string key, Func<T> getValue); } public class TimeCache<T> : ICache<T> where T : class { public MemoryCache m_cache = new MemoryCache(Guid.NewGuid().ToString()); long m_cacheLife; public TimeCache(TimeSpan cacheLifeTime) { m_cacheLife = (long)cacheLifeTime.TotalSeconds; } public T Get(string key, Func<T> getValue) { var cache = m_cache[key]; if (cache != null) { var value = cache as T; if (value != null) { return value; } } var v = getValue(); m_cache.Add(key, v, DateTimeOffset.Now.AddSeconds(m_cacheLife)); return v; } } }
mit
C#
492b7d90049f415823240f97d059983ec131f838
clean code
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/CacheUtil.cs
src/WeihanLi.Common/CacheUtil.cs
using System; using System.Collections.Concurrent; using System.Reflection; using WeihanLi.Common.DependencyInjection; namespace WeihanLi.Common { public static class CacheUtil { /// <summary> /// TypePropertyCache /// </summary> public static readonly ConcurrentDictionary<Type, PropertyInfo[]> TypePropertyCache = new ConcurrentDictionary<Type, PropertyInfo[]>(); internal static readonly ConcurrentDictionary<Type, FieldInfo[]> TypeFieldCache = new ConcurrentDictionary<Type, FieldInfo[]>(); internal static readonly ConcurrentDictionary<Type, MethodInfo[]> TypeMethodCache = new ConcurrentDictionary<Type, MethodInfo[]>(); internal static readonly ConcurrentDictionary<Type, Func<ServiceContainer, object>> TypeNewFuncCache = new ConcurrentDictionary<Type, Func<ServiceContainer, object>>(); internal static readonly ConcurrentDictionary<Type, ConstructorInfo> TypeConstructorCache = new ConcurrentDictionary<Type, ConstructorInfo>(); internal static readonly ConcurrentDictionary<Type, Func<object>> TypeEmptyConstructorFuncCache = new ConcurrentDictionary<Type, Func<object>>(); internal static readonly ConcurrentDictionary<Type, Func<object[], object>> TypeConstructorFuncCache = new ConcurrentDictionary<Type, Func<object[], object>>(); internal static readonly ConcurrentDictionary<PropertyInfo, Func<object, object>> PropertyValueGetters = new ConcurrentDictionary<PropertyInfo, Func<object, object>>(); internal static readonly ConcurrentDictionary<PropertyInfo, Action<object, object>> PropertyValueSetters = new ConcurrentDictionary<PropertyInfo, Action<object, object>>(); } internal static class StrongTypedCache<T> { public static readonly ConcurrentDictionary<PropertyInfo, Func<T, object>> PropertyValueGetters = new ConcurrentDictionary<PropertyInfo, Func<T, object>>(); public static readonly ConcurrentDictionary<PropertyInfo, Action<T, object>> PropertyValueSetters = new ConcurrentDictionary<PropertyInfo, Action<T, object>>(); } }
using System; using System.Collections.Concurrent; using System.Reflection; using WeihanLi.Common.DependencyInjection; namespace WeihanLi.Common { public static class CacheUtil { /// <summary> /// TypePropertyCache /// </summary> public static readonly ConcurrentDictionary<Type, PropertyInfo[]> TypePropertyCache = new ConcurrentDictionary<Type, PropertyInfo[]>(); internal static readonly ConcurrentDictionary<Type, FieldInfo[]> TypeFieldCache = new ConcurrentDictionary<Type, FieldInfo[]>(); internal static readonly ConcurrentDictionary<Type, MethodInfo[]> TypeMethodCache = new ConcurrentDictionary<Type, MethodInfo[]>(); internal static readonly ConcurrentDictionary<Type, Func<ServiceContainer, object>> TypeNewFuncCache = new ConcurrentDictionary<Type, Func<ServiceContainer, object>>(); internal static readonly ConcurrentDictionary<Type, ConstructorInfo> TypeConstructorCache = new ConcurrentDictionary<Type, ConstructorInfo>(); internal static readonly ConcurrentDictionary<Type, Func<object>> TypeEmptyConstructorFuncCache = new ConcurrentDictionary<Type, Func<object>>(); internal static readonly ConcurrentDictionary<Type, Func<object[], object>> TypeConstructorFuncCache = new ConcurrentDictionary<Type, Func<object[], object>>(); internal static readonly ConcurrentDictionary<PropertyInfo, Func<object, object>> PropertyValueGetters = new ConcurrentDictionary<PropertyInfo, Func<object, object>>(); internal static readonly ConcurrentDictionary<PropertyInfo, Action<object, object>> PropertyValueSetters = new ConcurrentDictionary<PropertyInfo, Action<object, object>>(); } internal static class StrongTypedCache<T> { public static ConcurrentDictionary<PropertyInfo, Func<T, object>> PropertyValueGetters = new ConcurrentDictionary<PropertyInfo, Func<T, object>>(); public static ConcurrentDictionary<PropertyInfo, Action<T, object>> PropertyValueSetters = new ConcurrentDictionary<PropertyInfo, Action<T, object>>(); } }
mit
C#
97e2b4ef3a6eb9e0572bfcc761e565e97e5d1f6a
Add Test to JSBridge
RonnChyran/snowflake,RonnChyran/snowflake,faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake,faint32/snowflake-1
Snowflake.API/Core/API/JSAPI/JSBridge.cs
Snowflake.API/Core/API/JSAPI/JSBridge.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Core.API; using Newtonsoft.Json; using Snowflake.Extensions; using Snowflake.Information.Game; namespace Snowflake.Core.API.JSAPI { public static class JSBridge { public static string GetAllPlatforms(JSRequest request) { return JSBridge.ProcessJSONP(CoreAPI.GetAllPlatforms(), request); } public static string GetGamesByPlatform(JSRequest request) { return JSBridge.ProcessJSONP(CoreAPI.GetGamesByPlatform(request.MethodParameters["platformid"]), request); } public static string GetTestGame(JSRequest request) { var platform = FrontendCore.LoadedCore.LoadedPlatforms["NINTENDO_NES"]; var game = platform.GetScrapeEngine().GetGameInfo("dummysmb.nes"); return JSBridge.ProcessJSONP(new Game[] {game}, request); } public static string Work(JSRequest request) { System.Threading.Thread.Sleep(100000); return "done"; } private static string ProcessJSONP(dynamic output, JSRequest request){ if (request.MethodParameters.ContainsKey("jsoncallback")) { return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(output) + ");"; } else { return JsonConvert.SerializeObject(output); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Core.API; using Newtonsoft.Json; namespace Snowflake.Core.API.JSAPI { public static class JSBridge { public static string GetAllPlatforms(JSRequest request) { return JSBridge.ProcessJSONP(CoreAPI.GetAllPlatforms(), request); } public static string GetGamesByPlatform(JSRequest request) { return JSBridge.ProcessJSONP(CoreAPI.GetGamesByPlatform(request.MethodParameters["platformid"]), request); } public static string Work(JSRequest request) { System.Threading.Thread.Sleep(100000); return "done"; } private static string ProcessJSONP(dynamic output, JSRequest request){ if (request.MethodParameters.ContainsKey("jsoncallback")) { return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(output) + ");"; } else { return JsonConvert.SerializeObject(output); } } } }
mpl-2.0
C#
21dc239007785e8249862b47ff402992e1302090
Use safe exception handling.
hozuki/MilliSim,hozuki/MilliSim,hozuki/MilliSim
src/TheaterDays/Theater.Startup.cs
src/TheaterDays/Theater.Startup.cs
using System; using CommandLine; using JetBrains.Annotations; using OpenMLTD.MilliSim.Core; using OpenMLTD.MilliSim.Graphics; using OpenMLTD.TheaterDays.Subsystems.Configuration; using OpenMLTD.TheaterDays.Subsystems.Globalization; using OpenMLTD.TheaterDays.Subsystems.Plugin; namespace OpenMLTD.TheaterDays { partial class Theater { public static int Run([NotNull, ItemNotNull] string[] args, GraphicsBackend graphicsBackend, [NotNull] string loggerName = "theater-days") { GraphicsBackend = graphicsBackend; GameLog.Initialize(loggerName); GameLog.Enabled = true; var exitCode = -1; var optionsParsingResult = Parser.Default.ParseArguments<Options>(args); #if ENABLE_GUI_CONSOLE GuiConsole.Initialize(); GuiConsole.Error.WriteLine(); #endif try { if (optionsParsingResult.Tag == ParserResultType.Parsed) { var options = ((Parsed<Options>)optionsParsingResult).Value; GameLog.Enabled = options.IsDebugEnabled; using (var pluginManager = new TheaterDaysPluginManager()) { pluginManager.LoadPlugins(); var configurationStore = ConfigurationHelper.CreateConfigurationStore(pluginManager); var cultureSpecificInfo = CultureSpecificInfoHelper.CreateCultureSpecificInfo(); using (var game = new Theater(pluginManager, configurationStore, cultureSpecificInfo)) { game.Run(); } exitCode = 0; } } else { var helpText = CommandLine.Text.HelpText.AutoBuild(optionsParsingResult); // TODO: Does this even work? GameLog.Info(helpText); } } catch (Exception ex) { GameLog.Error(ex.Message); GameLog.Error(ex.StackTrace); } #if ENABLE_GUI_CONSOLE GuiConsole.Uninitialize(); #endif return exitCode; } } }
using CommandLine; using JetBrains.Annotations; using OpenMLTD.MilliSim.Core; using OpenMLTD.MilliSim.Graphics; using OpenMLTD.TheaterDays.Subsystems.Configuration; using OpenMLTD.TheaterDays.Subsystems.Globalization; using OpenMLTD.TheaterDays.Subsystems.Plugin; namespace OpenMLTD.TheaterDays { partial class Theater { public static int Run([NotNull, ItemNotNull] string[] args, GraphicsBackend graphicsBackend, [NotNull] string loggerName = "theater-days") { GraphicsBackend = graphicsBackend; GameLog.Initialize(loggerName); GameLog.Enabled = true; var optionsParsingResult = Parser.Default.ParseArguments<Options>(args); int exitCode; #if ENABLE_GUI_CONSOLE GuiConsole.Initialize(); GuiConsole.Error.WriteLine(); #endif if (optionsParsingResult.Tag == ParserResultType.Parsed) { var options = ((Parsed<Options>)optionsParsingResult).Value; GameLog.Enabled = options.IsDebugEnabled; using (var pluginManager = new TheaterDaysPluginManager()) { pluginManager.LoadPlugins(); var configurationStore = ConfigurationHelper.CreateConfigurationStore(pluginManager); var cultureSpecificInfo = CultureSpecificInfoHelper.CreateCultureSpecificInfo(); using (var game = new Theater(pluginManager, configurationStore, cultureSpecificInfo)) { game.Run(); } exitCode = 0; } } else { var helpText = CommandLine.Text.HelpText.AutoBuild(optionsParsingResult); // TODO: Does this even work? GameLog.Info(helpText); exitCode = -1; } #if ENABLE_GUI_CONSOLE GuiConsole.Uninitialize(); #endif return exitCode; } } }
mit
C#
239fbaa9f7b0c6f26e4976413138ec8a6e308766
Bring back old event methods as obsoleted
peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
osu.Framework/Screens/Screen.cs
osu.Framework/Screens/Screen.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Timing; namespace osu.Framework.Screens { public class Screen : CompositeDrawable, IScreen { public bool ValidForResume { get; set; } = true; public bool ValidForPush { get; set; } = true; public sealed override bool RemoveWhenNotAlive => false; [Resolved] protected Game Game { get; private set; } public Screen() { RelativeSizeAxes = Axes.Both; } internal override void UpdateClock(IFrameBasedClock clock) { base.UpdateClock(clock); if (Parent != null && !(Parent is ScreenStack)) throw new InvalidOperationException($"Screens must always be added to a {nameof(ScreenStack)} (attempted to add {GetType()} to {Parent.GetType()})"); } #pragma warning disable CS0618 public virtual void OnEntering(ScreenEnterEvent e) => OnEntering(e.Last); public virtual bool OnExiting(ScreenExitEvent e) => OnExiting(e.Next); public virtual void OnResuming(ScreenResumeEvent e) => OnResuming(e.Last); public virtual void OnSuspending(ScreenSuspendEvent e) => OnSuspending(e.Next); #pragma warning restore CS0618 [Obsolete("Override OnEntering(ScreenEnterEvent) instead.")] // Can be removed 20221013 public virtual void OnEntering(IScreen last) { } [Obsolete("Override OnExiting(ScreenExitEvent) instead.")] // Can be removed 20221013 public virtual bool OnExiting(IScreen next) => false; [Obsolete("Override OnResuming(ScreenResumeEvent) instead.")] // Can be removed 20221013 public virtual void OnResuming(IScreen last) { } [Obsolete("Override OnSuspending(ScreenSuspendEvent) instead.")] // Can be removed 20221013 public virtual void OnSuspending(IScreen next) { } } }
// 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Timing; namespace osu.Framework.Screens { public class Screen : CompositeDrawable, IScreen { public bool ValidForResume { get; set; } = true; public bool ValidForPush { get; set; } = true; public sealed override bool RemoveWhenNotAlive => false; [Resolved] protected Game Game { get; private set; } public Screen() { RelativeSizeAxes = Axes.Both; } internal override void UpdateClock(IFrameBasedClock clock) { base.UpdateClock(clock); if (Parent != null && !(Parent is ScreenStack)) throw new InvalidOperationException($"Screens must always be added to a {nameof(ScreenStack)} (attempted to add {GetType()} to {Parent.GetType()})"); } public virtual void OnEntering(ScreenEnterEvent e) { } public virtual bool OnExiting(ScreenExitEvent e) => false; public virtual void OnResuming(ScreenResumeEvent e) { } public virtual void OnSuspending(ScreenSuspendEvent e) { } } }
mit
C#
6fdff6eae7a923b9329d4e5ede34462524ed4163
remove erroneous clustering key attributes in CassandraPeerState
Abc-Arbitrage/Zebus
src/Abc.Zebus.Persistence.CQL/Data/CassandraPeerState.cs
src/Abc.Zebus.Persistence.CQL/Data/CassandraPeerState.cs
using Abc.Zebus.Persistence.CQL.Storage; using Cassandra.Mapping.Attributes; namespace Abc.Zebus.Persistence.CQL.Data { [Table("PeerState", CaseSensitive = true)] public class CassandraPeerState { public CassandraPeerState(PeerState peerState) { PeerId = peerState.PeerId.ToString(); NonAckedMessageCount = peerState.NonAckedMessageCount; OldestNonAckedMessageTimestamp = peerState.OldestNonAckedMessageTimestampInTicks; } public CassandraPeerState() { } [PartitionKey] [Column("PeerId")] public string PeerId { get; set; } [Column("NonAckedMessageCount")] public int NonAckedMessageCount { get; set; } [Column("OldestNonAckedMessageTimestamp")] public long OldestNonAckedMessageTimestamp { get; set; } } }
using Abc.Zebus.Persistence.CQL.Storage; using Cassandra.Mapping.Attributes; namespace Abc.Zebus.Persistence.CQL.Data { [Table("PeerState", CaseSensitive = true)] public class CassandraPeerState { public CassandraPeerState(PeerState peerState) { PeerId = peerState.PeerId.ToString(); NonAckedMessageCount = peerState.NonAckedMessageCount; OldestNonAckedMessageTimestamp = peerState.OldestNonAckedMessageTimestampInTicks; } public CassandraPeerState() { } [PartitionKey(0)] [Column("PeerId")] public string PeerId { get; set; } [ClusteringKey] [Column("NonAckedMessageCount")] public int NonAckedMessageCount { get; set; } [ClusteringKey] [Column("OldestNonAckedMessageTimestamp")] public long OldestNonAckedMessageTimestamp { get; set; } } }
mit
C#
14b951664320ed27b8a3affd09a9a9fa9f3e2d08
Fix broken FxAssert helpers.
muhbaasu/fx-sharp
src/FxSharp.Tests/FxAssert.cs
src/FxSharp.Tests/FxAssert.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FxSharp.Tests { public static class FxAssert { public static void Throws<T, TRes>(Func<TRes> fn) where T : Exception { try { fn(); Assert.Fail(); } catch (T) { } } public static void Throws<T>(Action fn) where T : Exception { try { fn(); Assert.Fail(); } catch (T) { } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FxSharp.Tests { public static class FxAssert { public static void Throws<T, TRes>(Func<TRes> fn) where T : Exception { try { fn(); } catch (T) { Assert.Fail(); } } public static void Throws<T>(Action fn) where T : Exception { try { fn(); } catch (T) { Assert.Fail(); } } } }
apache-2.0
C#
f76fedfc36a4fce7181a3653aa3bb8d445e840ca
Fix XmlNamespaceOverrides for Message Header
DigDes/SoapCore
src/SoapCore/CustomMessage.cs
src/SoapCore/CustomMessage.cs
using System.ServiceModel.Channels; using System.Xml; namespace SoapCore { public class CustomMessage : Message { public CustomMessage() { } public CustomMessage(Message message) { Message = message; } public Message Message { get; internal set; } public XmlNamespaceManager NamespaceManager { get; internal set; } public System.Collections.Generic.Dictionary<string, string> AdditionalEnvelopeXmlnsAttributes { get; internal set; } public override MessageHeaders Headers => Message.Headers; public override MessageProperties Properties => Message.Properties; public override MessageVersion Version => Message.Version; public override bool IsEmpty => Message.IsEmpty; public override bool IsFault => Message.IsFault; protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer) { writer.WriteStartDocument(); var prefix = Version.Envelope.NamespacePrefix(NamespaceManager); writer.WriteStartElement(prefix, "Envelope", Version.Envelope.Namespace()); writer.WriteXmlnsAttribute(prefix, Version.Envelope.Namespace()); var xsdPrefix = Namespaces.AddNamespaceIfNotAlreadyPresentAndGetPrefix(NamespaceManager, "xsd", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute(xsdPrefix, Namespaces.XMLNS_XSD); var xsiPrefix = Namespaces.AddNamespaceIfNotAlreadyPresentAndGetPrefix(NamespaceManager, "xsi", Namespaces.XMLNS_XSI); writer.WriteXmlnsAttribute(xsiPrefix, Namespaces.XMLNS_XSI); if (AdditionalEnvelopeXmlnsAttributes != null) { foreach (var rec in AdditionalEnvelopeXmlnsAttributes) { writer.WriteXmlnsAttribute(rec.Key, rec.Value); } } } protected override void OnWriteStartHeaders(XmlDictionaryWriter writer) { writer.WriteStartElement(Version.Envelope.NamespacePrefix(NamespaceManager), "Header", Version.Envelope.Namespace()); } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { writer.WriteStartElement(Version.Envelope.NamespacePrefix(NamespaceManager), "Body", Version.Envelope.Namespace()); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { Message.WriteBodyContents(writer); } protected override void OnClose() { Message.Close(); base.OnClose(); } } }
using System.ServiceModel.Channels; using System.Xml; namespace SoapCore { public class CustomMessage : Message { public CustomMessage() { } public CustomMessage(Message message) { Message = message; } public Message Message { get; internal set; } public XmlNamespaceManager NamespaceManager { get; internal set; } public System.Collections.Generic.Dictionary<string, string> AdditionalEnvelopeXmlnsAttributes { get; internal set; } public override MessageHeaders Headers => Message.Headers; public override MessageProperties Properties => Message.Properties; public override MessageVersion Version => Message.Version; public override bool IsEmpty => Message.IsEmpty; public override bool IsFault => Message.IsFault; protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer) { writer.WriteStartDocument(); var prefix = Version.Envelope.NamespacePrefix(NamespaceManager); writer.WriteStartElement(prefix, "Envelope", Version.Envelope.Namespace()); writer.WriteXmlnsAttribute(prefix, Version.Envelope.Namespace()); var xsdPrefix = Namespaces.AddNamespaceIfNotAlreadyPresentAndGetPrefix(NamespaceManager, "xsd", Namespaces.XMLNS_XSD); writer.WriteXmlnsAttribute(xsdPrefix, Namespaces.XMLNS_XSD); var xsiPrefix = Namespaces.AddNamespaceIfNotAlreadyPresentAndGetPrefix(NamespaceManager, "xsi", Namespaces.XMLNS_XSI); writer.WriteXmlnsAttribute(xsiPrefix, Namespaces.XMLNS_XSI); if (AdditionalEnvelopeXmlnsAttributes != null) { foreach (var rec in AdditionalEnvelopeXmlnsAttributes) { writer.WriteXmlnsAttribute(rec.Key, rec.Value); } } } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { writer.WriteStartElement(Version.Envelope.NamespacePrefix(NamespaceManager), "Body", Version.Envelope.Namespace()); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { Message.WriteBodyContents(writer); } protected override void OnClose() { Message.Close(); base.OnClose(); } } }
mit
C#
7627781781d934c5e1ea8b7760b39e3fdec3677c
Rename Short to ShortField
laicasaane/VFW
Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Shorts.cs
Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Shorts.cs
using UnityEngine; namespace Vexe.Editor.GUIs { public abstract partial class BaseGUI { public short ShortField(short value) { return ShortField(string.Empty, value); } public short ShortField(string label, short value) { return ShortField(label, value, null); } public short ShortField(string label, string tooltip, short value) { return ShortField(label, tooltip, value, null); } public short ShortField(string label, short value, Layout option) { return ShortField(label, string.Empty, value, option); } public short ShortField(string label, string tooltip, short value, Layout option) { return ShortField(GetContent(label, tooltip), value, option); } public abstract short ShortField(GUIContent content, short value, Layout option); } }
using UnityEngine; namespace Vexe.Editor.GUIs { public abstract partial class BaseGUI { public short Short(short value) { return Short(string.Empty, value); } public short Short(string label, short value) { return Short(label, value, null); } public short Short(string label, string tooltip, short value) { return Short(label, tooltip, value, null); } public short Short(string label, short value, Layout option) { return Short(label, string.Empty, value, option); } public short Short(string label, string tooltip, short value, Layout option) { return Short(GetContent(label, tooltip), value, option); } public abstract short Short(GUIContent content, short value, Layout option); } }
mit
C#
a7742d61d9469d4a1da3ea592f5d84d7c23d60b6
Fix missing string format parameter
Microsoft/clrmd,cshung/clrmd,cshung/clrmd,tomasr/clrmd,Microsoft/clrmd
src/Microsoft.Diagnostics.Runtime/MemoryReadException.cs
src/Microsoft.Diagnostics.Runtime/MemoryReadException.cs
using System.IO; namespace Microsoft.Diagnostics.Runtime { /// <summary> /// Thrown when we fail to read memory from the target process. /// </summary> public class MemoryReadException : IOException { /// <summary> /// The address of memory that could not be read. /// </summary> public ulong Address { get; private set; } /// <summary> /// Constructor /// </summary> /// <param name="address">The address of memory that could not be read.</param> public MemoryReadException(ulong address) : base(string.Format("Could not read memory at {0:x}.", address)) { } } }
using System.IO; namespace Microsoft.Diagnostics.Runtime { /// <summary> /// Thrown when we fail to read memory from the target process. /// </summary> public class MemoryReadException : IOException { /// <summary> /// The address of memory that could not be read. /// </summary> public ulong Address { get; private set; } /// <summary> /// Constructor /// </summary> /// <param name="address">The address of memory that could not be read.</param> public MemoryReadException(ulong address) : base(string.Format("Could not read memory at {0:x}.")) { } } }
mit
C#
17fb0db1848ab475fc34fb4f205dd32f18fd6259
Add TcpClient property to Message, issue #9
BrandonPotter/SimpleTCP
SimpleTCP/Message.cs
SimpleTCP/Message.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace SimpleTCP { public class Message { private TcpClient _tcpClient; private System.Text.Encoding _encoder = null; private byte _writeLineDelimiter; private bool _autoTrim = false; internal Message(byte[] data, TcpClient tcpClient, System.Text.Encoding stringEncoder, byte lineDelimiter) { Data = data; _tcpClient = tcpClient; _encoder = stringEncoder; _writeLineDelimiter = lineDelimiter; } internal Message(byte[] data, TcpClient tcpClient, System.Text.Encoding stringEncoder, byte lineDelimiter, bool autoTrim) { Data = data; _tcpClient = tcpClient; _encoder = stringEncoder; _writeLineDelimiter = lineDelimiter; _autoTrim = autoTrim; } public byte[] Data { get; private set; } public string MessageString { get { if (_autoTrim) { return _encoder.GetString(Data).Trim(); } return _encoder.GetString(Data); } } public void Reply(byte[] data) { _tcpClient.GetStream().Write(data, 0, data.Length); } public void Reply(string data) { if (string.IsNullOrEmpty(data)) { return; } Reply(_encoder.GetBytes(data)); } public void ReplyLine(string data) { if (string.IsNullOrEmpty(data)) { return; } if (data.LastOrDefault() != _writeLineDelimiter) { Reply(data + _encoder.GetString(new byte[] { _writeLineDelimiter })); } else { Reply(data); } } public TcpClient TcpClient { get { return _tcpClient; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace SimpleTCP { public class Message { private TcpClient _tcpClient; private System.Text.Encoding _encoder = null; private byte _writeLineDelimiter; private bool _autoTrim = false; internal Message(byte[] data, TcpClient tcpClient, System.Text.Encoding stringEncoder, byte lineDelimiter) { Data = data; _tcpClient = tcpClient; _encoder = stringEncoder; _writeLineDelimiter = lineDelimiter; } internal Message(byte[] data, TcpClient tcpClient, System.Text.Encoding stringEncoder, byte lineDelimiter, bool autoTrim) { Data = data; _tcpClient = tcpClient; _encoder = stringEncoder; _writeLineDelimiter = lineDelimiter; _autoTrim = autoTrim; } public byte[] Data { get; private set; } public string MessageString { get { if (_autoTrim) { return _encoder.GetString(Data).Trim(); } return _encoder.GetString(Data); } } public void Reply(byte[] data) { _tcpClient.GetStream().Write(data, 0, data.Length); } public void Reply(string data) { if (string.IsNullOrEmpty(data)) { return; } Reply(_encoder.GetBytes(data)); } public void ReplyLine(string data) { if (string.IsNullOrEmpty(data)) { return; } if (data.LastOrDefault() != _writeLineDelimiter) { Reply(data + _encoder.GetString(new byte[] { _writeLineDelimiter })); } else { Reply(data); } } } }
apache-2.0
C#
3280ab006a0c16da345d5bb39e2e709962f4cf4f
add config option to send logging output to the console
assaframan/MoviesRestForAppHarbor,assaframan/MoviesRestForAppHarbor,ServiceStack/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,assaframan/MoviesRestForAppHarbor,zhaokunfay/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples
src/RedisStackOverflow/RedisStackOverflow/Global.asax.cs
src/RedisStackOverflow/RedisStackOverflow/Global.asax.cs
using System; using Funq; using RedisStackOverflow.ServiceInterface; using ServiceStack.Configuration; using ServiceStack.Logging; using ServiceStack.Logging.Support.Logging; using ServiceStack.Redis; using ServiceStack.WebHost.Endpoints; namespace RedisStackOverflow { public class AppHost : AppHostBase { public AppHost() : base("Redis StackOverflow", typeof(QuestionsService).Assembly) { } public override void Configure(Container container) { //Show StackTrace in Web Service Exceptions SetConfig(new EndpointHostConfig { DebugMode = true }); //Register any dependencies you want injected into your services container.Register<IRedisClientsManager>(c => new PooledRedisClientManager()); container.Register<IRepository>(c => new Repository(c.Resolve<IRedisClientsManager>())); } } public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { if (ConfigUtils.GetAppSetting("log","false") == "true") LogManager.LogFactory = new ConsoleLogFactory(); new AppHost().Init(); } } }
using System; using Funq; using RedisStackOverflow.ServiceInterface; using ServiceStack.Redis; using ServiceStack.WebHost.Endpoints; namespace RedisStackOverflow { public class AppHost : AppHostBase { public AppHost() : base("Redis StackOverflow", typeof(QuestionsService).Assembly) { } public override void Configure(Container container) { //Show StackTrace in Web Service Exceptions SetConfig(new EndpointHostConfig { DebugMode = true }); //Register any dependencies you want injected into your services container.Register<IRedisClientsManager>(c => new PooledRedisClientManager()); container.Register<IRepository>(c => new Repository(c.Resolve<IRedisClientsManager>())); } } public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { new AppHost().Init(); } } }
bsd-3-clause
C#
659b17cb1c021af87abdd4ccba09dd9a9b68bda0
Add delete endpoint
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/API/WeaponsController.cs
Battery-Commander.Web/Controllers/API/WeaponsController.cs
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]"), Authorize] public class WeaponsController : Controller { private readonly Database db; public WeaponsController(Database db) { this.db = db; } [HttpGet] public async Task<IEnumerable<dynamic>> Get() { // GET: api/weapons return await db .Weapons .Select(_ => new { _.Id, _.OpticSerial, _.OpticType, _.Serial, _.StockNumber, _.Type, _.UnitId }) .ToListAsync(); } [HttpPost] public async Task<IActionResult> Post(Weapon weapon) { await db.Weapons.AddAsync(weapon); await db.SaveChangesAsync(); return Ok(); } [HttpDelete] public async Task<IActionResult> Delete(int id) { var weapon = await db.Weapons.FindAsync(id); db.Weapons.Remove(weapon); await db.SaveChangesAsync(); return Ok(); } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]"), Authorize] public class WeaponsController : Controller { private readonly Database db; public WeaponsController(Database db) { this.db = db; } [HttpGet] public async Task<IEnumerable<dynamic>> Get() { // GET: api/weapons return await db .Weapons .Select(_ => new { _.Id, _.OpticSerial, _.OpticType, _.Serial, _.StockNumber, _.Type, _.UnitId }) .ToListAsync(); } [HttpPost] public async Task<IActionResult> Post(Weapon weapon) { await db.Weapons.AddAsync(weapon); await db.SaveChangesAsync(); return Ok(); } } }
mit
C#
e096628e3d9c67b5f80c5ebfa53e5154bd5d042b
Add method to get service settings
DotNetRu/App,DotNetRu/App
DotNetRu.AzureService/Controllers/DiagnosticsController.cs
DotNetRu.AzureService/Controllers/DiagnosticsController.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using DotNetRu.AzureService; namespace DotNetRu.Azure { [Route("diagnostics")] public class DiagnosticsController : ControllerBase { private readonly ILogger logger; private readonly RealmSettings realmSettings; private readonly TweetSettings tweetSettings; private readonly PushSettings pushSettings; private readonly VkontakteSettings vkontakteSettings; public DiagnosticsController( ILogger<DiagnosticsController> logger, RealmSettings realmSettings, TweetSettings tweetSettings, VkontakteSettings vkontakteSettings, PushSettings pushSettings) { this.logger = logger; this.realmSettings = realmSettings; this.tweetSettings = tweetSettings; this.vkontakteSettings = vkontakteSettings; this.pushSettings = pushSettings; } [HttpGet] [Route("settings")] public IActionResult Settings() { return new ObjectResult(new { RealmSettings = realmSettings, TweetSettings = tweetSettings, VkontakteSettings = vkontakteSettings, pushSettings = pushSettings }); } } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System; namespace DotNetRu.Azure { [Route("diagnostics")] public class DiagnosticsController : ControllerBase { private readonly ILogger logger; public DiagnosticsController( ILogger<DiagnosticsController> logger) { this.logger = logger; } [HttpPost] [Route("ping")] public async Task<IActionResult> Ping() { try { logger.LogInformation("Ping is requested"); return new OkObjectResult("Success"); } catch (Exception e) { logger.LogCritical(e, "Unhandled error while ping"); return new ObjectResult(e) { StatusCode = StatusCodes.Status500InternalServerError }; } } } }
mit
C#
1a62a3e205c1dd3ed4354f000be4acca55726145
Set the GetAvailableJobChunksResponseParser to explicitly internal since Doxygen doesn't understand C# very well.
RachelTucker/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk,SpectraLogic/ds3_net_powershell,RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,asomers/ds3_net_sdk,SpectraLogic/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,shabtaisharon/ds3_net_sdk,rpmoore/ds3_net_sdk,SpectraLogic/ds3_net_powershell,shabtaisharon/ds3_net_sdk
Ds3/ResponseParsers/GetAvailableJobChunksResponseParser.cs
Ds3/ResponseParsers/GetAvailableJobChunksResponseParser.cs
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using Ds3.Calls; using Ds3.Runtime; using System; using System.Linq; using System.Net; namespace Ds3.ResponseParsers { internal class GetAvailableJobChunksResponseParser : IResponseParser<GetAvailableJobChunksRequest, GetAvailableJobChunksResponse> { public GetAvailableJobChunksResponse Parse(GetAvailableJobChunksRequest request, IWebResponse response) { using (response) { ResponseParseUtilities.HandleStatusCode(response, HttpStatusCode.OK, HttpStatusCode.NotFound); using (var responseStream = response.GetResponseStream()) { switch (response.StatusCode) { case HttpStatusCode.OK: var jobResponse = JobResponseParser<GetAvailableJobChunksRequest>.ParseResponseContent(responseStream); if (jobResponse.ObjectLists.Any()) { return GetAvailableJobChunksResponse.Success(jobResponse); } return GetAvailableJobChunksResponse.RetryAfter(TimeSpan.FromSeconds(int.Parse(response.Headers["retry-after"]))); case HttpStatusCode.NotFound: return GetAvailableJobChunksResponse.JobGone; default: throw new NotSupportedException("This line of code should be impossible to hit."); } } } } } }
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using Ds3.Calls; using Ds3.Runtime; using System; using System.Linq; using System.Net; namespace Ds3.ResponseParsers { class GetAvailableJobChunksResponseParser : IResponseParser<GetAvailableJobChunksRequest, GetAvailableJobChunksResponse> { public GetAvailableJobChunksResponse Parse(GetAvailableJobChunksRequest request, IWebResponse response) { using (response) { ResponseParseUtilities.HandleStatusCode(response, HttpStatusCode.OK, HttpStatusCode.NotFound); using (var responseStream = response.GetResponseStream()) { switch (response.StatusCode) { case HttpStatusCode.OK: var jobResponse = JobResponseParser<GetAvailableJobChunksRequest>.ParseResponseContent(responseStream); if (jobResponse.ObjectLists.Any()) { return GetAvailableJobChunksResponse.Success(jobResponse); } return GetAvailableJobChunksResponse.RetryAfter(TimeSpan.FromSeconds(int.Parse(response.Headers["retry-after"]))); case HttpStatusCode.NotFound: return GetAvailableJobChunksResponse.JobGone; default: throw new NotSupportedException("This line of code should be impossible to hit."); } } } } } }
apache-2.0
C#
b0ef77efd9d3c185cfccf7e9540ca4093f21fb11
Fix V3093
Rohansi/Texter
Texter/TextRegion.cs
Texter/TextRegion.cs
using System; namespace Texter { public class TextRegion : ITextRenderer { public uint Width { get; private set; } public uint Height { get; private set; } private ITextRenderer _renderer; private int _startX; private int _startY; internal TextRegion(ITextRenderer renderer, int x, int y, uint w, uint h) { if (renderer == null) throw new ArgumentNullException("renderer"); _renderer = renderer; _startX = x; _startY = y; Width = w; Height = h; } public void Set(int x, int y, Character character, bool useBlending = true) { if (x < 0 || x > Width - 1 || y < 0 || y > Height - 1) return; _renderer.Set(_startX + x, _startY + y, character, useBlending); } public Character Get(int x, int y) { if (x < 0 || x > Width - 1 || y < 0 || y > Height - 1) return Character.Blank; return _renderer.Get(_startX + x, _startY + y); } } }
using System; namespace Texter { public class TextRegion : ITextRenderer { public uint Width { get; private set; } public uint Height { get; private set; } private ITextRenderer _renderer; private int _startX; private int _startY; internal TextRegion(ITextRenderer renderer, int x, int y, uint w, uint h) { if (renderer == null) throw new ArgumentNullException("renderer"); _renderer = renderer; _startX = x; _startY = y; Width = w; Height = h; } public void Set(int x, int y, Character character, bool useBlending = true) { if (x < 0 || x > Width - 1 | y < 0 | y > Height - 1) return; _renderer.Set(_startX + x, _startY + y, character, useBlending); } public Character Get(int x, int y) { if (x < 0 || x > Width - 1 | y < 0 | y > Height - 1) return Character.Blank; return _renderer.Get(_startX + x, _startY + y); } } }
mit
C#
ec8d119a45c1f092a21dab78b0141f9f36bffb28
Update GetWarningsForFontSubstitution.cs
aspose-cells/Aspose.Cells-for-.NET,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,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,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Articles/GetWarningsForFontSubstitution.cs
Examples/CSharp/Articles/GetWarningsForFontSubstitution.cs
using System.IO; using Aspose.Cells; using System.Diagnostics; namespace Aspose.Cells.Examples.Articles { //ExStart:1 public class GetWarningsForFontSubstitution : IWarningCallback { public void Warning(WarningInfo info) { if (info.WarningType == WarningType.FontSubstitution) { Debug.WriteLine("WARNING INFO: " + info.Description); } } static void Main() { Workbook workbook = new Workbook("F:\\AllExamples\\Aspose.Cells\\net\\TechnicalArticles\\Aspose.CellsGeneral\\GetWarningsForFontSubstitution\\Data\\source.xlsx"); PdfSaveOptions options = new PdfSaveOptions(); options.WarningCallback = new GetWarningsForFontSubstitution(); workbook.Save("F:\\AllExamples\\Aspose.Cells\\net\\TechnicalArticles\\Aspose.CellsGeneral\\GetWarningsForFontSubstitution\\Data\\output.pdf", options); } } //ExEnd:1 }
using System.IO; using Aspose.Cells; using System.Diagnostics; namespace Aspose.Cells.Examples.Articles { //ExStart:1 public class GetWarningsForFontSubstitution : IWarningCallback { public void Warning(WarningInfo info) { if (info.WarningType == WarningType.FontSubstitution) { Debug.WriteLine("WARNING INFO: " + info.Description); } } static void Main() { Workbook workbook = new Workbook("F:\\AllExamples\\Aspose.Cells\\net\\TechnicalArticles\\Aspose.CellsGeneral\\GetWarningsForFontSubstitution\\Data\\source.xlsx"); PdfSaveOptions options = new PdfSaveOptions(); options.WarningCallback = new GetWarningsForFontSubstitution(); workbook.Save("F:\\AllExamples\\Aspose.Cells\\net\\TechnicalArticles\\Aspose.CellsGeneral\\GetWarningsForFontSubstitution\\Data\\output.pdf", options); //ExEnd:1 } } }
mit
C#
91b3b791ff79621a48e56aa3df2553eca8a88936
Fix to avoid unwanted updates after builds
sitofabi/duplicati,sitofabi/duplicati,duplicati/duplicati,duplicati/duplicati,duplicati/duplicati,sitofabi/duplicati,sitofabi/duplicati,mnaiman/duplicati,mnaiman/duplicati,mnaiman/duplicati,mnaiman/duplicati,sitofabi/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati
Installer/Windows/UpdateVersion/Properties/AssemblyInfo.cs
Installer/Windows/UpdateVersion/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("UpdateVersion")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("2.0.0.7")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("UpdateVersion")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
lgpl-2.1
C#
da8f6785ae133c60d6bf7f6a9593814606b37702
Switch around year and nickname in AssemblyCopyright
OatmealDome/SplatoonUtilities
MusicRandomizer/MusicRandomizer/Properties/AssemblyInfo.cs
MusicRandomizer/MusicRandomizer/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("MusicRandomizer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MusicRandomizer")] [assembly: AssemblyCopyright("Copyright © 2016 OatmealDome")] [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("6b679e72-f65f-4d8a-a15d-7ffd4ed150d3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MusicRandomizer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MusicRandomizer")] [assembly: AssemblyCopyright("Copyright © OatmealDome 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6b679e72-f65f-4d8a-a15d-7ffd4ed150d3")] // 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#
961bea5cd3577eba03f5be8ca172c0d0ea6851b1
Add get best id method for person.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Get/People/TraktPerson.cs
Source/Lib/TraktApiSharp/Objects/Get/People/TraktPerson.cs
namespace TraktApiSharp.Objects.Get.People { using Extensions; using Newtonsoft.Json; using System; /// <summary>A Trakt person.</summary> public class TraktPerson { /// <summary>Gets or sets the person name.</summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary>Gets or sets the collection of ids for the person for various web services.</summary> [JsonProperty(PropertyName = "ids")] public TraktPersonIds Ids { get; set; } /// <summary>Gets or sets the collection of images and image sets for the person.</summary> [JsonProperty(PropertyName = "images")] public TraktPersonImages Images { get; set; } /// <summary>Gets or sets the biography of the person.</summary> [JsonProperty(PropertyName = "biography")] public string Biography { get; set; } /// <summary>Gets or sets the UTC datetime when the person was born.</summary> [JsonProperty(PropertyName = "birthday")] public DateTime? Birthday { get; set; } /// <summary>Gets or sets the UTC datetime when the person died.</summary> [JsonProperty(PropertyName = "death")] public DateTime? Death { get; set; } /// <summary>Returns the age of the person, if <see cref="Birthday" /> is set, otherwise zero.</summary> public int Age => Birthday.HasValue ? (Death.HasValue ? Birthday.YearsBetween(Death) : Birthday.YearsBetween(DateTime.Now)) : 0; /// <summary>Gets or sets the birthplace of the person.</summary> [JsonProperty(PropertyName = "birthplace")] public string Birthplace { get; set; } /// <summary>Gets or sets the web address of the homepage of the person.</summary> [JsonProperty(PropertyName = "homepage")] public string Homepage { get; set; } } }
namespace TraktApiSharp.Objects.Get.People { using Extensions; using Newtonsoft.Json; using System; public class TraktPerson { [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "ids")] public TraktPersonIds Ids { get; set; } [JsonProperty(PropertyName = "images")] public TraktPersonImages Images { get; set; } [JsonProperty(PropertyName = "biography")] public string Biography { get; set; } [JsonProperty(PropertyName = "birthday")] public DateTime? Birthday { get; set; } [JsonProperty(PropertyName = "death")] public DateTime? Death { get; set; } public int Age => Birthday.HasValue ? (Death.HasValue ? Birthday.YearsBetween(Death) : Birthday.YearsBetween(DateTime.Now)) : 0; [JsonProperty(PropertyName = "birthplace")] public string Birthplace { get; set; } [JsonProperty(PropertyName = "homepage")] public string Homepage { get; set; } } }
mit
C#
4eec1afd07eebedab12c19d2b4f038e1739d0923
Modify trace injector to http injector
criteo/zipkin4net,criteo/zipkin4net
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingHandler.cs
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingHandler.cs
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ZipkinHttpTraceInjector _injector; private readonly string _serviceName; public TracingHandler(string serviceName) : this(new ZipkinHttpTraceInjector(), serviceName) {} internal TracingHandler(ZipkinHttpTraceInjector injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ITraceInjector<HttpHeaders> _injector; private readonly string _serviceName; public TracingHandler(ITraceInjector<HttpHeaders> injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }
apache-2.0
C#
ade5805b083bf693bd6ea63a06ff0a94cdc62ede
Fix master server auto-update with /nightly flag
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer
LmpUpdater/Appveyor/AppveyorUpdateChecker.cs
LmpUpdater/Appveyor/AppveyorUpdateChecker.cs
using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.AppveyorUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } }
using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.ApiLatestGithubReleaseUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } }
mit
C#
c7a2632500e55901aab327a1ef60e06b9341335b
Correct a minor typo
ft-/arribasim-dev-tests,intari/OpenSimMirror,allquixotic/opensim-autobackup,AlphaStaxLLC/taiga,ft-/opensim-optimizations-wip-tests,cdbean/CySim,justinccdev/opensim,ft-/opensim-optimizations-wip,intari/OpenSimMirror,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,N3X15/VoxelSim,ft-/opensim-optimizations-wip,N3X15/VoxelSim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,OpenSimian/opensimulator,RavenB/opensim,rryk/omp-server,intari/OpenSimMirror,cdbean/CySim,ft-/arribasim-dev-tests,RavenB/opensim,M-O-S-E-S/opensim,allquixotic/opensim-autobackup,BogusCurry/arribasim-dev,Michelle-Argus/ArribasimExtract,zekizeki/agentservice,AlexRa/opensim-mods-Alex,rryk/omp-server,Michelle-Argus/ArribasimExtract,justinccdev/opensim,ft-/arribasim-dev-tests,bravelittlescientist/opensim-performance,Michelle-Argus/ArribasimExtract,TomDataworks/opensim,cdbean/CySim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,bravelittlescientist/opensim-performance,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,AlphaStaxLLC/taiga,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-tests,rryk/omp-server,AlphaStaxLLC/taiga,AlexRa/opensim-mods-Alex,QuillLittlefeather/opensim-1,cdbean/CySim,AlphaStaxLLC/taiga,justinccdev/opensim,bravelittlescientist/opensim-performance,rryk/omp-server,allquixotic/opensim-autobackup,BogusCurry/arribasim-dev,bravelittlescientist/opensim-performance,M-O-S-E-S/opensim,OpenSimian/opensimulator,zekizeki/agentservice,ft-/arribasim-dev-tests,justinccdev/opensim,TechplexEngineer/Aurora-Sim,allquixotic/opensim-autobackup,ft-/arribasim-dev-extras,BogusCurry/arribasim-dev,RavenB/opensim,rryk/omp-server,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,bravelittlescientist/opensim-performance,ft-/arribasim-dev-extras,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,QuillLittlefeather/opensim-1,AlphaStaxLLC/taiga,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,bravelittlescientist/opensim-performance,TomDataworks/opensim,TechplexEngineer/Aurora-Sim,N3X15/VoxelSim,zekizeki/agentservice,RavenB/opensim,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip,BogusCurry/arribasim-dev,AlphaStaxLLC/taiga,intari/OpenSimMirror,ft-/arribasim-dev-extras,zekizeki/agentservice,TomDataworks/opensim,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-extras,TechplexEngineer/Aurora-Sim,AlphaStaxLLC/taiga,cdbean/CySim,RavenB/opensim,ft-/arribasim-dev-extras,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,QuillLittlefeather/opensim-1,RavenB/opensim,BogusCurry/arribasim-dev,Michelle-Argus/ArribasimExtract,TechplexEngineer/Aurora-Sim,allquixotic/opensim-autobackup,M-O-S-E-S/opensim,M-O-S-E-S/opensim,N3X15/VoxelSim,AlexRa/opensim-mods-Alex,intari/OpenSimMirror,TomDataworks/opensim,ft-/arribasim-dev-extras,N3X15/VoxelSim,zekizeki/agentservice,TomDataworks/opensim,cdbean/CySim,ft-/opensim-optimizations-wip-tests,zekizeki/agentservice,ft-/opensim-optimizations-wip-extras,justinccdev/opensim,allquixotic/opensim-autobackup,intari/OpenSimMirror,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-extras,rryk/omp-server,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,QuillLittlefeather/opensim-1,N3X15/VoxelSim,AlphaStaxLLC/taiga,ft-/arribasim-dev-tests,QuillLittlefeather/opensim-1,RavenB/opensim,OpenSimian/opensimulator,AlexRa/opensim-mods-Alex,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,N3X15/VoxelSim,justinccdev/opensim,Michelle-Argus/ArribasimExtract,N3X15/VoxelSim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC
OpenSim/Services/Interfaces/IAuthenticationService.cs
OpenSim/Services/Interfaces/IAuthenticationService.cs
using System; using OpenMetaverse; namespace OpenSim.Services.Interfaces { public interface IAuthenticationService { string GetNewKey(UUID userID, UUID authToken); bool VerifyKey(UUID userID, string key); bool VerifySession(UUID userID, UUID sessionID); } }
using System; using OpenMetaverse; namespace OpenSim.Services.Interfaces { public interface IAuthenticationService { string GetNewKey(UUID userID, UUID authToken); bool VerifyKey(UUID userID, string key); bool VerifySession(UUID iserID, UUID sessionID); } }
bsd-3-clause
C#
463be0cec2ba8f804a168c1105a7387bc1df851a
Test boton random
Portafolio-titulo2017-Grupo3/Sistema_escritorio_NET
OrionEscritorio/OrionEscritorio/TEST_RAMA.Designer.cs
OrionEscritorio/OrionEscritorio/TEST_RAMA.Designer.cs
namespace OrionEscritorio { partial class TEST_RAMA { /// <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 Windows Form 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.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(58, 97); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; // // TEST_RAMA // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Controls.Add(this.button1); this.Name = "TEST_RAMA"; this.Text = "Nombre Cambiado"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button button1; } }
namespace OrionEscritorio { partial class TEST_RAMA { /// <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 Windows Form 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.SuspendLayout(); // // TEST_RAMA // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Name = "TEST_RAMA"; this.Text = "Nombre Cambiado"; this.ResumeLayout(false); } #endregion } }
mit
C#
91e514bb75e386f82e03affbf51e63573486fedd
change qctools extensions to .gz
IUMDPI/IUMediaHelperApps
Packager/Models/FileModels/QualityControlFileModel.cs
Packager/Models/FileModels/QualityControlFileModel.cs
using System.IO; namespace Packager.Models.FileModels { public class QualityControlFileModel : AbstractObjectFileModel { public QualityControlFileModel(AbstractObjectFileModel fileModel) { SequenceIndicator = fileModel.SequenceIndicator; Extension = ".gz"; FileUse = fileModel.FileUse; ProjectCode = fileModel.ProjectCode; BarCode = fileModel.BarCode; } public string ToIntermediateFileName() { return $"{ToFileNameWithoutExtension()}.xml"; } } }
using System.IO; namespace Packager.Models.FileModels { public class QualityControlFileModel : AbstractObjectFileModel { public QualityControlFileModel(AbstractObjectFileModel fileModel) { SequenceIndicator = fileModel.SequenceIndicator; Extension = ".zip"; FileUse = fileModel.FileUse; ProjectCode = fileModel.ProjectCode; BarCode = fileModel.BarCode; } public string ToIntermediateFileName() { return $"{ToFileNameWithoutExtension()}.xml"; } } }
apache-2.0
C#
16e725d4e4802f674175f6d6b82a6a0b6476244a
Test coverage for continue and return in loops
agileobjects/ReadableExpressions
ReadableExpressions.UnitTests/WhenTranslatingLoops.cs
ReadableExpressions.UnitTests/WhenTranslatingLoops.cs
namespace AgileObjects.ReadableExpressions.UnitTests { using System; using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class WhenTranslatingLoops { [TestMethod] public void ShouldTranslateAnInfiniteLoop() { Expression<Action> writeLine = () => Console.WriteLine(); var loop = Expression.Loop(writeLine.Body); var translated = loop.ToReadableString(); const string EXPECTED = @" while (true) { Console.WriteLine(); }"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } [TestMethod] public void ShouldTranslateALoopWithABreakStatement() { var intVariable = Expression.Variable(typeof(int), "i"); var intGreaterThanTwo = Expression.GreaterThan(intVariable, Expression.Constant(2)); var breakLoop = Expression.Break(Expression.Label()); var ifGreaterThanTwoBreak = Expression.IfThen(intGreaterThanTwo, breakLoop); Expression<Action> writeLine = () => Console.WriteLine(); var incrementVariable = Expression.Increment(intVariable); var loopBody = Expression.Block(ifGreaterThanTwoBreak, writeLine.Body, incrementVariable); var loop = Expression.Loop(loopBody, breakLoop.Target); var translated = loop.ToReadableString(); const string EXPECTED = @" while (true) { if (i > 2) { break; } Console.WriteLine(); ++i; }"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } [TestMethod] public void ShouldTranslateALoopWithAContinueStatement() { var intVariable = Expression.Variable(typeof(int), "i"); var intLessThanThree = Expression.LessThan(intVariable, Expression.Constant(3)); var incrementVariable = Expression.Increment(intVariable); var continueLoop = Expression.Continue(Expression.Label()); var incrementAndContinue = Expression.Block(incrementVariable, continueLoop); var ifLessThanThreeContinue = Expression.IfThen(intLessThanThree, incrementAndContinue); Expression<Action> writeFinished = () => Console.Write("Finished!"); var returnFromLoop = Expression.Return(Expression.Label()); var loopBody = Expression.Block(ifLessThanThreeContinue, writeFinished.Body, returnFromLoop); var loop = Expression.Loop(loopBody, returnFromLoop.Target, continueLoop.Target); var translated = loop.ToReadableString(); const string EXPECTED = @" while (true) { if (i < 3) { ++i; continue; } Console.Write(""Finished!""); return; }"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } } }
namespace AgileObjects.ReadableExpressions.UnitTests { using System; using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class WhenTranslatingLoops { [TestMethod] public void ShouldTranslateAnInfiniteLoop() { Expression<Action> writeLine = () => Console.WriteLine(); var loop = Expression.Loop(writeLine.Body); var translated = loop.ToReadableString(); const string EXPECTED = @" while (true) { Console.WriteLine(); }"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } [TestMethod] public void ShouldTranslateALoopWithABreakStatement() { var intVariable = Expression.Variable(typeof(int), "i"); var intGreaterThanTwo = Expression.GreaterThan(intVariable, Expression.Constant(2)); var breakLoop = Expression.Break(Expression.Label()); var ifGreaterThanTwoBreak = Expression.IfThen(intGreaterThanTwo, breakLoop); Expression<Action> writeLine = () => Console.WriteLine(); var incrementVariable = Expression.Increment(intVariable); var loopBody = Expression.Block(ifGreaterThanTwoBreak, writeLine.Body, incrementVariable); var loop = Expression.Loop(loopBody, breakLoop.Target); var translated = loop.ToReadableString(); const string EXPECTED = @" while (true) { if (i > 2) { break; } Console.WriteLine(); ++i; }"; Assert.AreEqual(EXPECTED.TrimStart(), translated); } } }
mit
C#
8d3bac2f83d077aeccc6ba2cb9486061bde711de
Fix TearDown in AccessTests
Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet
Tests/IntegrationTests.Shared/AccessTests.cs
Tests/IntegrationTests.Shared/AccessTests.cs
/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ using System.IO; using NUnit.Framework; using Realms; namespace IntegrationTests.Shared { [TestFixture] public class AccessTests { protected string _databasePath; protected Realm _realm; [SetUp] public void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [TearDown] public void TearDown() { _realm.Close(); Realm.DeleteRealm(_realm.Config); } [TestCase("NullableCharProperty", '0')] [TestCase("NullableByteProperty", (byte)100)] [TestCase("NullableInt16Property", (short)100)] [TestCase("NullableInt32Property", 100)] [TestCase("NullableInt64Property", 100L)] [TestCase("NullableSingleProperty", 123.123f)] [TestCase("NullableDoubleProperty", 123.123)] [TestCase("NullableBooleanProperty", true)] public void SetValueAndReplaceWithNull(string propertyName, object propertyValue) { AllTypesObject ato; using (var transaction = _realm.BeginWrite()) { ato = _realm.CreateObject<AllTypesObject>(); TestHelpers.SetPropertyValue(ato, propertyName, propertyValue); transaction.Commit(); } Assert.That(TestHelpers.GetPropertyValue(ato, propertyName), Is.EqualTo(propertyValue)); using (var transaction = _realm.BeginWrite()) { TestHelpers.SetPropertyValue(ato, propertyName, null); transaction.Commit(); } Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null)); } } }
/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ using System.IO; using NUnit.Framework; using Realms; namespace IntegrationTests.Shared { [TestFixture] public class AccessTests { protected string _databasePath; protected Realm _realm; [SetUp] public void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [TearDown] public void TearDown() { _realm.Dispose(); } [TestCase("NullableCharProperty", '0')] [TestCase("NullableByteProperty", (byte)100)] [TestCase("NullableInt16Property", (short)100)] [TestCase("NullableInt32Property", 100)] [TestCase("NullableInt64Property", 100L)] [TestCase("NullableSingleProperty", 123.123f)] [TestCase("NullableDoubleProperty", 123.123)] [TestCase("NullableBooleanProperty", true)] public void SetValueAndReplaceWithNull(string propertyName, object propertyValue) { AllTypesObject ato; using (var transaction = _realm.BeginWrite()) { ato = _realm.CreateObject<AllTypesObject>(); TestHelpers.SetPropertyValue(ato, propertyName, propertyValue); transaction.Commit(); } Assert.That(TestHelpers.GetPropertyValue(ato, propertyName), Is.EqualTo(propertyValue)); using (var transaction = _realm.BeginWrite()) { TestHelpers.SetPropertyValue(ato, propertyName, null); transaction.Commit(); } Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null)); } } }
apache-2.0
C#
3d84445e8b44675a645b692f2185ca54d28d801b
Update SimpleAdding.cs
michaeljwebb/Algorithm-Practice
Coderbyte/SimpleAdding.cs
Coderbyte/SimpleAdding.cs
//Add up all the numbers from 1 to num. using System; class MainClass { public static int SimpleAdding(int num) { int result = (num*(num+1))/2; num = result; return num; } static void Main() { // keep this function call here Console.WriteLine(SimpleAdding(Console.ReadLine())); } }
using System; class MainClass { public static int SimpleAdding(int num) { int result = (num*(num+1))/2; num = result; return num; } static void Main() { // keep this function call here Console.WriteLine(SimpleAdding(Console.ReadLine())); } }
mit
C#
fd3a26c25df88d1efc6c22172c6e12c03fd6557a
Write data to OBJ and MTL
Stefander/JPMeshConverter
D3DMeshConverter/Form1.cs
D3DMeshConverter/Form1.cs
using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String meshOutputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); String mtlOutputName = meshOutputName.Replace(".obj",".mtl"); String mtlName = mtlOutputName.Substring(mtlOutputName.LastIndexOf("\\")+1); File.WriteAllText(meshOutputName, mesh.GetObjData(mtlName)); File.WriteAllText(mtlOutputName,mesh.GetMtlData()); // Show the user it worked MessageBox.Show(meshOutputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } }
using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String outputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); File.WriteAllText(outputName, mesh.ToString()); // Show the user it worked MessageBox.Show(outputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } }
mit
C#
f2151687b7a675a0e0fda37bc1bf790f528cb3ba
Fix labs lasting FOR EVER
adurdin/ggj2015
Alcove/Assets/GameSession/GameConstants.cs
Alcove/Assets/GameSession/GameConstants.cs
using UnityEngine; using System.Collections; public class GameConstants { // Gameplay public const int PLAYER_COUNT = 2; public const int NUM_TRIBES_PER_PLAYER = 4; public const float RECRUITMENT_AREA_DEFAULT_SPAWN_TIME = 0.5f; public const float RECRUITMENT_AREA_GROUND_WIDTH = 15.0f; public const float RECRUITMENT_AREA_GROUND_Y = -0.54f; public const float RECRUITMENT_UNIT_WALK_SPEED = 0.5f; public const float RECRUITMENT_UNIT_ANIMATION_SPEED = 8.5f; public const float RECRUITMENT_UNIT_RUN_SPEED = 2.0f; public const float WORKING_AREA_GROUND_WIDTH = 5.0f; public const float WORKING_AREA_GROUND_Y = -0.54f; public const int PREGAME_DISPLAY_TIME = 110; public const int GO_MESSAGE_DISPLAY_TIME = 40; public const int MAX_NUMBER_OF_ACTIVE_LABORATORIES = 1; /* Balancing */ public const int TRIBE_STARTING_UNIT_COUNT = 4; public const int TRIBE_UNITS_PER_BEDCHAMBER = 4; public const float BASE_TOWER_SEGMENT_ACTION_TIME = 15.0f; // Always takes this full time public const int CONSTRUCTION_TOWER_SEGMENT_TRIBE_COST = 0; public const float BEDCHAMBERS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_ACTION_TIME = 180.0f; public const int BALLISTA_TOWER_SEGMENT_TRIBE_COST = 6; public const float CANNONS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float CANNONS_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int CANNONS_TOWER_SEGMENT_TRIBE_COST = 9; public const float LABORATORY_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float LABORATORY_TOWER_SEGMENT_ACTION_TIME = 1.0f; public const int LABORATORY_TOWER_SEGMENT_TRIBE_COST = 6; public const float WIZARDTOWER_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float WIZARDTOWER_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int WIZARDTOWER_TOWER_SEGMENT_TRIBE_COST = 8; public const float MURDERHOLES_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float MURDERHOLES_TOWER_SEGMENT_ACTION_TIME = 60.0f; public const int MURDERHOLES_TOWER_SEGMENT_TRIBE_COST = 4; public const float WIN_TOWER_SEGMENT_BUILD_TIME = 30.0f; // Always takes this full time public const int WIN_TOWER_SEGMENT_TRIBE_SIZE = 20; // Number of workers consumed per tribe when building }
using UnityEngine; using System.Collections; public class GameConstants { // Gameplay public const int PLAYER_COUNT = 2; public const int NUM_TRIBES_PER_PLAYER = 4; public const float RECRUITMENT_AREA_DEFAULT_SPAWN_TIME = 0.5f; public const float RECRUITMENT_AREA_GROUND_WIDTH = 15.0f; public const float RECRUITMENT_AREA_GROUND_Y = -0.54f; public const float RECRUITMENT_UNIT_WALK_SPEED = 0.5f; public const float RECRUITMENT_UNIT_ANIMATION_SPEED = 8.5f; public const float RECRUITMENT_UNIT_RUN_SPEED = 2.0f; public const float WORKING_AREA_GROUND_WIDTH = 5.0f; public const float WORKING_AREA_GROUND_Y = -0.54f; public const int PREGAME_DISPLAY_TIME = 110; public const int GO_MESSAGE_DISPLAY_TIME = 40; public const int MAX_NUMBER_OF_ACTIVE_LABORATORIES = 1; /* Balancing */ public const int TRIBE_STARTING_UNIT_COUNT = 4; public const int TRIBE_UNITS_PER_BEDCHAMBER = 4; public const float BASE_TOWER_SEGMENT_ACTION_TIME = 15.0f; // Always takes this full time public const int CONSTRUCTION_TOWER_SEGMENT_TRIBE_COST = 0; public const float BEDCHAMBERS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_ACTION_TIME = 180.0f; public const int BALLISTA_TOWER_SEGMENT_TRIBE_COST = 6; public const float CANNONS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float CANNONS_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int CANNONS_TOWER_SEGMENT_TRIBE_COST = 9; public const float LABORATORY_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float LABORATORY_TOWER_SEGMENT_ACTION_TIME = 50.0f; public const int LABORATORY_TOWER_SEGMENT_TRIBE_COST = 6; public const float WIZARDTOWER_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float WIZARDTOWER_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int WIZARDTOWER_TOWER_SEGMENT_TRIBE_COST = 8; public const float MURDERHOLES_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float MURDERHOLES_TOWER_SEGMENT_ACTION_TIME = 60.0f; public const int MURDERHOLES_TOWER_SEGMENT_TRIBE_COST = 4; public const float WIN_TOWER_SEGMENT_BUILD_TIME = 30.0f; // Always takes this full time public const int WIN_TOWER_SEGMENT_TRIBE_SIZE = 20; // Number of workers consumed per tribe when building }
mit
C#
5a4b80c73d04929c06bd8056d18de4e693f42494
Fix UnitTests build
lion92pl/IIUWr,lion92pl/IIUWr
IIUWr/UnitTests/Mocks/Fereol/HTMLParsing/HTTPConnection.cs
IIUWr/UnitTests/Mocks/Fereol/HTMLParsing/HTTPConnection.cs
using IIUWr.Fereol.HTMLParsing.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnitTests.Mocks.Fereol.HTMLParsing { internal class HTTPConnection : IHTTPConnection { private readonly string _result; public HTTPConnection(string htmlFilePath) { _result = System.IO.File.ReadAllText(htmlFilePath); } public Task<bool> CheckConnectionAsync() { throw new NotImplementedException(); } public Task<string> GetStringAsync(string relativeUri) { return Task.FromResult(_result); } public Task<string> Post(string relativeUri, Dictionary<string, string> formData, bool addMiddlewareToken = true) { return Task.FromResult(_result); } public Task<bool> LoginAsync(string username, string password) { return Task.FromResult(username == "test" && password == "mock"); } } }
using IIUWr.Fereol.HTMLParsing.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnitTests.Mocks.Fereol.HTMLParsing { internal class HTTPConnection : IHTTPConnection { private readonly string _result; public HTTPConnection(string htmlFilePath) { _result = System.IO.File.ReadAllText(htmlFilePath); } public Task<bool> CheckConnectionAsync() { throw new NotImplementedException(); } public async Task<string> GetStringAsync(string relativeUri) { return await Task.FromResult(_result); } public Task<bool> LoginAsync(string username, string password) { return Task<bool>.FromResult(username == "test" && password == "mock"); } } }
mit
C#
77f6fe29fac3252bc934b06b700ced01b6afd1ae
Fix TestController.
enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api
Infopulse.EDemocracy.Web/Controllers/API/TestController.cs
Infopulse.EDemocracy.Web/Controllers/API/TestController.cs
using System.Linq; using System.Web.Http; using Infopulse.EDemocracy.Web.Auth; namespace Infopulse.EDemocracy.Web.Controllers.API { public class TestController : BaseApiController { [HttpGet] [Authorize] [AuthorizationCheckFilter(RequiredRolesString = "admin")] [Route("api/test/ping")] public string Ping() { var repo = new Infopulse.EDemocracy.Data.Repositories.OrganizationRepository(); var organization = repo.GetAll().FirstOrDefault(); return "понґ від " + this.GetSignedInUserEmail() + " з організації '" + (organization?.Name ?? "unknown") + "'"; } } }
using System.Web; using System.Web.Http; using Infopulse.EDemocracy.Web.Auth; namespace Infopulse.EDemocracy.Web.Controllers.API { public class TestController : BaseApiController { [HttpGet] [Authorize] [AuthorizationCheckFilter(RequiredRolesString = "admin")] [Route("api/test/ping")] public string Ping() { var repo = new Infopulse.EDemocracy.Data.Repositories.OrganizationRepository(); var organization = repo.Get(1); return "понґ від " + this.GetSignedInUserEmail() + " з організації '" + organization.Name + "'"; } } }
cc0-1.0
C#
001368153870384ee1c6ae98b8d1e00c1e9ccec3
Bump assembly version
Redth/AndHUD,Redth/AndHUD
AndHUD/AssemblyVersion.cs
AndHUD/AssemblyVersion.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
apache-2.0
C#
98f3aba50c95fcb7b07174b7157c6e6eb91ae2d0
Remove years from copyright
terrajobst/nquery,terrajobst/nquery
Src/CommonAssemblyInfo.cs
Src/CommonAssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly : AssemblyCopyright("Copyright Immo Landwerth")] [assembly : AssemblyCompany("NQuery")] [assembly : AssemblyProduct("NQuery")] [assembly : CLSCompliant(false)] [assembly : ComVisible(false)] [assembly: AssemblyVersion("0.9.5.0")]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly : AssemblyCopyright("Copyright 2005 - 2012 by Immo Landwerth")] [assembly : AssemblyCompany("NQuery")] [assembly : AssemblyProduct("NQuery")] [assembly : CLSCompliant(false)] [assembly : ComVisible(false)] [assembly: AssemblyVersion("0.9.5.0")]
mit
C#
61db725061d209fb733fe9762bdfc7f6d91ecf2f
Update Entity.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/Entity.cs
TIKSN.Core/Data/Entity.cs
using System; namespace TIKSN.Data { public class Entity<T> : IEntity<T> where T : IEquatable<T> { public virtual T ID { get; } } }
using System; namespace TIKSN.Data { public class Entity<T> : IEntity<T> where T : IEquatable<T> { public virtual T ID { get; } } }
mit
C#
cb6d35a98aae26f050f80279ea0ad603e2847432
Add servicing breadcrumb attribute
yonglehou/WebApi,scz2011/WebApi,lungisam/WebApi,chimpinano/WebApi,congysu/WebApi,congysu/WebApi,abkmr/WebApi,lewischeng-ms/WebApi,LianwMS/WebApi,yonglehou/WebApi,chimpinano/WebApi,abkmr/WebApi,LianwMS/WebApi,lungisam/WebApi,lewischeng-ms/WebApi,scz2011/WebApi
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")] [assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETMVC && ASPNETWEBPAGES #error Runtime projects cannot define both ASPNETMVC and ASPNETWEBPAGES #elif ASPNETMVC [assembly: AssemblyVersion("5.0.0.0")] // ASPNETMVC #if !BUILD_GENERATED_VERSION [assembly: AssemblyFileVersion("5.0.0.0")] // ASPNETMVC #endif [assembly: AssemblyProduct("Microsoft ASP.NET MVC")] #elif ASPNETWEBPAGES [assembly: AssemblyVersion("3.0.0.0")] // ASPNETWEBPAGES #if !BUILD_GENERATED_VERSION [assembly: AssemblyFileVersion("3.0.0.0")] // ASPNETWEBPAGES #endif [assembly: AssemblyProduct("Microsoft ASP.NET Web Pages")] #else #error Runtime projects must define either ASPNETMVC or ASPNETWEBPAGES #endif
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")] [assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETMVC && ASPNETWEBPAGES #error Runtime projects cannot define both ASPNETMVC and ASPNETWEBPAGES #elif ASPNETMVC [assembly: AssemblyVersion("5.0.0.0")] // ASPNETMVC #if !BUILD_GENERATED_VERSION [assembly: AssemblyFileVersion("5.0.0.0")] // ASPNETMVC #endif [assembly: AssemblyProduct("Microsoft ASP.NET MVC")] #elif ASPNETWEBPAGES [assembly: AssemblyVersion("3.0.0.0")] // ASPNETWEBPAGES #if !BUILD_GENERATED_VERSION [assembly: AssemblyFileVersion("3.0.0.0")] // ASPNETWEBPAGES #endif [assembly: AssemblyProduct("Microsoft ASP.NET Web Pages")] #else #error Runtime projects must define either ASPNETMVC or ASPNETWEBPAGES #endif
mit
C#
478c247645b29d6eaf0e8d6a01a02c9066a292e0
Update ViewLocator.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/ViewLocator.cs
src/Core2D/ViewLocator.cs
#nullable enable using Avalonia.Controls; using Avalonia.Controls.Templates; using Core2D.ViewModels; using Dock.Model.ReactiveUI.Core; namespace Core2D { [StaticViewLocator] public partial class ViewLocator : IDataTemplate { public IControl Build(object data) { var type = data.GetType(); return s_views.TryGetValue(type, out var func) ? func.Invoke() : new TextBlock { Text = $"Unable to create view for type: {type}" }; } public bool Match(object data) { return data is ViewModelBase or DockableBase; } } }
#nullable disable using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using Core2D.ViewModels; using Dock.Model.ReactiveUI.Core; namespace Core2D { [StaticViewLocator] public partial class ViewLocator : IDataTemplate { public IControl Build(object data) { var type = data.GetType(); if (s_views.TryGetValue(type, out var func)) { return func?.Invoke(); } return new TextBlock { Text = $"Unable to create view for type: {type}" }; } public bool Match(object data) { return data is ViewModelBase or DockableBase; } } }
mit
C#
a2b39c473385bd773969e71e169fdbb0b1066c45
Revert "menu"
RichardZC/Nacimientos,RichardZC/Nacimientos,RichardZC/Nacimientos
BL/MenuBL.cs
BL/MenuBL.cs
using BE; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BL.Modelo; using System.Data.Entity; namespace BL { public class MenuBL : Repositorio<menu> { public static List<Menu> ListarMenu() { using (var bd = new nacEntities()) { var menu = bd.menu.Select(x => new Menu() { MenuId = x.MenuId, Denominacion = x.Denominacion, Estado = false }).ToList(); return menu; } } } }
unlicense
C#
960fb80f828b9ee2fd53d4b14d76dbddd06d24d9
update assemblyinfo
ravendb/ravendb.contrib
src/SharedAssemblyInfo.cs
src/SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("RavenDB Community")] [assembly: AssemblyProduct("RavenDB Contributions")] [assembly: AssemblyCopyright("Copyright © RavenDB Community Members")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("RavenDB Community")] [assembly: AssemblyProduct("RavenDB Contributions")] [assembly: AssemblyCopyright("Copyright © 2012 - RavenDB Community Members")] [assembly: ComVisible(false)]
mit
C#
2e168ca512aae82446dee8db211b325bf8a8b56a
Refactor Program_Downloads_Data_Files() to determine dynamically whether it should be skipped.
martincostello/electronicupdates,experiandataquality/electronicupdates,experiandataquality/electronicupdates,martincostello/electronicupdates,martincostello/electronicupdates,martincostello/electronicupdates,experiandataquality/electronicupdates,martincostello/electronicupdates,experiandataquality/electronicupdates,experiandataquality/electronicupdates
CSharp/MetadataWebApi/MetadataWebApi.Tests/IntegrationTests.cs
CSharp/MetadataWebApi/MetadataWebApi.Tests/IntegrationTests.cs
//----------------------------------------------------------------------- // <copyright file="IntegrationTests.cs" company="Experian Data Quality"> // Copyright (c) Experian. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.IO; using Xunit; using Xunit.Abstractions; namespace Experian.Qas.Updates.Metadata.WebApi.V1 { public class IntegrationTests { private readonly ITestOutputHelper _output; public IntegrationTests(ITestOutputHelper output) { _output = output; } [RequiresServiceCredentialsFact] public void Program_Downloads_Data_Files() { // Arrange using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { Console.SetOut(writer); try { // Act Program.MainInternal(); // Assert Assert.True(Directory.Exists("QASData")); Assert.NotEmpty(Directory.GetFiles("QASData", "*", SearchOption.AllDirectories)); } finally { _output.WriteLine(writer.ToString()); } } } private sealed class RequiresServiceCredentialsFact : FactAttribute { public RequiresServiceCredentialsFact() : base() { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("QAS:ElectronicUpdates:UserName")) || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("QAS:ElectronicUpdates:Password"))) { this.Skip = "No service credentials are configured."; } } } } }
//----------------------------------------------------------------------- // <copyright file="IntegrationTests.cs" company="Experian Data Quality"> // Copyright (c) Experian. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.IO; using Xunit; using Xunit.Abstractions; namespace Experian.Qas.Updates.Metadata.WebApi.V1 { public class IntegrationTests { private readonly ITestOutputHelper _output; public IntegrationTests(ITestOutputHelper output) { _output = output; } [Fact(Skip = "Requires access to a dedicated test account.")] public void Program_Downloads_Data_Files() { // Arrange Environment.SetEnvironmentVariable("QAS:ElectronicUpdates:UserName", string.Empty); Environment.SetEnvironmentVariable("QAS:ElectronicUpdates:Password", string.Empty); using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { Console.SetOut(writer); try { // Act Program.MainInternal(); // Assert Assert.True(Directory.Exists("QASData")); Assert.NotEmpty(Directory.GetFiles("QASData", "*", SearchOption.AllDirectories)); } finally { _output.WriteLine(writer.ToString()); } } } } }
apache-2.0
C#
10080a492aaafb5a3636fc8235eb6fc21a626e2b
Fix for balance null ref
mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection
src/Cash-Flow-Projection/Models/Balance.cs
src/Cash-Flow-Projection/Models/Balance.cs
using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account)?.Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account).Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }
mit
C#
fca2a4cd4de12eba0c40b4f606b6de627991c7dd
Add some paging stuff
Krusen/ErgastApi.Net
src/ErgastiApi/Responses/ErgastResponse.cs
src/ErgastiApi/Responses/ErgastResponse.cs
using System; using ErgastApi.Serialization; using Newtonsoft.Json; namespace ErgastApi.Responses { public interface IErgastResponse { string Url { get; } int Limit { get; } int Offset { get; } int Total { get; } int Page { get; } int TotalPages { get; } bool HasMorePages { get; } } public class ErgastResponse : IErgastResponse { public string Url { get; set; } public int Limit { get; set; } public int Offset { get; set; } public int Total { get; set; } // TODO: Note that it can be inaccurate if limit/offset do not correlate // TODO: Test with 0 values public int Page => Offset / Limit; // TODO: Test with 0 values public int TotalPages => (int) Math.Ceiling(Total / (double)Limit); // TODO: Test public bool HasMorePages => Total > Limit + Offset; } }
using ErgastApi.Serialization; using Newtonsoft.Json; namespace ErgastApi.Responses { public interface IErgastResponse { string Url { get; set; } int Limit { get; set; } int Offset { get; set; } int Total { get; set; } } public class ErgastResponse : IErgastResponse { public string Url { get; set; } public int Limit { get; set; } public int Offset { get; set; } public int Total { get; set; } } }
unlicense
C#
b71b082850e90e1a52294c55c9a0325a2b05f56f
Update MartijnVanDijk.cs
planetxamarin/planetxamarin,MabroukENG/planetxamarin,beraybentesen/planetxamarin,MabroukENG/planetxamarin,stvansolano/planetxamarin,beraybentesen/planetxamarin,planetxamarin/planetxamarin,stvansolano/planetxamarin,MabroukENG/planetxamarin,beraybentesen/planetxamarin,stvansolano/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/MartijnVanDijk.cs
src/Firehose.Web/Authors/MartijnVanDijk.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP { public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://medium.com/feed/@martijn00"); } } public string FirstName => "Martijn"; public string LastName => "Van Dijk"; public string StateOrRegion => "Amsterdam, Netherlands"; public string EmailAddress => "mhvdijk@gmail.com"; public string ShortBioOrTagLine => ""; public Uri WebSite => new Uri("https://medium.com/@martijn00"); public string TwitterHandle => "mhvdijk"; public string GravatarHash => "22155f520ab611cf04f76762556ca3f5"; public string GitHubHandle => string.Empty; public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680); } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP { public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://medium.com/feed/@martijn00"); } } public string FirstName => "Martijn"; public string LastName => "Van Dijk"; public string StateOrRegion => "Amsterdam, Netherlands"; public string EmailAddress => "mhvdijk@gmail.com"; public string ShortBioOrTagLine => "Xamarin consultant"; public Uri WebSite => new Uri("https://medium.com/@martijn00"); public string TwitterHandle => "mhvdijk"; public string GravatarHash => "22155f520ab611cf04f76762556ca3f5"; public string GitHubHandle => string.Empty; public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680); } }
mit
C#
5625cdc78931ce00d2146f6530aa5f33928ec172
Mark MsSqlCe40Dialect as supports variable limit (NH-3194)
gliljas/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core
src/NHibernate/Dialect/MsSqlCe40Dialect.cs
src/NHibernate/Dialect/MsSqlCe40Dialect.cs
using NHibernate.Dialect.Function; using NHibernate.SqlCommand; namespace NHibernate.Dialect { public class MsSqlCe40Dialect : MsSqlCeDialect { public MsSqlCe40Dialect() { RegisterFunction("concat", new VarArgsSQLFunction(NHibernateUtil.String, "(", "+", ")")); } public override bool SupportsLimit { get { return true; } } public override bool SupportsLimitOffset { get { return true; } } public override bool SupportsVariableLimit { get { return true; } } public override SqlString GetLimitString(SqlString queryString, SqlString offset, SqlString limit) { var builder = new SqlStringBuilder(queryString); if (queryString.IndexOfCaseInsensitive(" ORDER BY ") < 0) builder.Add(" ORDER BY GETDATE()"); builder.Add(" OFFSET "); if (offset == null) builder.Add("0"); else builder.Add(offset); builder.Add(" ROWS"); if (limit != null) { builder.Add(" FETCH NEXT "); builder.Add(limit); builder.Add(" ROWS ONLY"); } return builder.ToSqlString(); } } }
using NHibernate.Dialect.Function; using NHibernate.SqlCommand; namespace NHibernate.Dialect { public class MsSqlCe40Dialect : MsSqlCeDialect { public MsSqlCe40Dialect() { RegisterFunction("concat", new VarArgsSQLFunction(NHibernateUtil.String, "(", "+", ")")); } public override bool SupportsLimit { get { return true; } } public override bool SupportsLimitOffset { get { return true; } } public override SqlString GetLimitString(SqlString queryString, SqlString offset, SqlString limit) { SqlStringBuilder builder = new SqlStringBuilder(queryString); if (queryString.IndexOfCaseInsensitive(" ORDER BY ") < 0) builder.Add(" ORDER BY GETDATE()"); builder.Add(" OFFSET "); if (offset == null) builder.Add("0"); else builder.Add(offset); builder.Add(" ROWS"); if (limit != null) { builder.Add(" FETCH NEXT "); builder.Add(limit); builder.Add(" ROWS ONLY"); } return builder.ToSqlString(); } } }
lgpl-2.1
C#
e5419d7561a7f3f8d2cf545b18c9b407291ed1de
Update RequestedPermission.cs
timheuer/alexa-skills-dotnet,stoiveyp/alexa-skills-dotnet
Alexa.NET/Response/RequestedPermission.cs
Alexa.NET/Response/RequestedPermission.cs
using System; namespace Alexa.NET.Response { public static class RequestedPermission { public const string ReadHouseholdList = "alexa::household:lists:read"; public const string WriteHouseholdList = "alexa::household:lists:write"; public const string FullAddress = "read::alexa:device:all:address"; public const string AddressCountryAndPostalCode = "read::alexa:device:all:address:country_and_postal_code"; } }
using System; namespace Alexa.NET.Response { public static class RequestedPermission { public const string ReadHouseholdList = "read::alexa:household:list"; public const string WriteHouseholdList = "write::alexa:household:list"; public const string FullAddress = "read::alexa:device:all:address"; public const string AddressCountryAndPostalCode = "read::alexa:device:all:address:country_and_postal_code"; } }
mit
C#
60877901c9afd44cbf2b4f6cb3e22010d8a0c732
Prepare 0.6.1 release
LouisTakePILLz/ArgumentParser
ArgumentParser/Properties/AssemblyInfo.cs
ArgumentParser/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("ArgumentParser")] [assembly: AssemblyDescription("A rich and elegant library for parameter-parsing that supports various syntaxes and flavors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 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("a67b27e2-8841-4951-a6f0-a00d93f59560")] // 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.6.1.0")] [assembly: AssemblyFileVersion("0.6.1.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("ArgumentParser")] [assembly: AssemblyDescription("A rich and elegant library for parameter-parsing that supports various syntaxes and flavors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 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("a67b27e2-8841-4951-a6f0-a00d93f59560")] // 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.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")]
apache-2.0
C#
eef0eaa1901c51c638e98865a15ccdfd62f53731
Fix unity call in another thread
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
Client/Systems/VesselPartModuleSyncSys/VesselPartModuleSyncMessageHandler.cs
Client/Systems/VesselPartModuleSyncSys/VesselPartModuleSyncMessageHandler.cs
using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData)) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } }
using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData) || !System.PartSyncSystemReady) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } }
mit
C#
41cf8d5db407803fdeb39fcea4630ae98a75b405
Fix casing of German NaturalText
kappy/DateTimeExtensions
DateTimeExtensions/NaturalText/CultureStrategies/DE_DENaturalTimeStrategy.cs
DateTimeExtensions/NaturalText/CultureStrategies/DE_DENaturalTimeStrategy.cs
#region License // // Copyright (c) 2011-2012, João Matos Silva <kappy@acydburne.com.pt> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using DateTimeExtensions.Common; namespace DateTimeExtensions.NaturalText.CultureStrategies { [Locale("de-DE")] public class DE_DENaturalTimeStrategy : NaturalTimeStrategyBase { protected override string YearText { get { return "Jahr"; } } protected override string MonthText { get { return "Monat"; } } protected override string DayText { get { return "Tag"; } } protected override string HourText { get { return "Stunde"; } } protected override string MinuteText { get { return "Minute"; } } protected override string SecondText { get { return "Sekunde"; } } protected override string Pluralize(string text) { if (text.EndsWith("e")) { return text + "n"; } return text + "en"; } } }
#region License // // Copyright (c) 2011-2012, João Matos Silva <kappy@acydburne.com.pt> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using DateTimeExtensions.Common; namespace DateTimeExtensions.NaturalText.CultureStrategies { [Locale("de-DE")] public class DE_DENaturalTimeStrategy : NaturalTimeStrategyBase { protected override string YearText { get { return "jahr"; } } protected override string MonthText { get { return "monat"; } } protected override string DayText { get { return "tag"; } } protected override string HourText { get { return "stunde"; } } protected override string MinuteText { get { return "minute"; } } protected override string SecondText { get { return "sekunde"; } } protected override string Pluralize(string text) { if (text.EndsWith("e")) { return text + "n"; } return text + "en"; } } }
apache-2.0
C#
0269281a9c013b3089aa7c3f567678a22003b01a
Fix possible NullRef
awaescher/RepoZ,awaescher/RepoZ
RepoZ.Ipc/Repository.cs
RepoZ.Ipc/Repository.cs
namespace RepoZ.Ipc { [System.Diagnostics.DebuggerDisplay("{Name}")] public class Repository { public static Repository FromString(string value) { var parts = value?.Split(new string[] { "::" }, System.StringSplitOptions.None); var partsCount = parts?.Length ?? 0; var validFormat = partsCount == 3 || partsCount == 4; if (!validFormat) return null; return new Repository() { Name = parts[0], BranchWithStatus = parts[1], Path = parts[2], HasUnpushedChanges = parts.Length > 3 && parts[3] == "1", }; } public override string ToString() { if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(BranchWithStatus) || string.IsNullOrEmpty(Path)) return ""; return $"{Name}::{BranchWithStatus}::{Path}::{(HasUnpushedChanges ? "1" : "0")}"; } public string Name { get; set; } public string BranchWithStatus { get; set; } public string Path { get; set; } public bool HasUnpushedChanges { get; set; } public string SafePath { // use '/' for linux systems and bash command line (will work on cmd and powershell as well) get => Path?.Replace(@"\", "/") ?? ""; } } }
namespace RepoZ.Ipc { [System.Diagnostics.DebuggerDisplay("{Name}")] public class Repository { public static Repository FromString(string value) { var parts = value?.Split(new string[] { "::" }, System.StringSplitOptions.None); var validFormat = parts.Length == 3 || parts.Length == 4; if (!validFormat) return null; return new Repository() { Name = parts[0], BranchWithStatus = parts[1], Path = parts[2], HasUnpushedChanges = parts.Length > 3 && parts[3] == "1", }; } public override string ToString() { if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(BranchWithStatus) || string.IsNullOrEmpty(Path)) return ""; return $"{Name}::{BranchWithStatus}::{Path}::{(HasUnpushedChanges ? "1" : "0")}"; } public string Name { get; set; } public string BranchWithStatus { get; set; } public string Path { get; set; } public bool HasUnpushedChanges { get; set; } public string SafePath { // use '/' for linux systems and bash command line (will work on cmd and powershell as well) get => Path?.Replace(@"\", "/") ?? ""; } } }
mit
C#
f8fc78ce56f8f0744a5271a41de83ae2f7e0ca95
remove die button
Zogzer/Applebot,Yen/Applebot,Zogzer/Applebot
Services/PingService.cs
Services/PingService.cs
using System; using System.Globalization; using System.Threading; using System.Threading.Tasks; namespace Applebot.Services { class PingService : IGatewayConsumerService { public string FriendlyName => "Ping Pong"; public async Task ConsumeMessageAsync(IGatewayMessage message, CancellationToken ct) { var parts = message.Content.Split(null, 2); if (parts.Length >= 1 && parts[0] == "!ping") { var localTime = DateTimeOffset.Now; var timeMessage = localTime.Hour switch { < 4 or >= 20 => "I can see the stars clearly in the sky...", < 6 => "The stars are dimming and the sun is near...", >= 18 => "It's getting darker and the sun is dropping...", _ => "The sun is high in the sky, I can see for miles..." }; var fullMessage = string.Format( CultureInfo.InvariantCulture, "Pong! {0} I'd say it's about {1:HH:mm:ss} on {1:MMMM dd} from where I am!", timeMessage, localTime); await message.RespondToSenderAsync(fullMessage, ct); } if (parts.Length >= 1 && parts[0] == "!dead") { // throw new Exception("Yikes!"); } } } }
using System; using System.Globalization; using System.Threading; using System.Threading.Tasks; namespace Applebot.Services { class PingService : IGatewayConsumerService { public string FriendlyName => "Ping Pong"; public async Task ConsumeMessageAsync(IGatewayMessage message, CancellationToken ct) { var parts = message.Content.Split(null, 2); if (parts.Length >= 1 && parts[0] == "!ping") { var localTime = DateTimeOffset.Now; var timeMessage = localTime.Hour switch { < 4 or >= 20 => "I can see the stars clearly in the sky...", < 6 => "The stars are dimming and the sun is near...", >= 18 => "It's getting darker and the sun is dropping...", _ => "The sun is high in the sky, I can see for miles..." }; var fullMessage = string.Format( CultureInfo.InvariantCulture, "Pong! {0} I'd say it's about {1:HH:mm:ss} on {1:MMMM dd} from where I am!", timeMessage, localTime); await message.RespondToSenderAsync(fullMessage, ct); } if (parts.Length >= 1 && parts[0] == "!dead") { throw new Exception("Yikes!"); } } } }
mit
C#
eb33c42da9d71ca6808f008fad1f1be5c08115ff
correct polyfill order
sf-takaki-umemura/angular-study,asadsahi/AspNetCoreSpa,hillinworks/echoisles,mak-in/sf-attendance,mak-in/sf-attendance,s-gotou/SF-kinjiro,asadsahi/AspNetCoreSpa,s-gotou/SF-kinjiro,asadsahi/AspNetCoreSpa,asadsahi/AspNetCoreSpa,mak-in/sf-attendance,hillinworks/echoisles,sf-takaki-umemura/angular-study,sf-takaki-umemura/angular-study,mak-in/sf-attendance,s-gotou/SF-kinjiro,sf-takaki-umemura/angular-study,hillinworks/echoisles,hillinworks/echoisles,s-gotou/SF-kinjiro
Views/Home/Index.cshtml
Views/Home/Index.cshtml
<style> div.app-spinner { position: fixed; top: 50%; left: 50%; } </style> <div class="container"> <appc-root> <div class="app-spinner"> <i class="fa fa-spinner fa-spin fa-5x" aria-hidden="true"></i> </div> </appc-root> </div> <script> window.user = '@ViewBag.user'; </script> <environment names="Development"> <script src="~/dist/polyfills.dll.js" asp-append-version="true"></script> <script src="~/dist/vendor.dll.js" asp-append-version="true"></script> </environment> <script src="~/dist/@ViewBag.MainDotJs" asp-append-version="true"></script>
<style> div.app-spinner { position: fixed; top: 50%; left: 50%; } </style> <div class="container"> <appc-root> <div class="app-spinner"> <i class="fa fa-spinner fa-spin fa-5x" aria-hidden="true"></i> </div> </appc-root> </div> <script> window.user = '@ViewBag.user'; </script> <environment names="Development"> <script src="~/dist/vendor.dll.js" asp-append-version="true"></script> <script src="~/dist/polyfills.dll.js" asp-append-version="true"></script> </environment> <script src="~/dist/@ViewBag.MainDotJs" asp-append-version="true"></script>
mit
C#
f479c81cb637a93ae605e79b4c2326bf006b0c55
Update GetInput.cs
plivo/plivo-dotnet,plivo/plivo-dotnet
src/Plivo/XML/GetInput.cs
src/Plivo/XML/GetInput.cs
using dict = System.Collections.Generic.Dictionary<string, string>; using list = System.Collections.Generic.List<string>; namespace Plivo.XML { public class GetInput : PlivoElement { public GetInput(string body, dict parameters) : base(body, parameters) { Nestables = new list() { "Speak", "Play", "Wait" }; ValidAttributes = new list() { "action", "method", "inputType", "executionTimeout", "digitEndTimeout", "speechEndTimeout", "numDigits", "finishOnKey", "speechModel", "hints", "language", "interimSpeechResultsCallback", "interimSpeechResultsCallbackMethod", "log", "redirect", "profanityFilter" }; addAttributes(); } } }
using dict = System.Collections.Generic.Dictionary<string, string>; using list = System.Collections.Generic.List<string>; namespace Plivo.XML { public class GetInput : PlivoElement { public GetInput(string body, dict parameters) : base(body, parameters) { Nestables = new list() { "Speak", "Play", "Wait" }; ValidAttributes = new list() { "action", "method", "inputType", "executionTimeout", "digitEndTimeout", "speechEndTimeout", "finishOnKey", "speechModel", "hints", "language", "interimSpeechResultsCallback", "interimSpeechResultsCallbackMethod", "log", "redirect", "profanityFilter" }; addAttributes(); } } }
mit
C#
882ace6efea12be861efc400d5b61e0a8dd48a0d
Make MultiplayerRoomUser equatable
NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,peppy/osu
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomUser.cs
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomUser.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Users; namespace osu.Game.Online.RealtimeMultiplayer { public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser> { public MultiplayerRoomUser(in int userId) { UserID = userId; } public long UserID { get; } public MultiplayerUserState State { get; set; } public User User { get; set; } public bool Equals(MultiplayerRoomUser other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return UserID == other.UserID; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((MultiplayerRoomUser)obj); } public override int GetHashCode() => UserID.GetHashCode(); } }
// 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.Game.Users; namespace osu.Game.Online.RealtimeMultiplayer { public class MultiplayerRoomUser { public MultiplayerRoomUser(in int userId) { UserID = userId; } public long UserID { get; set; } public MultiplayerUserState State { get; set; } public User User { get; set; } } }
mit
C#
10d99a180da9d61d0b989f482a5fc1a45b3f420b
Optimize ToReadOnlyList when we know the length already
jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode,jskeet/DemoCode
Drums/VDrumExplorer.Utility/Enumerable.cs
Drums/VDrumExplorer.Utility/Enumerable.cs
// Copyright 2020 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace VDrumExplorer.Utility { /// <summary> /// LINQ-like methods for common operations within V-Drum Explorer. This is only not called /// Enumerable to avoid causing ambiguities for regular static method calls like <see cref="Enumerable.Range"/> /// etc. /// </summary> public static class VDrumEnumerable { /// <summary> /// Converts the sequence into a read-only wrapper around a <see cref="List{T}"/>. /// This method materializes the sequence. /// </summary> /// <typeparam name="T">The element type of the list.</typeparam> /// <param name="source">The sequence to convert.</param> /// <returns>A read-only wrapper around a <see cref="List{T}"/> containing the items in the sequence.</returns> public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> source) => source.ToList().AsReadOnly(); /// <summary> /// Converts the sequence into a read-only wrapper around a <see cref="List{TResult}"/> /// by first applying a transformation to each element. This method materializes the sequence. /// </summary> /// <typeparam name="TSource">The element type of the input sequence.</typeparam> /// <typeparam name="TResult">The element type of the result list.</typeparam> /// <param name="source">The sequence to convert.</param> /// <param name="selector">A transform function to apply to each element.</param> /// <returns>A read-only wrapper around a <see cref="List{T}"/> containing the items in the sequence.</returns> public static IReadOnlyList<TResult> ToReadOnlyList<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) { if (source is IList<TSource> list) { var result = new TResult[list.Count]; for (int i = 0; i < list.Count; i++) { result[i] = selector(list[i]); } return new ReadOnlyCollection<TResult>(result); } else { return source.Select(selector).ToList().AsReadOnly(); } } } }
// Copyright 2020 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Collections.Generic; using System.Linq; namespace VDrumExplorer.Utility { /// <summary> /// LINQ-like methods for common operations within V-Drum Explorer. This is only not called /// Enumerable to avoid causing ambiguities for regular static method calls like <see cref="Enumerable.Range"/> /// etc. /// </summary> public static class VDrumEnumerable { /// <summary> /// Converts the sequence into a read-only wrapper around a <see cref="List{T}"/>. /// This method materializes the sequence. /// </summary> /// <typeparam name="T">The element type of the list.</typeparam> /// <param name="source">The sequence to convert.</param> /// <returns>A read-only wrapper around a <see cref="List{T}"/> containing the items in the sequence.</returns> public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> source) => source.ToList().AsReadOnly(); /// <summary> /// Converts the sequence into a read-only wrapper around a <see cref="List{TResult}"/> /// by first applying a transformation to each element. This method materializes the sequence. /// </summary> /// <typeparam name="TSource">The element type of the input sequence.</typeparam> /// <typeparam name="TResult">The element type of the result list.</typeparam> /// <param name="source">The sequence to convert.</param> /// <param name="selector">A transform function to apply to each element.</param> /// <returns>A read-only wrapper around a <see cref="List{T}"/> containing the items in the sequence.</returns> public static IReadOnlyList<TResult> ToReadOnlyList<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) => source.Select(selector).ToList().AsReadOnly(); } }
apache-2.0
C#
2d4151245443ba166cb946c1b9db2313266c029c
update profiler test
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
test/WeihanLi.Common.Test/ProfilerTest.cs
test/WeihanLi.Common.Test/ProfilerTest.cs
using System.Threading; using Xunit; namespace WeihanLi.Common.Test { public class ProfilerTest { [Theory] [InlineData(100)] [InlineData(500)] [InlineData(1000)] public void StopWatchProfileTest(int delay) { var profiler = new StopwatchProfiler(); profiler.Start(); Thread.Sleep(delay*2); profiler.Stop(); Assert.True(profiler.ElapsedMilliseconds >= delay); profiler.Restart(); Thread.Sleep(delay / 2); profiler.Stop(); Assert.True(profiler.ElapsedMilliseconds < delay); profiler.Reset(); Assert.Equal(0, profiler.ElapsedMilliseconds); } } }
using System.Threading; using Xunit; namespace WeihanLi.Common.Test { public class ProfilerTest { [Theory] [InlineData(100)] [InlineData(500)] [InlineData(1000)] public void StopWatchProfileTest(int delay) { var profiler = new StopwatchProfiler(); profiler.Start(); Thread.Sleep(delay); profiler.Stop(); Assert.True(profiler.ElapsedMilliseconds >= delay); profiler.Restart(); Thread.Sleep(delay / 2); profiler.Stop(); Assert.True(profiler.ElapsedMilliseconds < delay); profiler.Reset(); Assert.Equal(0, profiler.ElapsedMilliseconds); } } }
mit
C#
2bc6932567548187d6696f4900ae98cfd1eaddc9
make interface mod applicable
UselessToucan/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu-new,ppy/osu,2yangk23/osu,ppy/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,EVAST9919/osu,smoogipooo/osu
osu.Game/Rulesets/Mods/IModHasSettings.cs
osu.Game/Rulesets/Mods/IModHasSettings.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.Graphics; namespace osu.Game.Rulesets.Mods { /// <summary> /// An interface for mods that allows user control over it's properties. /// </summary> public interface IModHasSettings : IApplicableMod { Drawable[] CreateControls(); } }
// 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.Graphics; namespace osu.Game.Rulesets.Mods { /// <summary> /// An interface for mods that allows user control over it's properties. /// </summary> public interface IModHasSettings { Drawable[] CreateControls(); } }
mit
C#
cde8de154d10e5470dac1f974938e861d2b8db72
Remove unused test property for now
ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu
osu.Game/Tests/Visual/TestReplayPlayer.cs
osu.Game/Tests/Visual/TestReplayPlayer.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.Collections.Generic; using System.Linq; using osu.Framework.Bindables; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { /// <summary> /// A player that exposes many components that would otherwise not be available, for testing purposes. /// </summary> public class TestReplayPlayer : ReplayPlayer { protected override bool PauseOnFocusLost { get; } public new DrawableRuleset DrawableRuleset => base.DrawableRuleset; /// <summary> /// Mods from *player* (not OsuScreen). /// </summary> public new Bindable<IReadOnlyList<Mod>> Mods => base.Mods; public new HUDOverlay HUDOverlay => base.HUDOverlay; public new GameplayClockContainer GameplayClockContainer => base.GameplayClockContainer; public new ScoreProcessor ScoreProcessor => base.ScoreProcessor; public new HealthProcessor HealthProcessor => base.HealthProcessor; public new bool PauseCooldownActive => base.PauseCooldownActive; /// <summary> /// Instantiate a replay player that renders an autoplay mod. /// </summary> public TestReplayPlayer(bool allowPause = true, bool showResults = true, bool pauseOnFocusLost = false) : base((beatmap, mods) => mods.OfType<ModAutoplay>().First().CreateReplayScore(beatmap, mods), new PlayerConfiguration { AllowPause = allowPause, ShowResults = showResults }) { PauseOnFocusLost = pauseOnFocusLost; } /// <summary> /// Instantiate a replay player that renders the provided replay. /// </summary> public TestReplayPlayer(Score score, bool allowPause = true, bool showResults = true, bool pauseOnFocusLost = false) : base(score, new PlayerConfiguration { AllowPause = allowPause, ShowResults = showResults }) { PauseOnFocusLost = pauseOnFocusLost; } } }
// 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.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { /// <summary> /// A player that exposes many components that would otherwise not be available, for testing purposes. /// </summary> public class TestReplayPlayer : ReplayPlayer { protected override bool PauseOnFocusLost { get; } public new DrawableRuleset DrawableRuleset => base.DrawableRuleset; /// <summary> /// Mods from *player* (not OsuScreen). /// </summary> public new Bindable<IReadOnlyList<Mod>> Mods => base.Mods; public new HUDOverlay HUDOverlay => base.HUDOverlay; public new GameplayClockContainer GameplayClockContainer => base.GameplayClockContainer; public new ScoreProcessor ScoreProcessor => base.ScoreProcessor; public new HealthProcessor HealthProcessor => base.HealthProcessor; public new bool PauseCooldownActive => base.PauseCooldownActive; public readonly List<JudgementResult> Results = new List<JudgementResult>(); /// <summary> /// Instantiate a replay player that renders an autoplay mod. /// </summary> public TestReplayPlayer(bool allowPause = true, bool showResults = true, bool pauseOnFocusLost = false) : base((beatmap, mods) => mods.OfType<ModAutoplay>().First().CreateReplayScore(beatmap, mods), new PlayerConfiguration { AllowPause = allowPause, ShowResults = showResults }) { PauseOnFocusLost = pauseOnFocusLost; } /// <summary> /// Instantiate a replay player that renders the provided replay. /// </summary> public TestReplayPlayer(Score score, bool allowPause = true, bool showResults = true, bool pauseOnFocusLost = false) : base(score, new PlayerConfiguration { AllowPause = allowPause, ShowResults = showResults }) { PauseOnFocusLost = pauseOnFocusLost; } [BackgroundDependencyLoader] private void load() { ScoreProcessor.NewJudgement += r => Results.Add(r); } } }
mit
C#
c3c3cb1490ca0c75898be137c2895d04c2d1b0a0
fix the name of the AppDirectory for the Content Editor
svmnotn/cuddly-octo-adventure
ContentCreator/Program.cs
ContentCreator/Program.cs
namespace COA.ContentCreator { using System; using System.IO; using System.Windows.Forms; using Data; using UI; static class Program { internal static string AppDirectory { get { return Extensions.CoreDirectory + @"\Content Creator"; } } internal static string WorkingDirectory { get { return AppDirectory + @"\Data"; } } internal static string TmpDirectory { get { return AppDirectory + @"\tmp"; } } internal static string AnswerName { get { return main.CurrentTopic + '\\' + main.currentQuestion.id + "_answer" + (DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime).Ticks; } } internal static MainScreen main; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); main = new MainScreen(Setup()); Application.Run(main); } static Archive Setup() { if(!Directory.Exists(WorkingDirectory)) { Directory.CreateDirectory(WorkingDirectory); ArchiveManager.SaveArchiveToDir(WorkingDirectory, Archive.Default); } return ArchiveManager.LoadArchiveFromDir(WorkingDirectory); } internal static string CopyTo(string from, string to, string newName) { var type = from.Split('.'); var name = newName + '.' + type[type.Length - 1]; var newPath = to + '\\' + name; File.Copy(from, newPath, true); return name; } } }
namespace COA.ContentCreator { using System; using System.IO; using System.Windows.Forms; using Data; using UI; static class Program { internal static string AppDirectory { get { return Extensions.CoreDirectory + @"\SGCC"; } } internal static string WorkingDirectory { get { return AppDirectory + @"\Data"; } } internal static string TmpDirectory { get { return AppDirectory + @"\tmp"; } } internal static string AnswerName { get { return main.CurrentTopic + '\\' + main.currentQuestion.id + "_answer" + (DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime).Ticks; } } internal static MainScreen main; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); main = new MainScreen(Setup()); Application.Run(main); } static Archive Setup() { if(!Directory.Exists(WorkingDirectory)) { Directory.CreateDirectory(WorkingDirectory); ArchiveManager.SaveArchiveToDir(WorkingDirectory, Archive.Default); } return ArchiveManager.LoadArchiveFromDir(WorkingDirectory); } internal static string CopyTo(string from, string to, string newName) { var type = from.Split('.'); var name = newName + '.' + type[type.Length - 1]; var newPath = to + '\\' + name; File.Copy(from, newPath, true); return name; } } }
mit
C#
8495409d8d9637293d82dca6c46e3f8e7660882c
Work around faulty StatusStrip implementations
jeoffman/EDDiscovery,jthorpe4/EDDiscovery,mwerle/EDDiscovery,jgoode/EDDiscovery,jeoffman/EDDiscovery,vendolis/EDDiscovery,jgoode/EDDiscovery,mwerle/EDDiscovery,vendolis/EDDiscovery
EDDiscovery/Controls/StatusStripCustom.cs
EDDiscovery/Controls/StatusStripCustom.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST) { if ((int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } else if ((int)m.Result == HT_CLIENT) { // Work around the implementation returning HT_CLIENT instead of HT_BOTTOMRIGHT int x = unchecked((short)((uint)m.LParam & 0xFFFF)); int y = unchecked((short)((uint)m.LParam >> 16)); Point p = PointToClient(new Point(x, y)); if (p.X >= this.ClientSize.Width - this.ClientSize.Height) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST && (int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } }
apache-2.0
C#
f9c9f1ce5f861b81c7506ece1dc71c8d4a94e8de
Bump version, amend.
JohanLarsson/Gu.Analyzers
Gu.Analyzers.Analyzers/Properties/AssemblyInfo.cs
Gu.Analyzers.Analyzers/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Gu.Analyzers.Analyzers")] [assembly: AssemblyDescription("Roslyn analyzers for GU.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johan Larsson")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.1.11.25")] [assembly: AssemblyFileVersion("0.1.11.25")] [assembly: AssemblyInformationalVersion("0.1.11.25-dev")] [assembly: InternalsVisibleTo("Gu.Analyzers.CodeFixes")] [assembly: InternalsVisibleTo("Gu.Analyzers.Benchmarks")] [assembly: InternalsVisibleTo("Gu.Analyzers.Test")]
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Gu.Analyzers.Analyzers")] [assembly: AssemblyDescription("Roslyn analyzers for GU.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johan Larsson")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.1.11.24")] [assembly: AssemblyFileVersion("0.1.11.24")] [assembly: AssemblyInformationalVersion("0.1.11.24-dev")] [assembly: InternalsVisibleTo("Gu.Analyzers.CodeFixes")] [assembly: InternalsVisibleTo("Gu.Analyzers.Benchmarks")] [assembly: InternalsVisibleTo("Gu.Analyzers.Test")]
mit
C#
f22050c9759648521ea2bd05f51b3932e718eb00
Remove unnecessary initialiser
smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu
osu.Game.Rulesets.Taiko/Difficulty/Preprocessing/TaikoDifficultyHitObject.cs
osu.Game.Rulesets.Taiko/Difficulty/Preprocessing/TaikoDifficultyHitObject.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.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Taiko.Objects; namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing { public class TaikoDifficultyHitObject : DifficultyHitObject { public readonly TaikoDifficultyHitObjectRhythm Rhythm; public readonly HitType? HitType; public bool StaminaCheese; public readonly int ObjectIndex; public TaikoDifficultyHitObject(HitObject hitObject, HitObject lastObject, HitObject lastLastObject, double clockRate, int objectIndex, IEnumerable<TaikoDifficultyHitObjectRhythm> commonRhythms) : base(hitObject, lastObject, clockRate) { var currentHit = hitObject as Hit; double prevLength = (lastObject.StartTime - lastLastObject.StartTime) / clockRate; Rhythm = getClosestRhythm(DeltaTime / prevLength, commonRhythms); HitType = currentHit?.Type; ObjectIndex = objectIndex; } private TaikoDifficultyHitObjectRhythm getClosestRhythm(double ratio, IEnumerable<TaikoDifficultyHitObjectRhythm> commonRhythms) { return commonRhythms.OrderBy(x => Math.Abs(x.Ratio - ratio)).First(); } } }
// 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.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Taiko.Objects; namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing { public class TaikoDifficultyHitObject : DifficultyHitObject { public readonly TaikoDifficultyHitObjectRhythm Rhythm; public readonly HitType? HitType; public bool StaminaCheese = false; public readonly int ObjectIndex; public TaikoDifficultyHitObject(HitObject hitObject, HitObject lastObject, HitObject lastLastObject, double clockRate, int objectIndex, IEnumerable<TaikoDifficultyHitObjectRhythm> commonRhythms) : base(hitObject, lastObject, clockRate) { var currentHit = hitObject as Hit; double prevLength = (lastObject.StartTime - lastLastObject.StartTime) / clockRate; Rhythm = getClosestRhythm(DeltaTime / prevLength, commonRhythms); HitType = currentHit?.Type; ObjectIndex = objectIndex; } private TaikoDifficultyHitObjectRhythm getClosestRhythm(double ratio, IEnumerable<TaikoDifficultyHitObjectRhythm> commonRhythms) { return commonRhythms.OrderBy(x => Math.Abs(x.Ratio - ratio)).First(); } } }
mit
C#
12c42eba609c04916aacdd108762b6bb298010ba
Fix failing tests on .NET Core 3.0
telerik/JustMockLite
Telerik.JustMock/Core/MatcherTree/MethodInfoMatcherTreeNode.cs
Telerik.JustMock/Core/MatcherTree/MethodInfoMatcherTreeNode.cs
/* JustMock Lite Copyright © 2010-2015 Progress Software Corporation 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.Linq; using System.Reflection; namespace Telerik.JustMock.Core.MatcherTree { internal class MethodInfoMatcherTreeNode : MatcherTreeNode { public MethodBase MethodInfo { get; private set; } public MethodInfoMatcherTreeNode(MethodBase m) : base(null) { this.MethodInfo = m; } public override IMatcherTreeNode Clone() { return new MethodInfoMatcherTreeNode(MethodInfo); } public void AddChild(CallPattern callPattern, MethodMockMatcherTreeNode node) { AddChildInternal(callPattern, 0, node); } public void AddChild(CallPattern callPattern, IMethodMock methodMock,int id) { var node = new MethodMockMatcherTreeNode(methodMock, id); callPattern.MethodMockNode = node; AddChildInternal(callPattern, 0, node); } public List<MethodMockMatcherTreeNode> GetAllMethodMocks(CallPattern callPattern) { List<MethodMockMatcherTreeNode> results = new List<MethodMockMatcherTreeNode>(); GetMethodMockInternal(callPattern, 0, results, MatchingOptions.Concretizing); return results; } public List<MethodMockMatcherTreeNode> GetMethodMock(CallPattern callPattern) { List<MethodMockMatcherTreeNode> results = new List<MethodMockMatcherTreeNode>(); GetMethodMockInternal(callPattern, 0, results, MatchingOptions.Generalizing); return results; } public void AddOrUpdateOccurence(CallPattern callPattern, IMethodMock mock) { AddOrUpdateOccurenceInternal(callPattern, 0, mock); } public List<OccurrencesMatcherTreeNode> GetOccurences(CallPattern callPattern) { List<OccurrencesMatcherTreeNode> results = new List<OccurrencesMatcherTreeNode>(); GetOccurencesInternal(callPattern, 0, results); return results; } } }
/* JustMock Lite Copyright © 2010-2015 Progress Software Corporation 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.Linq; using System.Reflection; namespace Telerik.JustMock.Core.MatcherTree { internal class MethodInfoMatcherTreeNode : MatcherTreeNode { public MethodBase MethodInfo { get; private set; } public MethodInfoMatcherTreeNode(MethodBase m) : base(null) { this.MethodInfo = m; } public override IMatcherTreeNode Clone() { return new MethodInfoMatcherTreeNode(MethodInfo); } public void AddChild(CallPattern callPattern, MethodMockMatcherTreeNode node) { AddChildInternal(callPattern, 0, node); } public void AddChild(CallPattern callPattern, IMethodMock methodMock,int id) { var node = new MethodMockMatcherTreeNode(methodMock, id); callPattern.MethodMockNode = node; AddChildInternal(callPattern, 0, node); } public List<MethodMockMatcherTreeNode> GetAllMethodMocks(CallPattern callPattern) { List<MethodMockMatcherTreeNode> results = new List<MethodMockMatcherTreeNode>(); GetMethodMockInternal(callPattern, 0, results, MatchingOptions.Concretizing); return results.ToList(); } public List<MethodMockMatcherTreeNode> GetMethodMock(CallPattern callPattern) { List<MethodMockMatcherTreeNode> results = new List<MethodMockMatcherTreeNode>(); GetMethodMockInternal(callPattern, 0, results, MatchingOptions.Generalizing); return results; } public void AddOrUpdateOccurence(CallPattern callPattern, IMethodMock mock) { AddOrUpdateOccurenceInternal(callPattern, 0, mock); } public List<OccurrencesMatcherTreeNode> GetOccurences(CallPattern callPattern) { List<OccurrencesMatcherTreeNode> results = new List<OccurrencesMatcherTreeNode>(); GetOccurencesInternal(callPattern, 0, results); return results; } } }
apache-2.0
C#
64ffe6362954032183ced01b0b3f8ca54cc68703
Revise control validation and test timeout
larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl
Tests/MatterControl.AutomationTests/HardwareLevelingUITests.cs
Tests/MatterControl.AutomationTests/HardwareLevelingUITests.cs
using System.Threading; using System.Threading.Tasks; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain, Apartment(ApartmentState.STA)] public class HardwareLevelingUITests { [Test] public async Task HasHardwareLevelingHidesLevelingSettings() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.WaitForFirstDraw(); // Add printer that has hardware leveling testRunner.AddAndSelectPrinter("Airwolf 3D", "HD"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsFalse(testRunner.WaitForName("print_leveling_solution Row", .5), "Print leveling should not exist for an Airwolf HD"); // Add printer that does not have hardware leveling testRunner.AddAndSelectPrinter("3D Factory", "MendelMax 1.5"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsTrue(testRunner.WaitForName("print_leveling_solution Row"), "Print leveling should exist for a 3D Factory MendelMax"); return Task.CompletedTask; }, overrideHeight: 800); } [Test, Category("Emulator")] public async Task SoftwareLevelingRequiredCorrectWorkflow() { await MatterControlUtilities.RunTest((testRunner) => { // make a jump start printer using (var emulator = testRunner.LaunchAndConnectToPrinterEmulator("JumpStart", "V1", runSlow: false)) { // make sure it is showing the correct button testRunner.OpenPrintPopupMenu(false, false); var startPrintButton = testRunner.GetWidgetByName("Start Print Button", out _); Assert.IsFalse(startPrintButton.Enabled, "Start Print should not be enabled"); testRunner.ClickByName("SetupPrinter"); testRunner.Complete9StepLeveling(); testRunner.OpenPrintPopupMenu(false, false); // make sure the button has changed to start print startPrintButton = testRunner.GetWidgetByName("Start Print Button", out _); Assert.IsTrue(startPrintButton.Enabled, "Start Print should be enabled after running printer setup"); Assert.IsFalse(testRunner.WaitForName("SetupPrinter", .5), "Finish Setup should not be visible after leveling the printer"); // reset to defaults and make sure print leveling is cleared testRunner.SwitchToSliceSettings(); testRunner.ClickByName("Printer Overflow Menu"); testRunner.ClickByName("Reset to Defaults Menu Item"); testRunner.ClickByName("Yes Button"); testRunner.OpenPrintPopupMenu(false, false); // make sure it is showing the correct button Assert.IsTrue(testRunner.WaitForName("SetupPrinter"), "Finish Setup should be visible after reset to Defaults"); } return Task.CompletedTask; }, maxTimeToRun: 90); } } }
using System.Threading; using System.Threading.Tasks; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain, Apartment(ApartmentState.STA)] public class HardwareLevelingUITests { [Test] public async Task HasHardwareLevelingHidesLevelingSettings() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.WaitForFirstDraw(); // Add printer that has hardware leveling testRunner.AddAndSelectPrinter("Airwolf 3D", "HD"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsFalse(testRunner.WaitForName("print_leveling_solution Row", .5), "Print leveling should not exist for an Airwolf HD"); // Add printer that does not have hardware leveling testRunner.AddAndSelectPrinter("3D Factory", "MendelMax 1.5"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsTrue(testRunner.WaitForName("print_leveling_solution Row"), "Print leveling should exist for a 3D Factory MendelMax"); return Task.CompletedTask; }, overrideHeight: 800); } [Test, Category("Emulator")] public async Task SoftwareLevelingRequiredCorrectWorkflow() { await MatterControlUtilities.RunTest((testRunner) => { // make a jump start printer using (var emulator = testRunner.LaunchAndConnectToPrinterEmulator("JumpStart", "V1", runSlow: false)) { // make sure it is showing the correct button testRunner.OpenPrintPopupMenu(false, false); // HACK: automatically resuming setup wizard. Long term we want a better plan testRunner.ClickByName("SetupPrinter"); testRunner.Complete9StepLeveling(); // make sure the button has changed to start print Assert.IsTrue(testRunner.WaitForName("PrintPopupMenu"), "Start Print should be visible after leveling the printer"); Assert.IsFalse(testRunner.WaitForName("SetupPrinter", .5), "Finish Setup should not be visible after leveling the printer"); // reset to defaults and make sure print leveling is cleared testRunner.SwitchToSliceSettings(); testRunner.ClickByName("Printer Overflow Menu"); testRunner.ClickByName("Reset to Defaults Menu Item"); testRunner.ClickByName("Yes Button"); testRunner.OpenPrintPopupMenu(false, false); // make sure it is showing the correct button Assert.IsTrue(testRunner.WaitForName("SetupPrinter"), "Finish Setup should be visible after reset to Defaults"); } return Task.CompletedTask; }); } } }
bsd-2-clause
C#
6b065d0db6d0feb3c942df21d2dfa0e8e8044782
Fix Health Check
dgarage/NBXplorer,dgarage/NBXplorer
NBXplorer/HealthChecks/NodesHealthCheck.cs
NBXplorer/HealthChecks/NodesHealthCheck.cs
using Microsoft.Extensions.Diagnostics.HealthChecks; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace NBXplorer.HealthChecks { public class NodesHealthCheck : IHealthCheck { public NodesHealthCheck(BitcoinDWaiters waiters) { Waiters = waiters; } public BitcoinDWaiters Waiters { get; } public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { bool ok = true; var data = new Dictionary<string, object>(); foreach (var waiter in Waiters.All()) { ok &= waiter.RPCAvailable; data.Add(waiter.Network.CryptoCode, waiter.State.ToString()); } return Task.FromResult(ok ? HealthCheckResult.Healthy(data: data) : HealthCheckResult.Degraded("Some nodes are not running", data: data)); } } }
using Microsoft.Extensions.Diagnostics.HealthChecks; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace NBXplorer.HealthChecks { public class NodesHealthCheck : IHealthCheck { public NodesHealthCheck(BitcoinDWaiters waiters) { Waiters = waiters; } public BitcoinDWaiters Waiters { get; } public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { bool ok = false; var data = new Dictionary<string, object>(); foreach (var waiter in Waiters.All()) { ok &= !waiter.RPCAvailable; data.Add(waiter.Network.CryptoCode, waiter.State.ToString()); } return Task.FromResult(ok ? HealthCheckResult.Healthy("Some nodes are not running", data: data) : HealthCheckResult.Degraded(data: data)); } } }
mit
C#
ed2f9dd4432fb1dbe17b6524f69fe3780c3b0919
Adjust settings slider spacings
NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu
osu.Game/Overlays/Settings/SettingsSlider.cs
osu.Game/Overlays/Settings/SettingsSlider.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsSlider<T> : SettingsSlider<T, OsuSliderBar<T>> where T : struct, IEquatable<T>, IComparable<T>, IConvertible { } public class SettingsSlider<TValue, TSlider> : SettingsItem<TValue> where TValue : struct, IEquatable<TValue>, IComparable<TValue>, IConvertible where TSlider : OsuSliderBar<TValue>, new() { protected override Drawable CreateControl() => new TSlider { Margin = new MarginPadding { Vertical = 10 }, RelativeSizeAxes = Axes.X }; /// <summary> /// When set, value changes based on user input are only transferred to any bound control's Current on commit. /// This is useful if the UI interaction could be adversely affected by the value changing, such as the position of the <see cref="SliderBar{T}"/> on the screen. /// </summary> public bool TransferValueOnCommit { get => ((TSlider)Control).TransferValueOnCommit; set => ((TSlider)Control).TransferValueOnCommit = value; } /// <summary> /// A custom step value for each key press which actuates a change on this control. /// </summary> public float KeyboardStep { get => ((TSlider)Control).KeyboardStep; set => ((TSlider)Control).KeyboardStep = value; } /// <summary> /// Whether to format the tooltip as a percentage or the actual value. /// </summary> public bool DisplayAsPercentage { get => ((TSlider)Control).DisplayAsPercentage; set => ((TSlider)Control).DisplayAsPercentage = value; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsSlider<T> : SettingsSlider<T, OsuSliderBar<T>> where T : struct, IEquatable<T>, IComparable<T>, IConvertible { } public class SettingsSlider<TValue, TSlider> : SettingsItem<TValue> where TValue : struct, IEquatable<TValue>, IComparable<TValue>, IConvertible where TSlider : OsuSliderBar<TValue>, new() { protected override Drawable CreateControl() => new TSlider { Margin = new MarginPadding { Top = 5, Bottom = 5 }, RelativeSizeAxes = Axes.X }; /// <summary> /// When set, value changes based on user input are only transferred to any bound control's Current on commit. /// This is useful if the UI interaction could be adversely affected by the value changing, such as the position of the <see cref="SliderBar{T}"/> on the screen. /// </summary> public bool TransferValueOnCommit { get => ((TSlider)Control).TransferValueOnCommit; set => ((TSlider)Control).TransferValueOnCommit = value; } /// <summary> /// A custom step value for each key press which actuates a change on this control. /// </summary> public float KeyboardStep { get => ((TSlider)Control).KeyboardStep; set => ((TSlider)Control).KeyboardStep = value; } /// <summary> /// Whether to format the tooltip as a percentage or the actual value. /// </summary> public bool DisplayAsPercentage { get => ((TSlider)Control).DisplayAsPercentage; set => ((TSlider)Control).DisplayAsPercentage = value; } } }
mit
C#
fcc6cb36e4c1e204e4ea106e6756b2cdb442bb48
Change text colour to black
UselessToucan/osu,smoogipooo/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu
osu.Game/Screens/Edit/Timing/RowAttribute.cs
osu.Game/Screens/Edit/Timing/RowAttribute.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Timing { public class RowAttribute : CompositeDrawable, IHasTooltip { private readonly string header; private readonly Func<string> content; private readonly Color4 colour; public RowAttribute(string header, Func<string> content, Color4 colour) { this.header = header; this.content = content; this.colour = colour; } [BackgroundDependencyLoader] private void load(OsuColour colours) { AutoSizeAxes = Axes.X; Height = 20; Anchor = Anchor.CentreLeft; Origin = Anchor.CentreLeft; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = colour, RelativeSizeAxes = Axes.Both, }, new OsuSpriteText { Padding = new MarginPadding(2), Anchor = Anchor.Centre, Origin = Anchor.Centre, Font = OsuFont.Default.With(weight: FontWeight.SemiBold, size: 12), Text = header, Colour = colours.Gray0 }, }; } public string TooltipText => content(); } }
// 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Timing { public class RowAttribute : CompositeDrawable, IHasTooltip { private readonly string header; private readonly Func<string> content; private readonly Color4 colour; public RowAttribute(string header, Func<string> content, Color4 colour) { this.header = header; this.content = content; this.colour = colour; } [BackgroundDependencyLoader] private void load(OsuColour colours) { AutoSizeAxes = Axes.X; Height = 20; Anchor = Anchor.CentreLeft; Origin = Anchor.CentreLeft; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = colour, RelativeSizeAxes = Axes.Both, }, new OsuSpriteText { Padding = new MarginPadding(2), Anchor = Anchor.Centre, Origin = Anchor.Centre, Font = OsuFont.Default.With(weight: FontWeight.SemiBold, size: 12), Text = header, Colour = colours.Gray3 }, }; } public string TooltipText => content(); } }
mit
C#
04acbdc2dc980d18dae94aa214a521a3657f1f2a
Fix for null values when stripping characters in feeds.
JaCraig/FileCurator,JaCraig/FileCurator
src/FileCurator/Formats/RSS/Data/Utils.cs
src/FileCurator/Formats/RSS/Data/Utils.cs
/* Copyright 2017 James Craig 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. */ namespace FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original?.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and") ?? ""; } } }
/* Copyright 2017 James Craig 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. */ namespace FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and"); } } }
apache-2.0
C#
45463c1b480659c465f27cae69cfe645c5d38e1a
Remove ununsed viewportWidth, viewportHeight
peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework
osu.Framework.Android/AndroidGameView.cs
osu.Framework.Android/AndroidGameView.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using Android.Content; using Android.Runtime; using Android.Util; using osuTK.Graphics; namespace osu.Framework.Android { public abstract class AndroidGameView : osuTK.Android.AndroidGameView { private AndroidGameHost host; public abstract Game CreateGame(); public AndroidGameView(Context context) : base(context) { init(); } public AndroidGameView(Context context, IAttributeSet attrs) : base(context, attrs) { init(); } public AndroidGameView(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { init(); } private void init() { AutoSetContextOnRenderFrame = true; ContextRenderingApi = GLVersion.ES3; } protected override void CreateFrameBuffer() { try { base.CreateFrameBuffer(); Log.Verbose("AndroidGameView", "Successfully created the framebuffer"); } catch (Exception e) { Log.Verbose("AndroidGameView", "{0}", e); throw new Exception("Can't load egl, aborting", e); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); RenderGame(); } [STAThread] public void RenderGame() { host = new AndroidGameHost(this); host.Run(CreateGame()); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using Android.Content; using Android.Runtime; using Android.Util; using osuTK.Graphics; namespace osu.Framework.Android { public abstract class AndroidGameView : osuTK.Android.AndroidGameView { private int viewportWidth, viewportHeight; private AndroidGameHost host; public abstract Game CreateGame(); public AndroidGameView(Context context) : base(context) { init(); } public AndroidGameView(Context context, IAttributeSet attrs) : base(context, attrs) { init(); } public AndroidGameView(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { init(); } private void init() { AutoSetContextOnRenderFrame = true; ContextRenderingApi = GLVersion.ES3; } protected override void CreateFrameBuffer() { try { base.CreateFrameBuffer(); Log.Verbose("AndroidGameView", "Successfully created the framebuffer"); } catch (Exception e) { Log.Verbose("AndroidGameView", "{0}", e); throw new Exception("Can't load egl, aborting", e); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); viewportHeight = Height; viewportWidth = Width; RenderGame(); } protected override void OnResize(EventArgs e) { viewportHeight = Height; viewportWidth = Width; } [STAThread] public void RenderGame() { host = new AndroidGameHost(this); host.Run(CreateGame()); } } }
mit
C#
051aeee9ffe507083a8e9189fecb785957a280ef
Convert apostrophe and ampersand to underscore in enum names (#939)
NJsonSchema/NJsonSchema,RSuter/NJsonSchema
src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs
src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs
//----------------------------------------------------------------------- // <copyright file="DefaultEnumNameGenerator.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- namespace NJsonSchema.CodeGeneration { /// <summary>The default enumeration name generator.</summary> public class DefaultEnumNameGenerator : IEnumNameGenerator { /// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema4 schema) { if (string.IsNullOrEmpty(name)) { return "Empty"; } if (name.StartsWith("_-")) { name = "__" + name.Substring(2); } return ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-").Replace(@"""", @""), true) .Replace(".", "_") .Replace(",", "_") .Replace("#", "_") .Replace("&", "_") .Replace("-", "_") .Replace("'", "_") .Replace("(", "_") .Replace(")", "_") .Replace("\\", "_"); } } }
//----------------------------------------------------------------------- // <copyright file="DefaultEnumNameGenerator.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- namespace NJsonSchema.CodeGeneration { /// <summary>The default enumeration name generator.</summary> public class DefaultEnumNameGenerator : IEnumNameGenerator { /// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema4 schema) { if (string.IsNullOrEmpty(name)) { return "Empty"; } if (name.StartsWith("_-")) { name = "__" + name.Substring(2); } return ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-").Replace(@"""", @""), true) .Replace(".", "_") .Replace(",", "_") .Replace("#", "_") .Replace("-", "_") .Replace("\\", "_"); } } }
mit
C#
427ac259f4121280b5c909aa26f043d015a31335
Refactor datatype configuration connector
tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmuseeg/Umbraco-CMS,bjarnef/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS
src/Umbraco.Core/Deploy/IDataTypeConfigurationConnector.cs
src/Umbraco.Core/Deploy/IDataTypeConfigurationConnector.cs
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Umbraco.Core.Models; namespace Umbraco.Core.Deploy { /// <summary> /// Defines methods that can convert a data type configurations to / from an environment-agnostic string. /// </summary> /// <remarks>Configurations may contain values such as content identifiers, that would be local /// to one environment, and need to be converted in order to be deployed.</remarks> [SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "This is actual only used by Deploy, but we dont want third parties to have references on deploy, thats why this interface is part of core.")] public interface IDataTypeConfigurationConnector { /// <summary> /// Gets the property editor aliases that the value converter supports by default. /// </summary> IEnumerable<string> PropertyEditorAliases { get; } /// <summary> /// Gets the artifact datatype configuration corresponding to the actual datatype configuration. /// </summary> /// <param name="dataType">The datatype.</param> /// <param name="dependencies">The dependencies.</param> IDictionary<string, object> ToArtifact(IDataType dataType, ICollection<ArtifactDependency> dependencies); /// <summary> /// Gets the actual datatype configuration corresponding to the artifact configuration. /// </summary> /// <param name="dataType">The datatype.</param> /// <param name="configuration">The artifact configuration.</param> object FromArtifact(IDataType dataType, IDictionary<string, object> configuration); } }
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Umbraco.Core.Deploy { /// <summary> /// Defines methods that can convert a data type configurations to / from an environment-agnostic string. /// </summary> /// <remarks>Configurations may contain values such as content identifiers, that would be local /// to one environment, and need to be converted in order to be deployed.</remarks> [SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "This is actual only used by Deploy, but we dont want third parties to have references on deploy, thats why this interface is part of core.")] public interface IDataTypeConfigurationConnector { /// <summary> /// Gets the property editor aliases that the value converter supports by default. /// </summary> IEnumerable<string> PropertyEditorAliases { get; } /// <summary> /// Gets the environment-agnostic data type configurations corresponding to environment-specific configurations. /// </summary> /// <param name="configuration">The environment-specific configuration.</param> /// <param name="dependencies">The dependencies.</param> /// <returns></returns> IDictionary<string, string> ConvertToDeploy(IDictionary<string, string> configuration, ICollection<ArtifactDependency> dependencies); /// <summary> /// Gets the environment-specific data type configurations corresponding to environment-agnostic configurations. /// </summary> /// <param name="configuration">The environment-agnostic configuration.</param> /// <returns></returns> IDictionary<string, string> ConvertToLocalEnvironment(IDictionary<string, string> configuration); } }
mit
C#
e01e405e245c0a171e612f7d883f9ff200886307
add m4a support
jasonracey/ConvertToMp3,jasonracey/ConvertToMp3
ConvertToMp3/FileFinder.cs
ConvertToMp3/FileFinder.cs
using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace ConvertToMp3 { public static class FileFinder { private static readonly List<string> Extensions = new List<string> { ".ape", ".flac", ".m4a", ".mp4" }; public static IEnumerable<string> GetSupportedFiles(string path) { return Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories) .Where(file => Extensions.Contains(Path.GetExtension(file) ?? string.Empty, StringComparer.OrdinalIgnoreCase)); } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace ConvertToMp3 { public static class FileFinder { private static readonly List<string> Extensions = new List<string> { ".ape", ".flac", ".mp4" }; public static IEnumerable<string> GetSupportedFiles(string path) { return Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories) .Where(file => Extensions.Contains(Path.GetExtension(file) ?? string.Empty, StringComparer.OrdinalIgnoreCase)); } } }
mit
C#
c3e0c65c57f79fce292335429a642ac02965fd70
Improve description of graph problem
jogonzal-msft/coding-interview-solutions,jogonzal/coding-interview-solutions
CodingInterviewSolutions/CodingInterviewSolutions/Named/GraphSerialization.cs
CodingInterviewSolutions/CodingInterviewSolutions/Named/GraphSerialization.cs
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace CodingInterviewSolutions.Named { /// <summary> /// Problem description: Given a graph formed by nodes described by the class "Node" below, we want to serialize it. /// You have access to a JSON serializer (e.g. JSON.stringify for JS or JSON.NET for C#) that can serialize DAGs (Directed Acyclic Graph), however, it didn't work for all graphs in your test cases. /// (Candidate should ask/suggest these are possible problems) Problem 1: The graph contains cycles (node1 -> node2 -> node1 -> node2) and (optional) Problem 2: a node can have multiple parents (e.g. node1 can be a child of node2 and of node3) /// Hint1: For a graph that contains cycles, when you used your JSON serializer that works on DAGs, it threw an error "Converting circular structure to JSON" /// Hint2: For a graph that contains nodes with multiple parents, you noticed the serializer worked, but it serialized the same node multiple times. In a case where a node was the child of all other N nodes in the graph, it serialized that node N times. /// Solution 1 (implemented here): A. Add ids to all nodes B. Whenever you see a node that you've already seen in the graph, serialize only its id /// Solution 2: Add ids to all nodes. Serialize the connections of the nodes as an array with only their id's (e.g. [node1 -> node2, node1 -> node3, ...]) /// and serialize all unique nodes in a linear list. /// Bonus: Build a deserializer for the results of your serializers /// </summary> public static class GraphSerialization { public class Node { public Dictionary<string, string> Properties { get; set; } public List<Node> Connections { get; set; } } /// <summary> /// There are a couple things we need to watch out for here: /// 1. We'll generate a new node for serialization - we'll add to that node only if the node was /// never seen before (keep a HashSet of seen nodes) /// 2. If the node was seen before, we'll only serialize it's id. /// If not, then serialize it fully (with children and properties) /// </summary> public static string SerializeGraph(Node rootNode) { Dictionary<Node, Guid> visitedNodes = new Dictionary<Node, Guid>(); SerializableNode serializableRootNode = GetSerializableNode(rootNode, visitedNodes); return JsonConvert.SerializeObject(serializableRootNode); } private static SerializableNode GetSerializableNode(Node node, Dictionary<Node, Guid> visitedNodes) { Guid id; if (visitedNodes.TryGetValue(node, out id)) { // Node has been previously serialized - just serialize it's ID return new SerializableNode(){ Id = id }; } else { // Add to visited id = Guid.NewGuid(); visitedNodes.Add(node, id); // Get children List<SerializableNode> connections = null; if (node.Connections != null && node.Connections.Count > 0){ connections = node.Connections.Select(n => GetSerializableNode(n, visitedNodes)).ToList(); } // Return node with id, properties and connections return new SerializableNode(){ Id = id, Properties = node.Properties, Connections = node.Connections }; } } /// <summary> /// Used to append an id to every single node /// </summary> private class SerializableNode : Node { public Guid Id { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace CodingInterviewSolutions.Named { /// <summary> /// This problem consists on serializing and deserializing a graph object given below /// </summary> public static class GraphSerialization { public class Node { public Dictionary<string, string> Properties { get; set; } public List<Node> Connections { get; set; } } /// <summary> /// There are a couple things we need to watch out for here: /// 1. We'll generate a new node for serialization - we'll add to that node only if the node was /// never seen before (keep a HashSet of seen nodes) /// 2. If the node was seen before, we'll only serialize it's id. /// If not, then serialize it fully (with children and properties) /// </summary> public static string SerializeGraph(Node rootNode) { Dictionary<Node, Guid> visitedNodes = new Dictionary<Node, Guid>(); SerializableNode serializableRootNode = GetSerializableNode(rootNode, visitedNodes); return JsonConvert.SerializeObject(serializableRootNode); } private static SerializableNode GetSerializableNode(Node node, Dictionary<Node, Guid> visitedNodes) { Guid id; if (visitedNodes.TryGetValue(node, out id)) { // Node has been previously serialized - just serialize it's ID return new SerializableNode(){ Id = id }; } else { // Add to visited id = Guid.NewGuid(); visitedNodes.Add(node, id); // Get children List<SerializableNode> connections = null; if (node.Connections != null && node.Connections.Count > 0){ connections = node.Connections.Select(n => GetSerializableNode(n, visitedNodes)).ToList(); } // Return node with id, properties and connections return new SerializableNode(){ Id = id, Properties = node.Properties, Connections = node.Connections }; } } /// <summary> /// Used to append an id to every single node /// </summary> private class SerializableNode : Node { public Guid Id { get; set; } } } }
mit
C#
a8f976f8c55cdf462fcb4b1536a53cf846f3a3b9
Fix #502
Lone-Coder/letsencrypt-win-simple
letsencrypt-win-simple/ScheduledRenewal.cs
letsencrypt-win-simple/ScheduledRenewal.cs
using System; using System.IO; using System.Linq; using Newtonsoft.Json; using Serilog; using System.Collections.Generic; namespace LetsEncrypt.ACME.Simple { public class ScheduledRenewal { public DateTime Date { get; set; } public Target Binding { get; set; } public string CentralSsl { get; set; } public string San { get; set; } public string KeepExisting { get; set; } public string Script { get; set; } public string ScriptParameters { get; set; } public bool Warmup { get; set; } public AzureOptions AzureOptions { get; set; } public override string ToString() => $"{Binding} Renew After {Date.ToShortDateString()}"; internal string Save() { return JsonConvert.SerializeObject(this); } internal static ScheduledRenewal Load(string renewal) { var result = JsonConvert.DeserializeObject<ScheduledRenewal>(renewal); if (result == null || result.Binding == null) { Log.Error("Unable to deserialize renewal {renewal}", renewal); return null; } if (result.Binding.AlternativeNames == null) { result.Binding.AlternativeNames = new List<string>(); } if (result.Binding.Plugin == null) { Log.Error("Plugin {plugin} not found", result.Binding.PluginName); return null; } try { result.Binding.Plugin.Refresh(result); } catch (Exception ex) { Log.Warning("Error refreshing renewal for {host} - {@ex}", result.Binding.Host, ex); } return result; } } }
using System; using System.IO; using System.Linq; using Newtonsoft.Json; using Serilog; namespace LetsEncrypt.ACME.Simple { public class ScheduledRenewal { public DateTime Date { get; set; } public Target Binding { get; set; } public string CentralSsl { get; set; } public string San { get; set; } public string KeepExisting { get; set; } public string Script { get; set; } public string ScriptParameters { get; set; } public bool Warmup { get; set; } public AzureOptions AzureOptions { get; set; } public override string ToString() => $"{Binding} Renew After {Date.ToShortDateString()}"; internal string Save() { return JsonConvert.SerializeObject(this); } internal static ScheduledRenewal Load(string renewal) { var result = JsonConvert.DeserializeObject<ScheduledRenewal>(renewal); if (result == null || result.Binding == null) { Log.Error("Unable to deserialize renewal {renewal}", renewal); return null; } if (result.Binding.Plugin == null) { Log.Error("Plugin {plugin} not found", result.Binding.PluginName); return null; } try { result.Binding.Plugin.Refresh(result); } catch (Exception ex) { Log.Warning("Error refreshing renewal for {host} - {@ex}", result.Binding.Host, ex); } return result; } } }
apache-2.0
C#
2ff63c6670f4e2c304a97595b21a44c52d41c314
Correct EmphasisLevel.Reduced value
timheuer/alexa-skills-dotnet
Alexa.NET/Response/Ssml/EmphasisLevel.cs
Alexa.NET/Response/Ssml/EmphasisLevel.cs
using System; namespace Alexa.NET.Response.Ssml { public static class EmphasisLevel { public const string Strong = "strong"; public const string Moderate = "moderate"; public const string Reduced = "reduced"; } }
using System; namespace Alexa.NET.Response.Ssml { public static class EmphasisLevel { public const string Strong = "strong"; public const string Moderate = "moderate"; public const string Reduced = "reducated"; } }
mit
C#
efe00e9e099215ff0dbf7d10f583c55f87816544
Improve documentation on argumentcontext
noelheesen/Ensured
Ensured/ArgumentContext.cs
Ensured/ArgumentContext.cs
namespace Ensured { using System; using System.Collections; using System.Linq.Expressions; /// <summary> /// The context in which the argument is validated. /// </summary> /// <typeparam name="T">The <see cref="Type"/> of the argument that requires validation</typeparam> public sealed class ArgumentContext<T> { #region Fields private readonly T _value; private readonly string _paramName; #endregion #region Constructors /// <summary> /// Construct a context based upon the <paramref name="expression"/> passed in. /// </summary> /// <remarks> /// The context will extract the <see cref="_paramName"/> from the expression and use it in case none is provided later /// </remarks> /// <param name="expression">An <see cref="Expression"/> that returns a value to validate</param> internal ArgumentContext(Expression<Func<T>> expression) { this._value = expression.Compile().Invoke(); if (!Equals(expression, null)) { this._paramName = ((MemberExpression)expression.Body).Member.Name; } } #endregion #region Properties /// <summary> /// Gets the value to validate /// </summary> public T Value { get { return this._value; } } #endregion #region Methods /// <summary> /// overriden to return <see cref="Value"/> instead of itself /// </summary> /// <returns><see cref="Value"/></returns> public override string ToString() { return this._value.ToString(); } #endregion } }
namespace Ensured { using System; using System.Collections; using System.Linq.Expressions; /// <summary> /// The context in which the argument is validated. /// </summary> /// <typeparam name="T">The <see cref="Type"/> of the argument that requires validation</typeparam> public sealed class ArgumentContext<T> { #region Fields private readonly T _value; private readonly string _paramName; #endregion #region Constructors /// <summary> /// Construct a context based upon an <see cref="Expression"/>. /// </summary> /// <remarks> /// The context will extract the <see cref="_paramName"/> from the expression and use it in case none is provided later. /// </remarks> /// <param name="expression">An <see cref="Expression"/> that returns a value to validate</param> internal ArgumentContext(Expression<Func<T>> expression) { this._value = expression.Compile().Invoke(); if (!Equals(expression, null)) { this._paramName = ((MemberExpression)expression.Body).Member.Name; } } #endregion #region Properties /// <summary> /// Gets the value to validate /// </summary> public T Value { get { return this._value; } } #endregion #region Methods public override string ToString() { return this._value.ToString(); } #endregion } }
mit
C#
0cf2e89ecb8b6c6dc3d87514cddfec80017bc4a9
Add GeneratorFactory
inputfalken/Sharpy
GeneratorAPI/Generator.cs
GeneratorAPI/Generator.cs
using System; using System.Collections.Generic; namespace GeneratorAPI { /// <summary> /// </summary> /// <typeparam name="TProvider"></typeparam> public class Generator<TProvider> { private readonly TProvider _provider; public Generator(TProvider provider) => _provider = provider; private IEnumerable<TResult> InfiniteEnumerable<TResult>(Func<TProvider, TResult> fn) { while (true) yield return fn(_provider); } public Generation<TResult> Generate<TResult>(Func<TProvider, TResult> fn) => new Generation<TResult>( InfiniteEnumerable(fn)); } public class Generator { public static GeneratorFactory Factory { get; } = new GeneratorFactory(); } public class GeneratorFactory { public Generator<Random> RandomGenerator(Random random) => new Generator<Random>(random); } }
using System; using System.Collections.Generic; namespace GeneratorAPI { /// <summary> /// </summary> /// <typeparam name="TProvider"></typeparam> public class Generator<TProvider> { private readonly TProvider _provider; public Generator(TProvider provider) => _provider = provider; private IEnumerable<TResult> InfiniteEnumerable<TResult>(Func<TProvider, TResult> fn) { while (true) yield return fn(_provider); } public Generation<TResult> Generate<TResult>(Func<TProvider, TResult> fn) => new Generation<TResult>( InfiniteEnumerable(fn)); } }
mit
C#
af3a4ab8a017c7522b7d4635cd142a3f8a3f30a8
Sort usings
mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee
KafkaBroker/WorkerRole.cs
KafkaBroker/WorkerRole.cs
using Microsoft.Experimental.Azure.JavaPlatform; using Microsoft.Experimental.Azure.Kafka; using Microsoft.Experimental.Azure.ZooKeeper; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Threading; namespace KafkaBroker { public class WorkerRole : RoleEntryPoint { private JavaInstaller _javaInstaller; private KafkaBrokerRunner _kafkaRunner; public override void Run() { try { _kafkaRunner.Run(); } catch (Exception ex) { UploadExceptionToBlob(ex); throw; } } public override bool OnStart() { try { InstallJava(); InstallKafka(); } catch (Exception ex) { UploadExceptionToBlob(ex); throw; } return base.OnStart(); } private void InstallJava() { _javaInstaller = new JavaInstaller(Path.Combine(InstallDirectory, "Java")); _javaInstaller.Setup(); } private void InstallKafka() { var zookeeperRole = RoleEnvironment.Roles["Zookeeper"]; var zookeeperHosts = zookeeperRole.Instances.Select(i => i.InstanceEndpoints.First().Value.IPEndpoint.Address.ToString()); var myBrokerId = Int32.Parse(RoleEnvironment.CurrentRoleInstance.Id.Split('_').Last()); _kafkaRunner = new KafkaBrokerRunner( dataDirectory: Path.Combine(DataDirectory, "Data"), configsDirectory: Path.Combine(DataDirectory, "Config"), logsDirectory: Path.Combine(DataDirectory, "Logs"), jarsDirectory: Path.Combine(InstallDirectory, "Jars"), zooKeeperHosts: zookeeperHosts, zooKeeperPort: ZooKeeperConfig.DefaultPort, brokerId: myBrokerId, javaHome: _javaInstaller.JavaHome); _kafkaRunner.Setup(); } private static string InstallDirectory { get { return RoleEnvironment.GetLocalResource("InstallDir").RootPath; } } private static string DataDirectory { get { return RoleEnvironment.GetLocalResource("DataDir").RootPath; } } private void UploadExceptionToBlob(Exception ex) { var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString")); var container = storageAccount .CreateCloudBlobClient() .GetContainerReference("logs"); container.CreateIfNotExists(); container .GetBlockBlobReference("Exception from " + RoleEnvironment.CurrentRoleInstance.Id + " on " + DateTime.Now) .UploadText(ex.ToString()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using System.IO.Compression; using Microsoft.Experimental.Azure.JavaPlatform; using System.IO; using Microsoft.Experimental.Azure.ZooKeeper; using Microsoft.Experimental.Azure.Kafka; namespace KafkaBroker { public class WorkerRole : RoleEntryPoint { private JavaInstaller _javaInstaller; private KafkaBrokerRunner _kafkaRunner; public override void Run() { try { _kafkaRunner.Run(); } catch (Exception ex) { UploadExceptionToBlob(ex); throw; } } public override bool OnStart() { try { InstallJava(); InstallKafka(); } catch (Exception ex) { UploadExceptionToBlob(ex); throw; } return base.OnStart(); } private void InstallJava() { _javaInstaller = new JavaInstaller(Path.Combine(InstallDirectory, "Java")); _javaInstaller.Setup(); } private void InstallKafka() { var zookeeperRole = RoleEnvironment.Roles["Zookeeper"]; var zookeeperHosts = zookeeperRole.Instances.Select(i => i.InstanceEndpoints.First().Value.IPEndpoint.Address.ToString()); var myBrokerId = Int32.Parse(RoleEnvironment.CurrentRoleInstance.Id.Split('_').Last()); _kafkaRunner = new KafkaBrokerRunner( dataDirectory: Path.Combine(DataDirectory, "Data"), configsDirectory: Path.Combine(DataDirectory, "Config"), logsDirectory: Path.Combine(DataDirectory, "Logs"), jarsDirectory: Path.Combine(InstallDirectory, "Jars"), zooKeeperHosts: zookeeperHosts, zooKeeperPort: ZooKeeperConfig.DefaultPort, brokerId: myBrokerId, javaHome: _javaInstaller.JavaHome); _kafkaRunner.Setup(); } private static string InstallDirectory { get { return RoleEnvironment.GetLocalResource("InstallDir").RootPath; } } private static string DataDirectory { get { return RoleEnvironment.GetLocalResource("DataDir").RootPath; } } private void UploadExceptionToBlob(Exception ex) { var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString")); var container = storageAccount .CreateCloudBlobClient() .GetContainerReference("logs"); container.CreateIfNotExists(); container .GetBlockBlobReference("Exception from " + RoleEnvironment.CurrentRoleInstance.Id + " on " + DateTime.Now) .UploadText(ex.ToString()); } } }
mit
C#
bd90e0f8cee542f6226e197aad8f2d5daa987f5c
Sort owned rooms on account page by name
18098924759/JabbR,18098924759/JabbR,mzdv/JabbR,ajayanandgit/JabbR,e10/JabbR,mzdv/JabbR,borisyankov/JabbR,yadyn/JabbR,timgranstrom/JabbR,SonOfSam/JabbR,borisyankov/JabbR,yadyn/JabbR,yadyn/JabbR,timgranstrom/JabbR,M-Zuber/JabbR,borisyankov/JabbR,e10/JabbR,JabbR/JabbR,ajayanandgit/JabbR,SonOfSam/JabbR,JabbR/JabbR,M-Zuber/JabbR
JabbR/ViewModels/ProfilePageViewModel.cs
JabbR/ViewModels/ProfilePageViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using JabbR.Models; using JabbR.Services; using SimpleAuthentication.Core; namespace JabbR.ViewModels { public class ProfilePageViewModel { public ProfilePageViewModel(ChatUser user, IEnumerable<IAuthenticationProvider> configuredProviders) { Name = user.Name; Hash = user.Hash; Active = user.Status == (int)UserStatus.Active; Status = ((UserStatus)user.Status).ToString(); Note = user.Note; AfkNote = user.AfkNote; IsAfk = user.IsAfk; Flag = user.Flag; Country = ChatService.GetCountry(user.Flag); LastActivity = user.LastActivity; IsAdmin = user.IsAdmin; SocialDetails = new SocialLoginViewModel(configuredProviders, user.Identities); HasPassword = user.HasUserNameAndPasswordCredentials(); OwnedRooms = user.OwnedRooms.OrderBy(e => e.Name).ToArray(); } public bool HasPassword { get; private set; } public string Name { get; private set; } public string Hash { get; private set; } public bool Active { get; private set; } public string Status { get; private set; } public string Note { get; private set; } public string AfkNote { get; private set; } public bool IsAfk { get; private set; } public string Flag { get; private set; } public string Country { get; private set; } public DateTime LastActivity { get; private set; } public bool IsAdmin { get; private set; } public SocialLoginViewModel SocialDetails { get; private set; } public ICollection<ChatRoom> OwnedRooms { get; private set; } } }
using System; using System.Collections.Generic; using JabbR.Models; using JabbR.Services; using SimpleAuthentication.Core; namespace JabbR.ViewModels { public class ProfilePageViewModel { public ProfilePageViewModel(ChatUser user, IEnumerable<IAuthenticationProvider> configuredProviders) { Name = user.Name; Hash = user.Hash; Active = user.Status == (int)UserStatus.Active; Status = ((UserStatus)user.Status).ToString(); Note = user.Note; AfkNote = user.AfkNote; IsAfk = user.IsAfk; Flag = user.Flag; Country = ChatService.GetCountry(user.Flag); LastActivity = user.LastActivity; IsAdmin = user.IsAdmin; SocialDetails = new SocialLoginViewModel(configuredProviders, user.Identities); HasPassword = user.HasUserNameAndPasswordCredentials(); OwnedRooms = user.OwnedRooms; } public bool HasPassword { get; private set; } public string Name { get; private set; } public string Hash { get; private set; } public bool Active { get; private set; } public string Status { get; private set; } public string Note { get; private set; } public string AfkNote { get; private set; } public bool IsAfk { get; private set; } public string Flag { get; private set; } public string Country { get; private set; } public DateTime LastActivity { get; private set; } public bool IsAdmin { get; private set; } public SocialLoginViewModel SocialDetails { get; private set; } public ICollection<ChatRoom> OwnedRooms { get; private set; } } }
mit
C#
2e23abb332efb5cfbe0661476850d9ab22f609ce
Remove unused method
pauldendulk/Mapsui,charlenni/Mapsui,charlenni/Mapsui
Mapsui/Projection/BoundingBoxIterator.cs
Mapsui/Projection/BoundingBoxIterator.cs
using System.Collections.Generic; using Mapsui.Geometries; namespace Mapsui.Projection { public static class BoundingBoxIterator { public static IEnumerable<Point> AllVertices(this BoundingBox boundingBox) { return new[] { boundingBox.Min, boundingBox.Max }; } } }
using System.Collections.Generic; using Mapsui.Geometries; namespace Mapsui.Projection { public static class BoundingBoxIterator { public static IEnumerable<Point> AllVertices(this BoundingBox boundingBox) { return new[] { boundingBox.Min, boundingBox.Max }; } public static IEnumerable<Point> GetCornerVertices(this BoundingBox boundingBox) { return new[] { boundingBox.BottomLeft, boundingBox.TopLeft, boundingBox.TopRight, boundingBox.BottomRight}; } } }
mit
C#
caa2f4a3dd5764f65c8b1953d3d70cf4463044b8
Add validation messages
ykpoh/MvcInternationalization,ykpoh/MvcInternationalization,ykpoh/MvcInternationalization
MvcInternationalization/Models/Person.cs
MvcInternationalization/Models/Person.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace MvcInternationalization.Models { public class Person { [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "NameRequired")] public string Name { get; set; } [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "AddressRequired")] public string Address { get; set; } [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "SocialNumberRequired")] public string SocialNumber { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcInternationalization.Models { public class Person { public string Name { get; set; } public string Address { get; set; } public string SocialNumber { get; set; } } }
mit
C#
11395c40b7e4586c7c3c1030bc7e36d9e51ac5d3
Add button to access first run setup on demand
peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu
osu.Game/Overlays/Settings/Sections/GeneralSection.cs
osu.Game/Overlays/Settings/Sections/GeneralSection.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { [Resolved(CanBeNull = true)] private FirstRunSetupOverlay firstRunSetupOverlay { get; set; } public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new SettingsButton { Text = "Run setup wizard", Action = () => firstRunSetupOverlay?.Show(), }, new LanguageSettings(), new UpdateSettings(), }; } } }
// 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.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new LanguageSettings(), new UpdateSettings(), }; } } }
mit
C#
7e73475dfa995c53a65bc7b8b73a022764a3060b
change description
FacturAPI/facturapi-net
facturapi-net/Properties/AssemblyInfo.cs
facturapi-net/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("Facturapi")] [assembly: AssemblyDescription("Crea Facturas Electrónicas válidas en México lo más fácil posible (CFDI)")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Facturapi")] [assembly: AssemblyProduct("Facturapi")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("Facturapi")] [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("a91d3cf3-1051-41f4-833e-c52ee8fbce20")] // 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.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("Facturapi")] [assembly: AssemblyDescription("Crea Facturas Electrónicas válidas en México")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Facturapi")] [assembly: AssemblyProduct("Facturapi")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("Facturapi")] [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("a91d3cf3-1051-41f4-833e-c52ee8fbce20")] // 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.0")]
mit
C#
977e758fdd03e63191df54a08ea2b0f751a1d70c
Add generic TouchEvent
bridgedotnet/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge
Html5/Events/TouchEvent.cs
Html5/Events/TouchEvent.cs
// The documentation for this class (on <summary> tags) was extracted from: // https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent namespace Bridge.Html5 { [External] [Name("TouchEvent")] public class TouchEvent : UIEvent { /// <summary> /// A Boolean value indicating whether or not the alt key was down when the touch event was fired. /// </summary> public readonly bool AltKey; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects representing individual points of contact whose states changed between the previous touch event and this one. /// </summary> public readonly TouchList ChangedTouches; /// <summary> /// A Boolean value indicating whether or not the control key was down when the touch event was fired. /// </summary> public readonly bool CtrlKey; /// <summary> /// A Boolean value indicating whether or not the meta key was down when the touch event was fired. /// </summary> public readonly bool MetaKey; /// <summary> /// A Boolean value indicating whether or not the shift key was down when the touch event was fired. /// </summary> public readonly bool ShiftKey; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects that are both currently in contact with the touch surface and were also started on the same element that is the target of the event. /// </summary> public readonly TouchList TargetTouches; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects representing all current points of contact with the surface, regardless of target or changed status. /// </summary> public readonly TouchList Touches; } /// <summary> /// A generic version of the TouchEvent class. The type parameter is a type of CurrentTarget. /// </summary> /// <typeparam name="TCurrentTarget">The CurrentTarget type</typeparam> [External] [Name("TouchEvent")] public class TouchEvent<TCurrentTarget> : UIEvent<TCurrentTarget> where TCurrentTarget : Element { /// <summary> /// A Boolean value indicating whether or not the alt key was down when the touch event was fired. /// </summary> public readonly bool AltKey; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects representing individual points of contact whose states changed between the previous touch event and this one. /// </summary> public readonly TouchList ChangedTouches; /// <summary> /// A Boolean value indicating whether or not the control key was down when the touch event was fired. /// </summary> public readonly bool CtrlKey; /// <summary> /// A Boolean value indicating whether or not the meta key was down when the touch event was fired. /// </summary> public readonly bool MetaKey; /// <summary> /// A Boolean value indicating whether or not the shift key was down when the touch event was fired. /// </summary> public readonly bool ShiftKey; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects that are both currently in contact with the touch surface and were also started on the same element that is the target of the event. /// </summary> public readonly TouchList TargetTouches; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects representing all current points of contact with the surface, regardless of target or changed status. /// </summary> public readonly TouchList Touches; } }
// The documentation for this class (on <summary> tags) was extracted from: // https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent using Bridge.Html5.Interfaces; namespace Bridge.Html5.Events { [External] [Name("TouchEvent")] public class TouchEvent : UIEvent { /// <summary> /// A Boolean value indicating whether or not the alt key was down when the touch event was fired. /// </summary> public readonly bool AltKey; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects representing individual points of contact whose states changed between the previous touch event and this one. /// </summary> public readonly TouchList ChangedTouches; /// <summary> /// A Boolean value indicating whether or not the control key was down when the touch event was fired. /// </summary> public readonly bool CtrlKey; /// <summary> /// A Boolean value indicating whether or not the meta key was down when the touch event was fired. /// </summary> public readonly bool MetaKey; /// <summary> /// A Boolean value indicating whether or not the shift key was down when the touch event was fired. /// </summary> public readonly bool ShiftKey; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects that are both currently in contact with the touch surface and were also started on the same element that is the target of the event. /// </summary> public readonly TouchList TargetTouches; /// <summary> /// A <see cref="TouchList"/> of all the <see cref="Touch"/> objects representing all current points of contact with the surface, regardless of target or changed status. /// </summary> public readonly TouchList Touches; } }
apache-2.0
C#
6757ee2606bdd8eedc654a8abc2915e639813ba9
Update SolutionAssemblyInfo.cs
riveryc/DimensionData.ComputeClient,DimensionDataCBUSydney/DimensionData.ComputeClient,riveryc/DimensionData.ComputeClient,DimensionDataCBUSydney/Compute.Api.Client,DimensionDataCBUSydney/DimensionData.ComputeClient,riveryc/DimensionData.ComputeClient,samuelchong/Compute.Api.Client,DimensionDataCBUSydney/DimensionData.ComputeClient
PowershellModule/SolutionAssemblyInfo.cs
PowershellModule/SolutionAssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SolutionAssemblyInfo.cs" company=""> // // </copyright> // <summary> // SolutionAssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyCompany("Dimension Data")] [assembly: AssemblyProduct("Compute as a Service (CaaS) module for Windows Powershell.")] [assembly: AssemblyCopyright("Copyright © Dimension Data 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.0.0")] [assembly: AssemblyFileVersion("3.2.0.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SolutionAssemblyInfo.cs" company=""> // // </copyright> // <summary> // SolutionAssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyCompany("Dimension Data")] [assembly: AssemblyProduct("Compute as a Service (CaaS) module for Windows Powershell.")] [assembly: AssemblyCopyright("Copyright © Dimension Data 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.1.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")]
mit
C#
113e5006c1ca538d4644ea7d63ede85043382f69
Add instructions about movimentation
ErickSimoes/EscapeMuseumVR
Assets/Scripts/UIStartInstructions.cs
Assets/Scripts/UIStartInstructions.cs
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIStartInstructions : MonoBehaviour { private Text welcomeText; private Button buttonText; private List<string> instructions = new List<string>(); private int i = 0; void Start() { welcomeText = GetComponentInChildren<Text>(); buttonText = GetComponentInChildren<Button>(); instructions.Add("Enter the museum and\nlearn about great artists"); instructions.Add("Look at the paintings\nand answer the questions"); instructions.Add("To move,\nclick on floating balls"); instructions.Add("Good luck\nand enjoy!"); } public void OnClick() { if (i < instructions.Count) { welcomeText.text = instructions[i++]; } if (i == instructions.Count) { buttonText.GetComponentInChildren<Text>().text = "START"; i++; } else if (i > instructions.Count) { GetComponentInParent<Canvas>().enabled = false; } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIStartInstructions : MonoBehaviour { private Text welcomeText; private Button buttonText; private List<string> instructions = new List<string>(); private int i = 0; void Start() { welcomeText = GetComponentInChildren<Text>(); buttonText = GetComponentInChildren<Button>(); instructions.Add("Enter the museum and\nlearn about great artists"); instructions.Add("Look at the paintings\nand answer the questions"); instructions.Add("Good luck\nand enjoy!"); } public void OnClick() { if (i < instructions.Count) { welcomeText.text = instructions[i++]; } if (i == instructions.Count) { buttonText.GetComponentInChildren<Text>().text = "START"; i++; } else if (i > instructions.Count) { GetComponentInParent<Canvas>().enabled = false; } } }
apache-2.0
C#
83350b13049b51aeb235259dffb214e287af7612
Add calc method for disposible income
mattgwagner/CertiPay.Payroll.Common
CertiPay.Payroll.Common/CalculationType.cs
CertiPay.Payroll.Common/CalculationType.cs
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4, /// <summary> /// Deduction is taken as a percentage of the disposible income (gross pay - payroll taxes) /// </summary> PercentOfDisposibleIncome } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; yield return CalculationType.PercentOfDisposibleIncome; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4 } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; } } }
mit
C#
94fb049e2518e8c1bc70790e7d124215e7c1eb7a
Correct Merge.
VenusInterns/BlogTemplate,VenusInterns/BlogTemplate,VenusInterns/BlogTemplate
BlogTemplate/Pages/Post.cshtml.cs
BlogTemplate/Pages/Post.cshtml.cs
using System; using System.ComponentModel.DataAnnotations; using BlogTemplate._1.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace BlogTemplate._1.Pages { public class PostModel : PageModel { private readonly BlogDataStore _dataStore; public PostModel(BlogDataStore dataStore) { _dataStore = dataStore; } const int MaxAllowedComments = 100; [BindProperty] public CommentViewModel NewComment { get; set; } public bool IsCommentsFull => Post.Comments.Count >= MaxAllowedComments; public Post Post { get; set; } public void OnGet([FromRoute] int id) { Post = _dataStore.GetPost(id); if (Post == null) { RedirectToPage("/Index"); } } [ValidateAntiForgeryToken] public IActionResult OnPostPublishComment([FromRoute] int id) { Post = _dataStore.GetPost(id); if (Post == null) { RedirectToPage("/Index"); } else if (ModelState.IsValid) { Comment comment = new Comment { AuthorName = NewComment.AuthorName, Body = NewComment.Body, }; comment.IsPublic = true; comment.UniqueId = Guid.NewGuid(); Post.Comments.Add(comment); _dataStore.SavePost(Post); return Redirect("/post/" + id + "/" + Post.Slug); } return Page(); } public class CommentViewModel { [Required] [MaxLength(100, ErrorMessage = "You have exceeded the maximum length of 100 characters")] public string AuthorName { get; set; } [Required] [MaxLength(1000, ErrorMessage = "You have exceeded the maximum length of 1000 characters")] public string Body { get; set; } } } }
using System; using System.ComponentModel.DataAnnotations; using BlogTemplate._1.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace BlogTemplate._1.Pages { public class PostModel : PageModel { private readonly BlogDataStore _dataStore; public PostModel(BlogDataStore dataStore) { _dataStore = dataStore; } const int MaxAllowedComments = 100; [BindProperty] public CommentViewModel NewComment { get; set; } public bool IsCommentsFull => Post.Comments.Count >= MaxAllowedComments; public Post Post { get; set; } public void OnGet([FromRoute] int id) { Post = _dataStore.GetPost(id); if (Post == null) { RedirectToPage("/Index"); } } [ValidateAntiForgeryToken] public IActionResult OnPostPublishComment([FromRoute] int id) { Post = _dataStore.GetPost(id); if (Post == null) { RedirectToPage("/Index"); } else if (ModelState.IsValid) { Comment comment = new Comment { AuthorName = NewComment.AuthorName, Body = NewComment.Body, }; comment.IsPublic = true; comment.UniqueId = Guid.NewGuid(); Post.Comments.Add(comment); _dataStore.SavePost(Post); return Redirect("/post/" + id + "/" + Post.Slug); } return Page(); } public class CommentViewModel { [Required] [MaxLength(100, ErrorMessage = "You have exceeded the maximum length of 100 characters")] public string AuthorName { get; set; } [Required] [MaxLength(1000, ErrorMessage = "You have exceeded the maximum length of 1000 characters")] public string Body { get; set; } } } }
mit
C#
5b5fa08aa977e97d5588d1baa39fa98b792fe856
Remove serializable
julesbriquet/PostCredit
Game/Assets/Scripts/shooter/playerShip.cs
Game/Assets/Scripts/shooter/playerShip.cs
using UnityEngine; using System.Collections; public class PlayerShip : MonoBehaviour { public int playerNumber = 1; private string InputPlayerString = ""; private bool enableControl; private float inputY; public float speed; private Vector2 velocity; public float yMax; public GunEntity gun; // Use this for initialization void Start () { //Time.timeScale = 1.3f; } // Update is called once per frame void Update () { /* * HANDLING MULTIPLAYER */ if (playerNumber == 1) { InputPlayerString = "_P1"; } if (playerNumber == 2) { InputPlayerString = "_P2"; } /* * MOVING PART */ float inputY = Input.GetAxis("Vertical" + InputPlayerString); velocity = new Vector2(0, speed * inputY) * Time.deltaTime; rigidbody2D.velocity = velocity; ScreenLimitControl(); /* * SHOOTING PART */ bool triggerShoot = false; triggerShoot = Input.GetButton("Action" + InputPlayerString); if (triggerShoot) { // TODO gun.Shoot(playerNumber); } } // AVOID GOING OFF SCREEN void ScreenLimitControl() { float yMin = -yMax; rigidbody2D.position = new Vector2(rigidbody2D.position.x, Mathf.Clamp(rigidbody2D.position.y, yMin, yMax)); } }
using UnityEngine; using System.Collections; [System.Serializable] public class PlayerShip : MonoBehaviour { public int playerNumber = 1; private string InputPlayerString = ""; private bool enableControl; private float inputY; public float speed; private Vector2 velocity; public float yMax; public GunEntity gun; // Use this for initialization void Start () { //Time.timeScale = 1.3f; } // Update is called once per frame void Update () { /* * HANDLING MULTIPLAYER */ if (playerNumber == 1) { InputPlayerString = "_P1"; } if (playerNumber == 2) { InputPlayerString = "_P2"; } /* * MOVING PART */ float inputY = Input.GetAxis("Vertical" + InputPlayerString); velocity = new Vector2(0, speed * inputY) * Time.deltaTime; rigidbody2D.velocity = velocity; ScreenLimitControl(); /* * SHOOTING PART */ bool triggerShoot = false; triggerShoot = Input.GetButton("Action" + InputPlayerString); if (triggerShoot) { // TODO gun.Shoot(playerNumber); } } // AVOID GOING OFF SCREEN void ScreenLimitControl() { float yMin = -yMax; rigidbody2D.position = new Vector2(rigidbody2D.position.x, Mathf.Clamp(rigidbody2D.position.y, yMin, yMax)); } }
mit
C#
f7048e07d41a53af29f4d48ace8a7831f630c9c9
fix a problem with how the values are deserialized
marinoscar/TrackingApp
Code/TrackingApp.Droid/ApiRequestor.cs
Code/TrackingApp.Droid/ApiRequestor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using RestSharp; using System.Net; using Newtonsoft.Json; namespace TrackingApp.Droid { public class ApiRequestor { public ApiResult<T> Execute<T>(IRestClient client, IRestRequest request) where T : new() { return Execute<T>(client, request, null); } public ApiResult<T> Execute<T>(IRestClient client, IRestRequest request, Action<T, IRestResponse> validation) where T : new() { return Execute<T>(client, request, HttpStatusCode.OK, validation); } public ApiResult<T> Execute<T>(IRestClient client, IRestRequest request, HttpStatusCode expectedResult, Action<T, IRestResponse> validation) where T : new() { var result = new ApiResult<T>(); IRestResponse response = null; try { response = client.Execute(request); result.Message = response.StatusDescription; if (response.StatusCode != expectedResult) { result.HasErrors = true; result.Result = default(T); } else { result.Result = JsonConvert .DeserializeObject<T>(response.Content, new JsonSerializerSettings() { EqualityComparer = StringComparer.CurrentCultureIgnoreCase }); } } catch (Exception ex) { result.HasErrors = true; result.Exception = ex; if (response != null) result.Message = response.StatusDescription; } validation?.Invoke(result.Result, response); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using RestSharp; using System.Net; using Newtonsoft.Json; namespace TrackingApp.Droid { public class ApiRequestor { public ApiResult<T> Execute<T>(IRestClient client, IRestRequest request) where T : new() { return Execute<T>(client, request, null); } public ApiResult<T> Execute<T>(IRestClient client, IRestRequest request, Action<T, IRestResponse> validation) where T : new() { return Execute<T>(client, request, HttpStatusCode.OK, validation); } public ApiResult<T> Execute<T>(IRestClient client, IRestRequest request, HttpStatusCode expectedResult, Action<T, IRestResponse> validation) where T : new() { var result = new ApiResult<T>(); IRestResponse response = null; try { response = client.Execute(request); result.Message = response.StatusDescription; if (response.StatusCode != expectedResult) { result.HasErrors = true; result.Result = default(T); } else { result.Result = JsonConvert .DeserializeObject<List<T>>(response.Content, new JsonSerializerSettings() { EqualityComparer = StringComparer.CurrentCultureIgnoreCase }) .FirstOrDefault(); } } catch (Exception ex) { result.HasErrors = true; result.Exception = ex; if (response != null) result.Message = response.StatusDescription; } validation?.Invoke(result.Result, response); return result; } } }
mit
C#
1a6477318f3bd2842a994612f9f57f772698f313
Fix issue #390. Remove ImageLoadInformation from WinRT/WP8 builds
davidlee80/SharpDX-1,Ixonos-USA/SharpDX,TechPriest/SharpDX,shoelzer/SharpDX,dazerdude/SharpDX,sharpdx/SharpDX,TechPriest/SharpDX,RobyDX/SharpDX,dazerdude/SharpDX,jwollen/SharpDX,sharpdx/SharpDX,andrewst/SharpDX,RobyDX/SharpDX,Ixonos-USA/SharpDX,jwollen/SharpDX,VirusFree/SharpDX,PavelBrokhman/SharpDX,sharpdx/SharpDX,TigerKO/SharpDX,andrewst/SharpDX,TechPriest/SharpDX,jwollen/SharpDX,manu-silicon/SharpDX,wyrover/SharpDX,VirusFree/SharpDX,dazerdude/SharpDX,shoelzer/SharpDX,VirusFree/SharpDX,manu-silicon/SharpDX,shoelzer/SharpDX,mrvux/SharpDX,manu-silicon/SharpDX,TigerKO/SharpDX,shoelzer/SharpDX,PavelBrokhman/SharpDX,wyrover/SharpDX,TigerKO/SharpDX,waltdestler/SharpDX,mrvux/SharpDX,fmarrabal/SharpDX,Ixonos-USA/SharpDX,fmarrabal/SharpDX,weltkante/SharpDX,fmarrabal/SharpDX,weltkante/SharpDX,PavelBrokhman/SharpDX,weltkante/SharpDX,andrewst/SharpDX,davidlee80/SharpDX-1,Ixonos-USA/SharpDX,davidlee80/SharpDX-1,wyrover/SharpDX,manu-silicon/SharpDX,VirusFree/SharpDX,RobyDX/SharpDX,waltdestler/SharpDX,waltdestler/SharpDX,TechPriest/SharpDX,mrvux/SharpDX,PavelBrokhman/SharpDX,wyrover/SharpDX,weltkante/SharpDX,shoelzer/SharpDX,davidlee80/SharpDX-1,dazerdude/SharpDX,fmarrabal/SharpDX,RobyDX/SharpDX,jwollen/SharpDX,TigerKO/SharpDX,waltdestler/SharpDX
Source/SharpDX.Direct3D11/ImageLoadInformation.cs
Source/SharpDX.Direct3D11/ImageLoadInformation.cs
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !W8CORE using System; namespace SharpDX.Direct3D11 { public partial struct ImageLoadInformation { /// <summary> /// The default value for load options. /// </summary> public const int FileDefaultValue = -1; /// <summary> /// Gets an ImageLoadInformation that is setup with all default values (<see cref="FileDefaultValue"/>). /// </summary> public static readonly ImageLoadInformation Default = GetDefault(); private static ImageLoadInformation GetDefault() { var value = default(ImageLoadInformation); unsafe { Utilities.ClearMemory(new IntPtr(&value), 0xFF, Utilities.SizeOf<ImageLoadInformation>()); } return value; } } } #endif
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace SharpDX.Direct3D11 { public partial struct ImageLoadInformation { /// <summary> /// The default value for load options. /// </summary> public const int FileDefaultValue = -1; /// <summary> /// Gets an ImageLoadInformation that is setup with all default values (<see cref="FileDefaultValue"/>). /// </summary> public static readonly ImageLoadInformation Default = GetDefault(); private static ImageLoadInformation GetDefault() { var value = default(ImageLoadInformation); unsafe { Utilities.ClearMemory(new IntPtr(&value), 0xFF, Utilities.SizeOf<ImageLoadInformation>()); } return value; } } }
mit
C#